View.java revision f87ec6a64484e263e66795f24faea73b3620cacb
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.RevealAnimator;
21import android.animation.StateListAnimator;
22import android.animation.ValueAnimator;
23import android.annotation.IntDef;
24import android.annotation.NonNull;
25import android.annotation.Nullable;
26import android.content.ClipData;
27import android.content.Context;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.content.res.TypedArray;
31import android.graphics.Bitmap;
32import android.graphics.Canvas;
33import android.graphics.Insets;
34import android.graphics.Interpolator;
35import android.graphics.LinearGradient;
36import android.graphics.Matrix;
37import android.graphics.Outline;
38import android.graphics.Paint;
39import android.graphics.PixelFormat;
40import android.graphics.Point;
41import android.graphics.PorterDuff;
42import android.graphics.PorterDuffXfermode;
43import android.graphics.Rect;
44import android.graphics.RectF;
45import android.graphics.Region;
46import android.graphics.Shader;
47import android.graphics.drawable.ColorDrawable;
48import android.graphics.drawable.Drawable;
49import android.hardware.display.DisplayManagerGlobal;
50import android.os.Bundle;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.Parcel;
54import android.os.Parcelable;
55import android.os.RemoteException;
56import android.os.SystemClock;
57import android.os.SystemProperties;
58import android.text.TextUtils;
59import android.util.AttributeSet;
60import android.util.FloatProperty;
61import android.util.LayoutDirection;
62import android.util.Log;
63import android.util.LongSparseLongArray;
64import android.util.Pools.SynchronizedPool;
65import android.util.Property;
66import android.util.SparseArray;
67import android.util.SuperNotCalledException;
68import android.util.TypedValue;
69import android.view.ContextMenu.ContextMenuInfo;
70import android.view.AccessibilityIterators.TextSegmentIterator;
71import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
72import android.view.AccessibilityIterators.WordTextSegmentIterator;
73import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
74import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityEventSource;
76import android.view.accessibility.AccessibilityManager;
77import android.view.accessibility.AccessibilityNodeInfo;
78import android.view.accessibility.AccessibilityNodeProvider;
79import android.view.animation.Animation;
80import android.view.animation.AnimationUtils;
81import android.view.animation.Transformation;
82import android.view.inputmethod.EditorInfo;
83import android.view.inputmethod.InputConnection;
84import android.view.inputmethod.InputMethodManager;
85import android.widget.ScrollBarDrawable;
86
87import static android.os.Build.VERSION_CODES.*;
88import static java.lang.Math.max;
89
90import com.android.internal.R;
91import com.android.internal.util.Predicate;
92import com.android.internal.view.menu.MenuBuilder;
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 gurantee 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_viewName
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     * Ignore the clipBounds of this view for the children.
726     */
727    static boolean sIgnoreClipBoundsForChildren = false;
728
729    /**
730     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
731     * calling setFlags.
732     */
733    private static final int NOT_FOCUSABLE = 0x00000000;
734
735    /**
736     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
737     * setFlags.
738     */
739    private static final int FOCUSABLE = 0x00000001;
740
741    /**
742     * Mask for use with setFlags indicating bits used for focus.
743     */
744    private static final int FOCUSABLE_MASK = 0x00000001;
745
746    /**
747     * This view will adjust its padding to fit sytem windows (e.g. status bar)
748     */
749    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
750
751    /** @hide */
752    @IntDef({VISIBLE, INVISIBLE, GONE})
753    @Retention(RetentionPolicy.SOURCE)
754    public @interface Visibility {}
755
756    /**
757     * This view is visible.
758     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
759     * android:visibility}.
760     */
761    public static final int VISIBLE = 0x00000000;
762
763    /**
764     * This view is invisible, but it still takes up space for layout purposes.
765     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
766     * android:visibility}.
767     */
768    public static final int INVISIBLE = 0x00000004;
769
770    /**
771     * This view is invisible, and it doesn't take any space for layout
772     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
773     * android:visibility}.
774     */
775    public static final int GONE = 0x00000008;
776
777    /**
778     * Mask for use with setFlags indicating bits used for visibility.
779     * {@hide}
780     */
781    static final int VISIBILITY_MASK = 0x0000000C;
782
783    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
784
785    /**
786     * This view is enabled. Interpretation varies by subclass.
787     * Use with ENABLED_MASK when calling setFlags.
788     * {@hide}
789     */
790    static final int ENABLED = 0x00000000;
791
792    /**
793     * This view is disabled. Interpretation varies by subclass.
794     * Use with ENABLED_MASK when calling setFlags.
795     * {@hide}
796     */
797    static final int DISABLED = 0x00000020;
798
799   /**
800    * Mask for use with setFlags indicating bits used for indicating whether
801    * this view is enabled
802    * {@hide}
803    */
804    static final int ENABLED_MASK = 0x00000020;
805
806    /**
807     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
808     * called and further optimizations will be performed. It is okay to have
809     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
810     * {@hide}
811     */
812    static final int WILL_NOT_DRAW = 0x00000080;
813
814    /**
815     * Mask for use with setFlags indicating bits used for indicating whether
816     * this view is will draw
817     * {@hide}
818     */
819    static final int DRAW_MASK = 0x00000080;
820
821    /**
822     * <p>This view doesn't show scrollbars.</p>
823     * {@hide}
824     */
825    static final int SCROLLBARS_NONE = 0x00000000;
826
827    /**
828     * <p>This view shows horizontal scrollbars.</p>
829     * {@hide}
830     */
831    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
832
833    /**
834     * <p>This view shows vertical scrollbars.</p>
835     * {@hide}
836     */
837    static final int SCROLLBARS_VERTICAL = 0x00000200;
838
839    /**
840     * <p>Mask for use with setFlags indicating bits used for indicating which
841     * scrollbars are enabled.</p>
842     * {@hide}
843     */
844    static final int SCROLLBARS_MASK = 0x00000300;
845
846    /**
847     * Indicates that the view should filter touches when its window is obscured.
848     * Refer to the class comments for more information about this security feature.
849     * {@hide}
850     */
851    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
852
853    /**
854     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
855     * that they are optional and should be skipped if the window has
856     * requested system UI flags that ignore those insets for layout.
857     */
858    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
859
860    /**
861     * <p>This view doesn't show fading edges.</p>
862     * {@hide}
863     */
864    static final int FADING_EDGE_NONE = 0x00000000;
865
866    /**
867     * <p>This view shows horizontal fading edges.</p>
868     * {@hide}
869     */
870    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
871
872    /**
873     * <p>This view shows vertical fading edges.</p>
874     * {@hide}
875     */
876    static final int FADING_EDGE_VERTICAL = 0x00002000;
877
878    /**
879     * <p>Mask for use with setFlags indicating bits used for indicating which
880     * fading edges are enabled.</p>
881     * {@hide}
882     */
883    static final int FADING_EDGE_MASK = 0x00003000;
884
885    /**
886     * <p>Indicates this view can be clicked. When clickable, a View reacts
887     * to clicks by notifying the OnClickListener.<p>
888     * {@hide}
889     */
890    static final int CLICKABLE = 0x00004000;
891
892    /**
893     * <p>Indicates this view is caching its drawing into a bitmap.</p>
894     * {@hide}
895     */
896    static final int DRAWING_CACHE_ENABLED = 0x00008000;
897
898    /**
899     * <p>Indicates that no icicle should be saved for this view.<p>
900     * {@hide}
901     */
902    static final int SAVE_DISABLED = 0x000010000;
903
904    /**
905     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
906     * property.</p>
907     * {@hide}
908     */
909    static final int SAVE_DISABLED_MASK = 0x000010000;
910
911    /**
912     * <p>Indicates that no drawing cache should ever be created for this view.<p>
913     * {@hide}
914     */
915    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
916
917    /**
918     * <p>Indicates this view can take / keep focus when int touch mode.</p>
919     * {@hide}
920     */
921    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
922
923    /** @hide */
924    @Retention(RetentionPolicy.SOURCE)
925    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
926    public @interface DrawingCacheQuality {}
927
928    /**
929     * <p>Enables low quality mode for the drawing cache.</p>
930     */
931    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
932
933    /**
934     * <p>Enables high quality mode for the drawing cache.</p>
935     */
936    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
937
938    /**
939     * <p>Enables automatic quality mode for the drawing cache.</p>
940     */
941    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
942
943    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
944            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
945    };
946
947    /**
948     * <p>Mask for use with setFlags indicating bits used for the cache
949     * quality property.</p>
950     * {@hide}
951     */
952    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
953
954    /**
955     * <p>
956     * Indicates this view can be long clicked. When long clickable, a View
957     * reacts to long clicks by notifying the OnLongClickListener or showing a
958     * context menu.
959     * </p>
960     * {@hide}
961     */
962    static final int LONG_CLICKABLE = 0x00200000;
963
964    /**
965     * <p>Indicates that this view gets its drawable states from its direct parent
966     * and ignores its original internal states.</p>
967     *
968     * @hide
969     */
970    static final int DUPLICATE_PARENT_STATE = 0x00400000;
971
972    /** @hide */
973    @IntDef({
974        SCROLLBARS_INSIDE_OVERLAY,
975        SCROLLBARS_INSIDE_INSET,
976        SCROLLBARS_OUTSIDE_OVERLAY,
977        SCROLLBARS_OUTSIDE_INSET
978    })
979    @Retention(RetentionPolicy.SOURCE)
980    public @interface ScrollBarStyle {}
981
982    /**
983     * The scrollbar style to display the scrollbars inside the content area,
984     * without increasing the padding. The scrollbars will be overlaid with
985     * translucency on the view's content.
986     */
987    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
988
989    /**
990     * The scrollbar style to display the scrollbars inside the padded area,
991     * increasing the padding of the view. The scrollbars will not overlap the
992     * content area of the view.
993     */
994    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
995
996    /**
997     * The scrollbar style to display the scrollbars at the edge of the view,
998     * without increasing the padding. The scrollbars will be overlaid with
999     * translucency.
1000     */
1001    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1002
1003    /**
1004     * The scrollbar style to display the scrollbars at the edge of the view,
1005     * increasing the padding of the view. The scrollbars will only overlap the
1006     * background, if any.
1007     */
1008    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1009
1010    /**
1011     * Mask to check if the scrollbar style is overlay or inset.
1012     * {@hide}
1013     */
1014    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1015
1016    /**
1017     * Mask to check if the scrollbar style is inside or outside.
1018     * {@hide}
1019     */
1020    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1021
1022    /**
1023     * Mask for scrollbar style.
1024     * {@hide}
1025     */
1026    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1027
1028    /**
1029     * View flag indicating that the screen should remain on while the
1030     * window containing this view is visible to the user.  This effectively
1031     * takes care of automatically setting the WindowManager's
1032     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1033     */
1034    public static final int KEEP_SCREEN_ON = 0x04000000;
1035
1036    /**
1037     * View flag indicating whether this view should have sound effects enabled
1038     * for events such as clicking and touching.
1039     */
1040    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1041
1042    /**
1043     * View flag indicating whether this view should have haptic feedback
1044     * enabled for events such as long presses.
1045     */
1046    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1047
1048    /**
1049     * <p>Indicates that the view hierarchy should stop saving state when
1050     * it reaches this view.  If state saving is initiated immediately at
1051     * the view, it will be allowed.
1052     * {@hide}
1053     */
1054    static final int PARENT_SAVE_DISABLED = 0x20000000;
1055
1056    /**
1057     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1058     * {@hide}
1059     */
1060    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1061
1062    /** @hide */
1063    @IntDef(flag = true,
1064            value = {
1065                FOCUSABLES_ALL,
1066                FOCUSABLES_TOUCH_MODE
1067            })
1068    @Retention(RetentionPolicy.SOURCE)
1069    public @interface FocusableMode {}
1070
1071    /**
1072     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1073     * should add all focusable Views regardless if they are focusable in touch mode.
1074     */
1075    public static final int FOCUSABLES_ALL = 0x00000000;
1076
1077    /**
1078     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1079     * should add only Views focusable in touch mode.
1080     */
1081    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1082
1083    /** @hide */
1084    @IntDef({
1085            FOCUS_BACKWARD,
1086            FOCUS_FORWARD,
1087            FOCUS_LEFT,
1088            FOCUS_UP,
1089            FOCUS_RIGHT,
1090            FOCUS_DOWN
1091    })
1092    @Retention(RetentionPolicy.SOURCE)
1093    public @interface FocusDirection {}
1094
1095    /** @hide */
1096    @IntDef({
1097            FOCUS_LEFT,
1098            FOCUS_UP,
1099            FOCUS_RIGHT,
1100            FOCUS_DOWN
1101    })
1102    @Retention(RetentionPolicy.SOURCE)
1103    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1104
1105    /**
1106     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1107     * item.
1108     */
1109    public static final int FOCUS_BACKWARD = 0x00000001;
1110
1111    /**
1112     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1113     * item.
1114     */
1115    public static final int FOCUS_FORWARD = 0x00000002;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus to the left.
1119     */
1120    public static final int FOCUS_LEFT = 0x00000011;
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus up.
1124     */
1125    public static final int FOCUS_UP = 0x00000021;
1126
1127    /**
1128     * Use with {@link #focusSearch(int)}. Move focus to the right.
1129     */
1130    public static final int FOCUS_RIGHT = 0x00000042;
1131
1132    /**
1133     * Use with {@link #focusSearch(int)}. Move focus down.
1134     */
1135    public static final int FOCUS_DOWN = 0x00000082;
1136
1137    /**
1138     * Bits of {@link #getMeasuredWidthAndState()} and
1139     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1140     */
1141    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1142
1143    /**
1144     * Bits of {@link #getMeasuredWidthAndState()} and
1145     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1146     */
1147    public static final int MEASURED_STATE_MASK = 0xff000000;
1148
1149    /**
1150     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1151     * for functions that combine both width and height into a single int,
1152     * such as {@link #getMeasuredState()} and the childState argument of
1153     * {@link #resolveSizeAndState(int, int, int)}.
1154     */
1155    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1156
1157    /**
1158     * Bit of {@link #getMeasuredWidthAndState()} and
1159     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1160     * is smaller that the space the view would like to have.
1161     */
1162    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1163
1164    /**
1165     * Base View state sets
1166     */
1167    // Singles
1168    /**
1169     * Indicates the view has no states set. States are used with
1170     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1171     * view depending on its state.
1172     *
1173     * @see android.graphics.drawable.Drawable
1174     * @see #getDrawableState()
1175     */
1176    protected static final int[] EMPTY_STATE_SET;
1177    /**
1178     * Indicates the view is enabled. States are used with
1179     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1180     * view depending on its state.
1181     *
1182     * @see android.graphics.drawable.Drawable
1183     * @see #getDrawableState()
1184     */
1185    protected static final int[] ENABLED_STATE_SET;
1186    /**
1187     * Indicates the view is focused. States are used with
1188     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1189     * view depending on its state.
1190     *
1191     * @see android.graphics.drawable.Drawable
1192     * @see #getDrawableState()
1193     */
1194    protected static final int[] FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is selected. States are used with
1197     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1198     * view depending on its state.
1199     *
1200     * @see android.graphics.drawable.Drawable
1201     * @see #getDrawableState()
1202     */
1203    protected static final int[] SELECTED_STATE_SET;
1204    /**
1205     * Indicates the view is pressed. States are used with
1206     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1207     * view depending on its state.
1208     *
1209     * @see android.graphics.drawable.Drawable
1210     * @see #getDrawableState()
1211     */
1212    protected static final int[] PRESSED_STATE_SET;
1213    /**
1214     * Indicates the view's window has focus. States are used with
1215     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1216     * view depending on its state.
1217     *
1218     * @see android.graphics.drawable.Drawable
1219     * @see #getDrawableState()
1220     */
1221    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1222    // Doubles
1223    /**
1224     * Indicates the view is enabled and has the focus.
1225     *
1226     * @see #ENABLED_STATE_SET
1227     * @see #FOCUSED_STATE_SET
1228     */
1229    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is enabled and selected.
1232     *
1233     * @see #ENABLED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view is enabled and that its window has focus.
1239     *
1240     * @see #ENABLED_STATE_SET
1241     * @see #WINDOW_FOCUSED_STATE_SET
1242     */
1243    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1244    /**
1245     * Indicates the view is focused and selected.
1246     *
1247     * @see #FOCUSED_STATE_SET
1248     * @see #SELECTED_STATE_SET
1249     */
1250    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1251    /**
1252     * Indicates the view has the focus and that its window has the focus.
1253     *
1254     * @see #FOCUSED_STATE_SET
1255     * @see #WINDOW_FOCUSED_STATE_SET
1256     */
1257    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1258    /**
1259     * Indicates the view is selected and that its window has the focus.
1260     *
1261     * @see #SELECTED_STATE_SET
1262     * @see #WINDOW_FOCUSED_STATE_SET
1263     */
1264    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1265    // Triples
1266    /**
1267     * Indicates the view is enabled, focused and selected.
1268     *
1269     * @see #ENABLED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #SELECTED_STATE_SET
1272     */
1273    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1274    /**
1275     * Indicates the view is enabled, focused and its window has the focus.
1276     *
1277     * @see #ENABLED_STATE_SET
1278     * @see #FOCUSED_STATE_SET
1279     * @see #WINDOW_FOCUSED_STATE_SET
1280     */
1281    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1282    /**
1283     * Indicates the view is enabled, selected and its window has the focus.
1284     *
1285     * @see #ENABLED_STATE_SET
1286     * @see #SELECTED_STATE_SET
1287     * @see #WINDOW_FOCUSED_STATE_SET
1288     */
1289    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1290    /**
1291     * Indicates the view is focused, selected and its window has the focus.
1292     *
1293     * @see #FOCUSED_STATE_SET
1294     * @see #SELECTED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is enabled, focused, selected and its window
1300     * has the focus.
1301     *
1302     * @see #ENABLED_STATE_SET
1303     * @see #FOCUSED_STATE_SET
1304     * @see #SELECTED_STATE_SET
1305     * @see #WINDOW_FOCUSED_STATE_SET
1306     */
1307    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed and its window has the focus.
1310     *
1311     * @see #PRESSED_STATE_SET
1312     * @see #WINDOW_FOCUSED_STATE_SET
1313     */
1314    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1315    /**
1316     * Indicates the view is pressed and selected.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #SELECTED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_SELECTED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed, selected and its window has the focus.
1324     *
1325     * @see #PRESSED_STATE_SET
1326     * @see #SELECTED_STATE_SET
1327     * @see #WINDOW_FOCUSED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed and focused.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, focused and its window has the focus.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #FOCUSED_STATE_SET
1342     * @see #WINDOW_FOCUSED_STATE_SET
1343     */
1344    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1345    /**
1346     * Indicates the view is pressed, focused and selected.
1347     *
1348     * @see #PRESSED_STATE_SET
1349     * @see #SELECTED_STATE_SET
1350     * @see #FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, focused, selected and its window has the focus.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #FOCUSED_STATE_SET
1358     * @see #SELECTED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is pressed and enabled.
1364     *
1365     * @see #PRESSED_STATE_SET
1366     * @see #ENABLED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_ENABLED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, enabled and its window has the focus.
1371     *
1372     * @see #PRESSED_STATE_SET
1373     * @see #ENABLED_STATE_SET
1374     * @see #WINDOW_FOCUSED_STATE_SET
1375     */
1376    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1377    /**
1378     * Indicates the view is pressed, enabled and selected.
1379     *
1380     * @see #PRESSED_STATE_SET
1381     * @see #ENABLED_STATE_SET
1382     * @see #SELECTED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled, selected and its window has the
1387     * focus.
1388     *
1389     * @see #PRESSED_STATE_SET
1390     * @see #ENABLED_STATE_SET
1391     * @see #SELECTED_STATE_SET
1392     * @see #WINDOW_FOCUSED_STATE_SET
1393     */
1394    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1395    /**
1396     * Indicates the view is pressed, enabled and focused.
1397     *
1398     * @see #PRESSED_STATE_SET
1399     * @see #ENABLED_STATE_SET
1400     * @see #FOCUSED_STATE_SET
1401     */
1402    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1403    /**
1404     * Indicates the view is pressed, enabled, focused and its window has the
1405     * focus.
1406     *
1407     * @see #PRESSED_STATE_SET
1408     * @see #ENABLED_STATE_SET
1409     * @see #FOCUSED_STATE_SET
1410     * @see #WINDOW_FOCUSED_STATE_SET
1411     */
1412    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1413    /**
1414     * Indicates the view is pressed, enabled, focused and selected.
1415     *
1416     * @see #PRESSED_STATE_SET
1417     * @see #ENABLED_STATE_SET
1418     * @see #SELECTED_STATE_SET
1419     * @see #FOCUSED_STATE_SET
1420     */
1421    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1422    /**
1423     * Indicates the view is pressed, enabled, focused, selected and its window
1424     * has the focus.
1425     *
1426     * @see #PRESSED_STATE_SET
1427     * @see #ENABLED_STATE_SET
1428     * @see #SELECTED_STATE_SET
1429     * @see #FOCUSED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1433
1434    /**
1435     * The order here is very important to {@link #getDrawableState()}
1436     */
1437    private static final int[][] VIEW_STATE_SETS;
1438
1439    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1440    static final int VIEW_STATE_SELECTED = 1 << 1;
1441    static final int VIEW_STATE_FOCUSED = 1 << 2;
1442    static final int VIEW_STATE_ENABLED = 1 << 3;
1443    static final int VIEW_STATE_PRESSED = 1 << 4;
1444    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1445    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1446    static final int VIEW_STATE_HOVERED = 1 << 7;
1447    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1448    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1449
1450    static final int[] VIEW_STATE_IDS = new int[] {
1451        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1452        R.attr.state_selected,          VIEW_STATE_SELECTED,
1453        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1454        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1455        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1456        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1457        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1458        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1459        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1460        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1461    };
1462
1463    static {
1464        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1465            throw new IllegalStateException(
1466                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1467        }
1468        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1469        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1470            int viewState = R.styleable.ViewDrawableStates[i];
1471            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1472                if (VIEW_STATE_IDS[j] == viewState) {
1473                    orderedIds[i * 2] = viewState;
1474                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1475                }
1476            }
1477        }
1478        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1479        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1480        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1481            int numBits = Integer.bitCount(i);
1482            int[] set = new int[numBits];
1483            int pos = 0;
1484            for (int j = 0; j < orderedIds.length; j += 2) {
1485                if ((i & orderedIds[j+1]) != 0) {
1486                    set[pos++] = orderedIds[j];
1487                }
1488            }
1489            VIEW_STATE_SETS[i] = set;
1490        }
1491
1492        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1493        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1494        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1495        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1497        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1498        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1499                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1500        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1502        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1504                | VIEW_STATE_FOCUSED];
1505        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1506        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1508        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1510        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1512                | VIEW_STATE_ENABLED];
1513        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1515        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1517                | VIEW_STATE_ENABLED];
1518        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1519                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1520                | VIEW_STATE_ENABLED];
1521        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1523                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1524
1525        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1526        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1527                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1528        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1530        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1531                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1532                | VIEW_STATE_PRESSED];
1533        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1534                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1535        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1537                | VIEW_STATE_PRESSED];
1538        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1539                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1540                | VIEW_STATE_PRESSED];
1541        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1542                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1543                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1544        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1545                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1546        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1547                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1548                | VIEW_STATE_PRESSED];
1549        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1550                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1551                | VIEW_STATE_PRESSED];
1552        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1553                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1554                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1555        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1556                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1557                | VIEW_STATE_PRESSED];
1558        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1559                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1560                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1561        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1562                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1563                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1564        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1565                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1566                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1567                | VIEW_STATE_PRESSED];
1568    }
1569
1570    /**
1571     * Accessibility event types that are dispatched for text population.
1572     */
1573    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1574            AccessibilityEvent.TYPE_VIEW_CLICKED
1575            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1576            | AccessibilityEvent.TYPE_VIEW_SELECTED
1577            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1578            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1579            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1580            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1581            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1582            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1583            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1584            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1585
1586    /**
1587     * Temporary Rect currently for use in setBackground().  This will probably
1588     * be extended in the future to hold our own class with more than just
1589     * a Rect. :)
1590     */
1591    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1592
1593    /**
1594     * Map used to store views' tags.
1595     */
1596    private SparseArray<Object> mKeyedTags;
1597
1598    /**
1599     * The next available accessibility id.
1600     */
1601    private static int sNextAccessibilityViewId;
1602
1603    /**
1604     * The animation currently associated with this view.
1605     * @hide
1606     */
1607    protected Animation mCurrentAnimation = null;
1608
1609    /**
1610     * Width as measured during measure pass.
1611     * {@hide}
1612     */
1613    @ViewDebug.ExportedProperty(category = "measurement")
1614    int mMeasuredWidth;
1615
1616    /**
1617     * Height as measured during measure pass.
1618     * {@hide}
1619     */
1620    @ViewDebug.ExportedProperty(category = "measurement")
1621    int mMeasuredHeight;
1622
1623    /**
1624     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1625     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1626     * its display list. This flag, used only when hw accelerated, allows us to clear the
1627     * flag while retaining this information until it's needed (at getDisplayList() time and
1628     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1629     *
1630     * {@hide}
1631     */
1632    boolean mRecreateDisplayList = false;
1633
1634    /**
1635     * The view's identifier.
1636     * {@hide}
1637     *
1638     * @see #setId(int)
1639     * @see #getId()
1640     */
1641    @ViewDebug.ExportedProperty(resolveId = true)
1642    int mID = NO_ID;
1643
1644    /**
1645     * The stable ID of this view for accessibility purposes.
1646     */
1647    int mAccessibilityViewId = NO_ID;
1648
1649    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1650
1651    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1652
1653    /**
1654     * The view's tag.
1655     * {@hide}
1656     *
1657     * @see #setTag(Object)
1658     * @see #getTag()
1659     */
1660    protected Object mTag = null;
1661
1662    // for mPrivateFlags:
1663    /** {@hide} */
1664    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1665    /** {@hide} */
1666    static final int PFLAG_FOCUSED                     = 0x00000002;
1667    /** {@hide} */
1668    static final int PFLAG_SELECTED                    = 0x00000004;
1669    /** {@hide} */
1670    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1671    /** {@hide} */
1672    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1673    /** {@hide} */
1674    static final int PFLAG_DRAWN                       = 0x00000020;
1675    /**
1676     * When this flag is set, this view is running an animation on behalf of its
1677     * children and should therefore not cancel invalidate requests, even if they
1678     * lie outside of this view's bounds.
1679     *
1680     * {@hide}
1681     */
1682    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1683    /** {@hide} */
1684    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1685    /** {@hide} */
1686    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1687    /** {@hide} */
1688    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1689    /** {@hide} */
1690    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1691    /** {@hide} */
1692    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1693    /** {@hide} */
1694    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1695    /** {@hide} */
1696    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1697
1698    private static final int PFLAG_PRESSED             = 0x00004000;
1699
1700    /** {@hide} */
1701    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1702    /**
1703     * Flag used to indicate that this view should be drawn once more (and only once
1704     * more) after its animation has completed.
1705     * {@hide}
1706     */
1707    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1708
1709    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1710
1711    /**
1712     * Indicates that the View returned true when onSetAlpha() was called and that
1713     * the alpha must be restored.
1714     * {@hide}
1715     */
1716    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1717
1718    /**
1719     * Set by {@link #setScrollContainer(boolean)}.
1720     */
1721    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1722
1723    /**
1724     * Set by {@link #setScrollContainer(boolean)}.
1725     */
1726    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1727
1728    /**
1729     * View flag indicating whether this view was invalidated (fully or partially.)
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_DIRTY                       = 0x00200000;
1734
1735    /**
1736     * View flag indicating whether this view was invalidated by an opaque
1737     * invalidate request.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1742
1743    /**
1744     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1745     *
1746     * @hide
1747     */
1748    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1749
1750    /**
1751     * Indicates whether the background is opaque.
1752     *
1753     * @hide
1754     */
1755    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1756
1757    /**
1758     * Indicates whether the scrollbars are opaque.
1759     *
1760     * @hide
1761     */
1762    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1763
1764    /**
1765     * Indicates whether the view is opaque.
1766     *
1767     * @hide
1768     */
1769    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1770
1771    /**
1772     * Indicates a prepressed state;
1773     * the short time between ACTION_DOWN and recognizing
1774     * a 'real' press. Prepressed is used to recognize quick taps
1775     * even when they are shorter than ViewConfiguration.getTapTimeout().
1776     *
1777     * @hide
1778     */
1779    private static final int PFLAG_PREPRESSED          = 0x02000000;
1780
1781    /**
1782     * Indicates whether the view is temporarily detached.
1783     *
1784     * @hide
1785     */
1786    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1787
1788    /**
1789     * Indicates that we should awaken scroll bars once attached
1790     *
1791     * @hide
1792     */
1793    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1794
1795    /**
1796     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1797     * @hide
1798     */
1799    private static final int PFLAG_HOVERED             = 0x10000000;
1800
1801    /**
1802     * no longer needed, should be reused
1803     */
1804    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1805
1806    /** {@hide} */
1807    static final int PFLAG_ACTIVATED                   = 0x40000000;
1808
1809    /**
1810     * Indicates that this view was specifically invalidated, not just dirtied because some
1811     * child view was invalidated. The flag is used to determine when we need to recreate
1812     * a view's display list (as opposed to just returning a reference to its existing
1813     * display list).
1814     *
1815     * @hide
1816     */
1817    static final int PFLAG_INVALIDATED                 = 0x80000000;
1818
1819    /**
1820     * Masks for mPrivateFlags2, as generated by dumpFlags():
1821     *
1822     * |-------|-------|-------|-------|
1823     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1824     *                                1  PFLAG2_DRAG_HOVERED
1825     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1826     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1827     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1828     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1829     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1830     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1831     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1832     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1833     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1834     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1835     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1836     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1837     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1838     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1839     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1840     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1841     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1842     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1843     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1844     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1845     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1846     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1847     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1848     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1849     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1850     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1851     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1852     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1853     *    1                              PFLAG2_PADDING_RESOLVED
1854     *   1                               PFLAG2_DRAWABLE_RESOLVED
1855     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1856     * |-------|-------|-------|-------|
1857     */
1858
1859    /**
1860     * Indicates that this view has reported that it can accept the current drag's content.
1861     * Cleared when the drag operation concludes.
1862     * @hide
1863     */
1864    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1865
1866    /**
1867     * Indicates that this view is currently directly under the drag location in a
1868     * drag-and-drop operation involving content that it can accept.  Cleared when
1869     * the drag exits the view, or when the drag operation concludes.
1870     * @hide
1871     */
1872    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1873
1874    /** @hide */
1875    @IntDef({
1876        LAYOUT_DIRECTION_LTR,
1877        LAYOUT_DIRECTION_RTL,
1878        LAYOUT_DIRECTION_INHERIT,
1879        LAYOUT_DIRECTION_LOCALE
1880    })
1881    @Retention(RetentionPolicy.SOURCE)
1882    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1883    public @interface LayoutDir {}
1884
1885    /** @hide */
1886    @IntDef({
1887        LAYOUT_DIRECTION_LTR,
1888        LAYOUT_DIRECTION_RTL
1889    })
1890    @Retention(RetentionPolicy.SOURCE)
1891    public @interface ResolvedLayoutDir {}
1892
1893    /**
1894     * Horizontal layout direction of this view is from Left to Right.
1895     * Use with {@link #setLayoutDirection}.
1896     */
1897    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1898
1899    /**
1900     * Horizontal layout direction of this view is from Right to Left.
1901     * Use with {@link #setLayoutDirection}.
1902     */
1903    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1904
1905    /**
1906     * Horizontal layout direction of this view is inherited from its parent.
1907     * Use with {@link #setLayoutDirection}.
1908     */
1909    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1910
1911    /**
1912     * Horizontal layout direction of this view is from deduced from the default language
1913     * script for the locale. Use with {@link #setLayoutDirection}.
1914     */
1915    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1916
1917    /**
1918     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1919     * @hide
1920     */
1921    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1922
1923    /**
1924     * Mask for use with private flags indicating bits used for horizontal layout direction.
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1928
1929    /**
1930     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1931     * right-to-left direction.
1932     * @hide
1933     */
1934    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1935
1936    /**
1937     * Indicates whether the view horizontal layout direction has been resolved.
1938     * @hide
1939     */
1940    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1944     * @hide
1945     */
1946    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1947            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1948
1949    /*
1950     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1951     * flag value.
1952     * @hide
1953     */
1954    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1955            LAYOUT_DIRECTION_LTR,
1956            LAYOUT_DIRECTION_RTL,
1957            LAYOUT_DIRECTION_INHERIT,
1958            LAYOUT_DIRECTION_LOCALE
1959    };
1960
1961    /**
1962     * Default horizontal layout direction.
1963     */
1964    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1965
1966    /**
1967     * Default horizontal layout direction.
1968     * @hide
1969     */
1970    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1971
1972    /**
1973     * Text direction is inherited thru {@link ViewGroup}
1974     */
1975    public static final int TEXT_DIRECTION_INHERIT = 0;
1976
1977    /**
1978     * Text direction is using "first strong algorithm". The first strong directional character
1979     * determines the paragraph direction. If there is no strong directional character, the
1980     * paragraph direction is the view's resolved layout direction.
1981     */
1982    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1983
1984    /**
1985     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1986     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1987     * If there are neither, the paragraph direction is the view's resolved layout direction.
1988     */
1989    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1990
1991    /**
1992     * Text direction is forced to LTR.
1993     */
1994    public static final int TEXT_DIRECTION_LTR = 3;
1995
1996    /**
1997     * Text direction is forced to RTL.
1998     */
1999    public static final int TEXT_DIRECTION_RTL = 4;
2000
2001    /**
2002     * Text direction is coming from the system Locale.
2003     */
2004    public static final int TEXT_DIRECTION_LOCALE = 5;
2005
2006    /**
2007     * Default text direction is inherited
2008     */
2009    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2010
2011    /**
2012     * Default resolved text direction
2013     * @hide
2014     */
2015    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2016
2017    /**
2018     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2019     * @hide
2020     */
2021    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2022
2023    /**
2024     * Mask for use with private flags indicating bits used for text direction.
2025     * @hide
2026     */
2027    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2028            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2029
2030    /**
2031     * Array of text direction flags for mapping attribute "textDirection" to correct
2032     * flag value.
2033     * @hide
2034     */
2035    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2036            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2037            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2038            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2039            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2040            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2041            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2042    };
2043
2044    /**
2045     * Indicates whether the view text direction has been resolved.
2046     * @hide
2047     */
2048    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2049            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2050
2051    /**
2052     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2053     * @hide
2054     */
2055    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2056
2057    /**
2058     * Mask for use with private flags indicating bits used for resolved text direction.
2059     * @hide
2060     */
2061    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2062            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2063
2064    /**
2065     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2066     * @hide
2067     */
2068    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2069            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2070
2071    /** @hide */
2072    @IntDef({
2073        TEXT_ALIGNMENT_INHERIT,
2074        TEXT_ALIGNMENT_GRAVITY,
2075        TEXT_ALIGNMENT_CENTER,
2076        TEXT_ALIGNMENT_TEXT_START,
2077        TEXT_ALIGNMENT_TEXT_END,
2078        TEXT_ALIGNMENT_VIEW_START,
2079        TEXT_ALIGNMENT_VIEW_END
2080    })
2081    @Retention(RetentionPolicy.SOURCE)
2082    public @interface TextAlignment {}
2083
2084    /**
2085     * Default text alignment. The text alignment of this View is inherited from its parent.
2086     * Use with {@link #setTextAlignment(int)}
2087     */
2088    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2089
2090    /**
2091     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2092     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2093     *
2094     * Use with {@link #setTextAlignment(int)}
2095     */
2096    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2097
2098    /**
2099     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2100     *
2101     * Use with {@link #setTextAlignment(int)}
2102     */
2103    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2104
2105    /**
2106     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2107     *
2108     * Use with {@link #setTextAlignment(int)}
2109     */
2110    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2111
2112    /**
2113     * Center the paragraph, e.g. ALIGN_CENTER.
2114     *
2115     * Use with {@link #setTextAlignment(int)}
2116     */
2117    public static final int TEXT_ALIGNMENT_CENTER = 4;
2118
2119    /**
2120     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2121     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2122     *
2123     * Use with {@link #setTextAlignment(int)}
2124     */
2125    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2126
2127    /**
2128     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2129     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2130     *
2131     * Use with {@link #setTextAlignment(int)}
2132     */
2133    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2134
2135    /**
2136     * Default text alignment is inherited
2137     */
2138    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2139
2140    /**
2141     * Default resolved text alignment
2142     * @hide
2143     */
2144    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2145
2146    /**
2147      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2148      * @hide
2149      */
2150    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2151
2152    /**
2153      * Mask for use with private flags indicating bits used for text alignment.
2154      * @hide
2155      */
2156    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2157
2158    /**
2159     * Array of text direction flags for mapping attribute "textAlignment" to correct
2160     * flag value.
2161     * @hide
2162     */
2163    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2164            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2166            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2167            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2168            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2169            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2170            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2171    };
2172
2173    /**
2174     * Indicates whether the view text alignment has been resolved.
2175     * @hide
2176     */
2177    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2178
2179    /**
2180     * Bit shift to get the resolved text alignment.
2181     * @hide
2182     */
2183    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2184
2185    /**
2186     * Mask for use with private flags indicating bits used for text alignment.
2187     * @hide
2188     */
2189    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2190            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2191
2192    /**
2193     * Indicates whether if the view text alignment has been resolved to gravity
2194     */
2195    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2196            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2197
2198    // Accessiblity constants for mPrivateFlags2
2199
2200    /**
2201     * Shift for the bits in {@link #mPrivateFlags2} related to the
2202     * "importantForAccessibility" attribute.
2203     */
2204    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2205
2206    /**
2207     * Automatically determine whether a view is important for accessibility.
2208     */
2209    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2210
2211    /**
2212     * The view is important for accessibility.
2213     */
2214    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2215
2216    /**
2217     * The view is not important for accessibility.
2218     */
2219    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2220
2221    /**
2222     * The view is not important for accessibility, nor are any of its
2223     * descendant views.
2224     */
2225    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2226
2227    /**
2228     * The default whether the view is important for accessibility.
2229     */
2230    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2231
2232    /**
2233     * Mask for obtainig the bits which specify how to determine
2234     * whether a view is important for accessibility.
2235     */
2236    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2237        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2238        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2239        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2240
2241    /**
2242     * Shift for the bits in {@link #mPrivateFlags2} related to the
2243     * "accessibilityLiveRegion" attribute.
2244     */
2245    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2246
2247    /**
2248     * Live region mode specifying that accessibility services should not
2249     * automatically announce changes to this view. This is the default live
2250     * region mode for most views.
2251     * <p>
2252     * Use with {@link #setAccessibilityLiveRegion(int)}.
2253     */
2254    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2255
2256    /**
2257     * Live region mode specifying that accessibility services should announce
2258     * changes to this view.
2259     * <p>
2260     * Use with {@link #setAccessibilityLiveRegion(int)}.
2261     */
2262    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2263
2264    /**
2265     * Live region mode specifying that accessibility services should interrupt
2266     * ongoing speech to immediately announce changes to this view.
2267     * <p>
2268     * Use with {@link #setAccessibilityLiveRegion(int)}.
2269     */
2270    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2271
2272    /**
2273     * The default whether the view is important for accessibility.
2274     */
2275    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2276
2277    /**
2278     * Mask for obtaining the bits which specify a view's accessibility live
2279     * region mode.
2280     */
2281    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2282            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2283            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2284
2285    /**
2286     * Flag indicating whether a view has accessibility focus.
2287     */
2288    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2289
2290    /**
2291     * Flag whether the accessibility state of the subtree rooted at this view changed.
2292     */
2293    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2294
2295    /**
2296     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2297     * is used to check whether later changes to the view's transform should invalidate the
2298     * view to force the quickReject test to run again.
2299     */
2300    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2301
2302    /**
2303     * Flag indicating that start/end padding has been resolved into left/right padding
2304     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2305     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2306     * during measurement. In some special cases this is required such as when an adapter-based
2307     * view measures prospective children without attaching them to a window.
2308     */
2309    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2310
2311    /**
2312     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2313     */
2314    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2315
2316    /**
2317     * Indicates that the view is tracking some sort of transient state
2318     * that the app should not need to be aware of, but that the framework
2319     * should take special care to preserve.
2320     */
2321    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2322
2323    /**
2324     * Group of bits indicating that RTL properties resolution is done.
2325     */
2326    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2327            PFLAG2_TEXT_DIRECTION_RESOLVED |
2328            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2329            PFLAG2_PADDING_RESOLVED |
2330            PFLAG2_DRAWABLE_RESOLVED;
2331
2332    // There are a couple of flags left in mPrivateFlags2
2333
2334    /* End of masks for mPrivateFlags2 */
2335
2336    /**
2337     * Masks for mPrivateFlags3, as generated by dumpFlags():
2338     *
2339     * |-------|-------|-------|-------|
2340     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2341     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2342     *                               1   PFLAG3_IS_LAID_OUT
2343     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2344     *                             1     PFLAG3_CALLED_SUPER
2345     * |-------|-------|-------|-------|
2346     */
2347
2348    /**
2349     * Flag indicating that view has a transform animation set on it. This is used to track whether
2350     * an animation is cleared between successive frames, in order to tell the associated
2351     * DisplayList to clear its animation matrix.
2352     */
2353    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2354
2355    /**
2356     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2357     * animation is cleared between successive frames, in order to tell the associated
2358     * DisplayList to restore its alpha value.
2359     */
2360    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2361
2362    /**
2363     * Flag indicating that the view has been through at least one layout since it
2364     * was last attached to a window.
2365     */
2366    static final int PFLAG3_IS_LAID_OUT = 0x4;
2367
2368    /**
2369     * Flag indicating that a call to measure() was skipped and should be done
2370     * instead when layout() is invoked.
2371     */
2372    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2373
2374    /**
2375     * Flag indicating that an overridden method correctly  called down to
2376     * the superclass implementation as required by the API spec.
2377     */
2378    static final int PFLAG3_CALLED_SUPER = 0x10;
2379
2380    /**
2381     * Flag indicating that a view's outline has been specifically defined.
2382     */
2383    static final int PFLAG3_OUTLINE_DEFINED = 0x20;
2384
2385    /**
2386     * Flag indicating that we're in the process of applying window insets.
2387     */
2388    static final int PFLAG3_APPLYING_INSETS = 0x40;
2389
2390    /**
2391     * Flag indicating that we're in the process of fitting system windows using the old method.
2392     */
2393    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2394
2395    /**
2396     * Flag indicating that nested scrolling is enabled for this view.
2397     * The view will optionally cooperate with views up its parent chain to allow for
2398     * integrated nested scrolling along the same axis.
2399     */
2400    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200;
2401
2402    /* End of masks for mPrivateFlags3 */
2403
2404    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2405
2406    /**
2407     * Always allow a user to over-scroll this view, provided it is a
2408     * view that can scroll.
2409     *
2410     * @see #getOverScrollMode()
2411     * @see #setOverScrollMode(int)
2412     */
2413    public static final int OVER_SCROLL_ALWAYS = 0;
2414
2415    /**
2416     * Allow a user to over-scroll this view only if the content is large
2417     * enough to meaningfully scroll, provided it is a view that can scroll.
2418     *
2419     * @see #getOverScrollMode()
2420     * @see #setOverScrollMode(int)
2421     */
2422    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2423
2424    /**
2425     * Never allow a user to over-scroll this view.
2426     *
2427     * @see #getOverScrollMode()
2428     * @see #setOverScrollMode(int)
2429     */
2430    public static final int OVER_SCROLL_NEVER = 2;
2431
2432    /**
2433     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2434     * requested the system UI (status bar) to be visible (the default).
2435     *
2436     * @see #setSystemUiVisibility(int)
2437     */
2438    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2439
2440    /**
2441     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2442     * system UI to enter an unobtrusive "low profile" mode.
2443     *
2444     * <p>This is for use in games, book readers, video players, or any other
2445     * "immersive" application where the usual system chrome is deemed too distracting.
2446     *
2447     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2448     *
2449     * @see #setSystemUiVisibility(int)
2450     */
2451    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2452
2453    /**
2454     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2455     * system navigation be temporarily hidden.
2456     *
2457     * <p>This is an even less obtrusive state than that called for by
2458     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2459     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2460     * those to disappear. This is useful (in conjunction with the
2461     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2462     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2463     * window flags) for displaying content using every last pixel on the display.
2464     *
2465     * <p>There is a limitation: because navigation controls are so important, the least user
2466     * interaction will cause them to reappear immediately.  When this happens, both
2467     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2468     * so that both elements reappear at the same time.
2469     *
2470     * @see #setSystemUiVisibility(int)
2471     */
2472    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2473
2474    /**
2475     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2476     * into the normal fullscreen mode so that its content can take over the screen
2477     * while still allowing the user to interact with the application.
2478     *
2479     * <p>This has the same visual effect as
2480     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2481     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2482     * meaning that non-critical screen decorations (such as the status bar) will be
2483     * hidden while the user is in the View's window, focusing the experience on
2484     * that content.  Unlike the window flag, if you are using ActionBar in
2485     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2486     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2487     * hide the action bar.
2488     *
2489     * <p>This approach to going fullscreen is best used over the window flag when
2490     * it is a transient state -- that is, the application does this at certain
2491     * points in its user interaction where it wants to allow the user to focus
2492     * on content, but not as a continuous state.  For situations where the application
2493     * would like to simply stay full screen the entire time (such as a game that
2494     * wants to take over the screen), the
2495     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2496     * is usually a better approach.  The state set here will be removed by the system
2497     * in various situations (such as the user moving to another application) like
2498     * the other system UI states.
2499     *
2500     * <p>When using this flag, the application should provide some easy facility
2501     * for the user to go out of it.  A common example would be in an e-book
2502     * reader, where tapping on the screen brings back whatever screen and UI
2503     * decorations that had been hidden while the user was immersed in reading
2504     * the book.
2505     *
2506     * @see #setSystemUiVisibility(int)
2507     */
2508    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2509
2510    /**
2511     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2512     * flags, we would like a stable view of the content insets given to
2513     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2514     * will always represent the worst case that the application can expect
2515     * as a continuous state.  In the stock Android UI this is the space for
2516     * the system bar, nav bar, and status bar, but not more transient elements
2517     * such as an input method.
2518     *
2519     * The stable layout your UI sees is based on the system UI modes you can
2520     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2521     * then you will get a stable layout for changes of the
2522     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2523     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2524     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2525     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2526     * with a stable layout.  (Note that you should avoid using
2527     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2528     *
2529     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2530     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2531     * then a hidden status bar will be considered a "stable" state for purposes
2532     * here.  This allows your UI to continually hide the status bar, while still
2533     * using the system UI flags to hide the action bar while still retaining
2534     * a stable layout.  Note that changing the window fullscreen flag will never
2535     * provide a stable layout for a clean transition.
2536     *
2537     * <p>If you are using ActionBar in
2538     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2539     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2540     * insets it adds to those given to the application.
2541     */
2542    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2543
2544    /**
2545     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2546     * to be layed out as if it has requested
2547     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2548     * allows it to avoid artifacts when switching in and out of that mode, at
2549     * the expense that some of its user interface may be covered by screen
2550     * decorations when they are shown.  You can perform layout of your inner
2551     * UI elements to account for the navigation system UI through the
2552     * {@link #fitSystemWindows(Rect)} method.
2553     */
2554    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2555
2556    /**
2557     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2558     * to be layed out as if it has requested
2559     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2560     * allows it to avoid artifacts when switching in and out of that mode, at
2561     * the expense that some of its user interface may be covered by screen
2562     * decorations when they are shown.  You can perform layout of your inner
2563     * UI elements to account for non-fullscreen system UI through the
2564     * {@link #fitSystemWindows(Rect)} method.
2565     */
2566    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2567
2568    /**
2569     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2570     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2571     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2572     * user interaction.
2573     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2574     * has an effect when used in combination with that flag.</p>
2575     */
2576    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2577
2578    /**
2579     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2580     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2581     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2582     * experience while also hiding the system bars.  If this flag is not set,
2583     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2584     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2585     * if the user swipes from the top of the screen.
2586     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2587     * system gestures, such as swiping from the top of the screen.  These transient system bars
2588     * will overlay app’s content, may have some degree of transparency, and will automatically
2589     * hide after a short timeout.
2590     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2591     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2592     * with one or both of those flags.</p>
2593     */
2594    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2595
2596    /**
2597     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2598     */
2599    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2600
2601    /**
2602     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2603     */
2604    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2605
2606    /**
2607     * @hide
2608     *
2609     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2610     * out of the public fields to keep the undefined bits out of the developer's way.
2611     *
2612     * Flag to make the status bar not expandable.  Unless you also
2613     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2614     */
2615    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
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 hide notification icons and scrolling ticker text.
2624     */
2625    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2626
2627    /**
2628     * @hide
2629     *
2630     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2631     * out of the public fields to keep the undefined bits out of the developer's way.
2632     *
2633     * Flag to disable incoming notification alerts.  This will not block
2634     * icons, but it will block sound, vibrating and other visual or aural notifications.
2635     */
2636    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2637
2638    /**
2639     * @hide
2640     *
2641     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2642     * out of the public fields to keep the undefined bits out of the developer's way.
2643     *
2644     * Flag to hide only the scrolling ticker.  Note that
2645     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2646     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2647     */
2648    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
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 the center system info area.
2657     */
2658    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2659
2660    /**
2661     * @hide
2662     *
2663     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2664     * out of the public fields to keep the undefined bits out of the developer's way.
2665     *
2666     * Flag to hide only the home button.  Don't use this
2667     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2668     */
2669    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2670
2671    /**
2672     * @hide
2673     *
2674     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2675     * out of the public fields to keep the undefined bits out of the developer's way.
2676     *
2677     * Flag to hide only the back button. Don't use this
2678     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2679     */
2680    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2681
2682    /**
2683     * @hide
2684     *
2685     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2686     * out of the public fields to keep the undefined bits out of the developer's way.
2687     *
2688     * Flag to hide only the clock.  You might use this if your activity has
2689     * its own clock making the status bar's clock redundant.
2690     */
2691    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2692
2693    /**
2694     * @hide
2695     *
2696     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2697     * out of the public fields to keep the undefined bits out of the developer's way.
2698     *
2699     * Flag to hide only the recent apps button. Don't use this
2700     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2701     */
2702    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2703
2704    /**
2705     * @hide
2706     *
2707     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2708     * out of the public fields to keep the undefined bits out of the developer's way.
2709     *
2710     * Flag to disable the global search gesture. Don't use this
2711     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2712     */
2713    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
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 status bar is displayed in transient mode.
2722     */
2723    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
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 navigation bar is displayed in transient mode.
2732     */
2733    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
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 status bar would like to be shown.
2742     */
2743    public static final int STATUS_BAR_UNHIDE = 0x10000000;
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 hidden navigation bar would like to be shown.
2752     */
2753    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
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 status bar is displayed in translucent mode.
2762     */
2763    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2764
2765    /**
2766     * @hide
2767     *
2768     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2769     * out of the public fields to keep the undefined bits out of the developer's way.
2770     *
2771     * Flag to specify that the navigation bar is displayed in translucent mode.
2772     */
2773    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2774
2775    /**
2776     * @hide
2777     *
2778     * Makes system ui transparent.
2779     */
2780    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2781
2782    /**
2783     * @hide
2784     */
2785    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00007FFF;
2786
2787    /**
2788     * These are the system UI flags that can be cleared by events outside
2789     * of an application.  Currently this is just the ability to tap on the
2790     * screen while hiding the navigation bar to have it return.
2791     * @hide
2792     */
2793    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2794            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2795            | SYSTEM_UI_FLAG_FULLSCREEN;
2796
2797    /**
2798     * Flags that can impact the layout in relation to system UI.
2799     */
2800    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2801            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2802            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2803
2804    /** @hide */
2805    @IntDef(flag = true,
2806            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2807    @Retention(RetentionPolicy.SOURCE)
2808    public @interface FindViewFlags {}
2809
2810    /**
2811     * Find views that render the specified text.
2812     *
2813     * @see #findViewsWithText(ArrayList, CharSequence, int)
2814     */
2815    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2816
2817    /**
2818     * Find find views that contain the specified content description.
2819     *
2820     * @see #findViewsWithText(ArrayList, CharSequence, int)
2821     */
2822    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2823
2824    /**
2825     * Find views that contain {@link AccessibilityNodeProvider}. Such
2826     * a View is a root of virtual view hierarchy and may contain the searched
2827     * text. If this flag is set Views with providers are automatically
2828     * added and it is a responsibility of the client to call the APIs of
2829     * the provider to determine whether the virtual tree rooted at this View
2830     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2831     * representing the virtual views with this text.
2832     *
2833     * @see #findViewsWithText(ArrayList, CharSequence, int)
2834     *
2835     * @hide
2836     */
2837    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2838
2839    /**
2840     * The undefined cursor position.
2841     *
2842     * @hide
2843     */
2844    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2845
2846    /**
2847     * Indicates that the screen has changed state and is now off.
2848     *
2849     * @see #onScreenStateChanged(int)
2850     */
2851    public static final int SCREEN_STATE_OFF = 0x0;
2852
2853    /**
2854     * Indicates that the screen has changed state and is now on.
2855     *
2856     * @see #onScreenStateChanged(int)
2857     */
2858    public static final int SCREEN_STATE_ON = 0x1;
2859
2860    /**
2861     * Indicates no axis of view scrolling.
2862     */
2863    public static final int SCROLL_AXIS_NONE = 0;
2864
2865    /**
2866     * Indicates scrolling along the horizontal axis.
2867     */
2868    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2869
2870    /**
2871     * Indicates scrolling along the vertical axis.
2872     */
2873    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2874
2875    /**
2876     * Controls the over-scroll mode for this view.
2877     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2878     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2879     * and {@link #OVER_SCROLL_NEVER}.
2880     */
2881    private int mOverScrollMode;
2882
2883    /**
2884     * The parent this view is attached to.
2885     * {@hide}
2886     *
2887     * @see #getParent()
2888     */
2889    protected ViewParent mParent;
2890
2891    /**
2892     * {@hide}
2893     */
2894    AttachInfo mAttachInfo;
2895
2896    /**
2897     * {@hide}
2898     */
2899    @ViewDebug.ExportedProperty(flagMapping = {
2900        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2901                name = "FORCE_LAYOUT"),
2902        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2903                name = "LAYOUT_REQUIRED"),
2904        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2905            name = "DRAWING_CACHE_INVALID", outputIf = false),
2906        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2907        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2908        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2909        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2910    })
2911    int mPrivateFlags;
2912    int mPrivateFlags2;
2913    int mPrivateFlags3;
2914
2915    /**
2916     * This view's request for the visibility of the status bar.
2917     * @hide
2918     */
2919    @ViewDebug.ExportedProperty(flagMapping = {
2920        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2921                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2922                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2923        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2924                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2925                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2926        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2927                                equals = SYSTEM_UI_FLAG_VISIBLE,
2928                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2929    })
2930    int mSystemUiVisibility;
2931
2932    /**
2933     * Reference count for transient state.
2934     * @see #setHasTransientState(boolean)
2935     */
2936    int mTransientStateCount = 0;
2937
2938    /**
2939     * Count of how many windows this view has been attached to.
2940     */
2941    int mWindowAttachCount;
2942
2943    /**
2944     * The layout parameters associated with this view and used by the parent
2945     * {@link android.view.ViewGroup} to determine how this view should be
2946     * laid out.
2947     * {@hide}
2948     */
2949    protected ViewGroup.LayoutParams mLayoutParams;
2950
2951    /**
2952     * The view flags hold various views states.
2953     * {@hide}
2954     */
2955    @ViewDebug.ExportedProperty
2956    int mViewFlags;
2957
2958    static class TransformationInfo {
2959        /**
2960         * The transform matrix for the View. This transform is calculated internally
2961         * based on the translation, rotation, and scale properties.
2962         *
2963         * Do *not* use this variable directly; instead call getMatrix(), which will
2964         * load the value from the View's RenderNode.
2965         */
2966        private final Matrix mMatrix = new Matrix();
2967
2968        /**
2969         * The inverse transform matrix for the View. This transform is calculated
2970         * internally based on the translation, rotation, and scale properties.
2971         *
2972         * Do *not* use this variable directly; instead call getInverseMatrix(),
2973         * which will load the value from the View's RenderNode.
2974         */
2975        private Matrix mInverseMatrix;
2976
2977        /**
2978         * The opacity of the View. This is a value from 0 to 1, where 0 means
2979         * completely transparent and 1 means completely opaque.
2980         */
2981        @ViewDebug.ExportedProperty
2982        float mAlpha = 1f;
2983
2984        /**
2985         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2986         * property only used by transitions, which is composited with the other alpha
2987         * values to calculate the final visual alpha value.
2988         */
2989        float mTransitionAlpha = 1f;
2990    }
2991
2992    TransformationInfo mTransformationInfo;
2993
2994    /**
2995     * Current clip bounds. to which all drawing of this view are constrained.
2996     */
2997    Rect mClipBounds = null;
2998
2999    private boolean mLastIsOpaque;
3000
3001    /**
3002     * The distance in pixels from the left edge of this view's parent
3003     * to the left edge of this view.
3004     * {@hide}
3005     */
3006    @ViewDebug.ExportedProperty(category = "layout")
3007    protected int mLeft;
3008    /**
3009     * The distance in pixels from the left edge of this view's parent
3010     * to the right edge of this view.
3011     * {@hide}
3012     */
3013    @ViewDebug.ExportedProperty(category = "layout")
3014    protected int mRight;
3015    /**
3016     * The distance in pixels from the top edge of this view's parent
3017     * to the top edge of this view.
3018     * {@hide}
3019     */
3020    @ViewDebug.ExportedProperty(category = "layout")
3021    protected int mTop;
3022    /**
3023     * The distance in pixels from the top edge of this view's parent
3024     * to the bottom edge of this view.
3025     * {@hide}
3026     */
3027    @ViewDebug.ExportedProperty(category = "layout")
3028    protected int mBottom;
3029
3030    /**
3031     * The offset, in pixels, by which the content of this view is scrolled
3032     * horizontally.
3033     * {@hide}
3034     */
3035    @ViewDebug.ExportedProperty(category = "scrolling")
3036    protected int mScrollX;
3037    /**
3038     * The offset, in pixels, by which the content of this view is scrolled
3039     * vertically.
3040     * {@hide}
3041     */
3042    @ViewDebug.ExportedProperty(category = "scrolling")
3043    protected int mScrollY;
3044
3045    /**
3046     * The left padding in pixels, that is the distance in pixels between the
3047     * left edge of this view and the left edge of its content.
3048     * {@hide}
3049     */
3050    @ViewDebug.ExportedProperty(category = "padding")
3051    protected int mPaddingLeft = 0;
3052    /**
3053     * The right padding in pixels, that is the distance in pixels between the
3054     * right edge of this view and the right edge of its content.
3055     * {@hide}
3056     */
3057    @ViewDebug.ExportedProperty(category = "padding")
3058    protected int mPaddingRight = 0;
3059    /**
3060     * The top padding in pixels, that is the distance in pixels between the
3061     * top edge of this view and the top edge of its content.
3062     * {@hide}
3063     */
3064    @ViewDebug.ExportedProperty(category = "padding")
3065    protected int mPaddingTop;
3066    /**
3067     * The bottom padding in pixels, that is the distance in pixels between the
3068     * bottom edge of this view and the bottom edge of its content.
3069     * {@hide}
3070     */
3071    @ViewDebug.ExportedProperty(category = "padding")
3072    protected int mPaddingBottom;
3073
3074    /**
3075     * The layout insets in pixels, that is the distance in pixels between the
3076     * visible edges of this view its bounds.
3077     */
3078    private Insets mLayoutInsets;
3079
3080    /**
3081     * Briefly describes the view and is primarily used for accessibility support.
3082     */
3083    private CharSequence mContentDescription;
3084
3085    /**
3086     * Specifies the id of a view for which this view serves as a label for
3087     * accessibility purposes.
3088     */
3089    private int mLabelForId = View.NO_ID;
3090
3091    /**
3092     * Predicate for matching labeled view id with its label for
3093     * accessibility purposes.
3094     */
3095    private MatchLabelForPredicate mMatchLabelForPredicate;
3096
3097    /**
3098     * Predicate for matching a view by its id.
3099     */
3100    private MatchIdPredicate mMatchIdPredicate;
3101
3102    /**
3103     * Cache the paddingRight set by the user to append to the scrollbar's size.
3104     *
3105     * @hide
3106     */
3107    @ViewDebug.ExportedProperty(category = "padding")
3108    protected int mUserPaddingRight;
3109
3110    /**
3111     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3112     *
3113     * @hide
3114     */
3115    @ViewDebug.ExportedProperty(category = "padding")
3116    protected int mUserPaddingBottom;
3117
3118    /**
3119     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3120     *
3121     * @hide
3122     */
3123    @ViewDebug.ExportedProperty(category = "padding")
3124    protected int mUserPaddingLeft;
3125
3126    /**
3127     * Cache the paddingStart set by the user to append to the scrollbar's size.
3128     *
3129     */
3130    @ViewDebug.ExportedProperty(category = "padding")
3131    int mUserPaddingStart;
3132
3133    /**
3134     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3135     *
3136     */
3137    @ViewDebug.ExportedProperty(category = "padding")
3138    int mUserPaddingEnd;
3139
3140    /**
3141     * Cache initial left padding.
3142     *
3143     * @hide
3144     */
3145    int mUserPaddingLeftInitial;
3146
3147    /**
3148     * Cache initial right padding.
3149     *
3150     * @hide
3151     */
3152    int mUserPaddingRightInitial;
3153
3154    /**
3155     * Default undefined padding
3156     */
3157    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3158
3159    /**
3160     * Cache if a left padding has been defined
3161     */
3162    private boolean mLeftPaddingDefined = false;
3163
3164    /**
3165     * Cache if a right padding has been defined
3166     */
3167    private boolean mRightPaddingDefined = false;
3168
3169    /**
3170     * @hide
3171     */
3172    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3173    /**
3174     * @hide
3175     */
3176    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3177
3178    private LongSparseLongArray mMeasureCache;
3179
3180    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3181    private Drawable mBackground;
3182
3183    /**
3184     * Display list 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 mBackgroundDisplayList;
3191
3192    private int mBackgroundResource;
3193    private boolean mBackgroundSizeChanged;
3194
3195    private String mViewName;
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    /**
3267     * Stores the outline of the view, passed down to the DisplayList level for
3268     * defining shadow shape.
3269     */
3270    private Outline mOutline;
3271
3272    /**
3273     * Animator that automatically runs based on state changes.
3274     */
3275    private StateListAnimator mStateListAnimator;
3276
3277    /**
3278     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3279     * the user may specify which view to go to next.
3280     */
3281    private int mNextFocusLeftId = View.NO_ID;
3282
3283    /**
3284     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3285     * the user may specify which view to go to next.
3286     */
3287    private int mNextFocusRightId = View.NO_ID;
3288
3289    /**
3290     * When this view has focus and the next focus is {@link #FOCUS_UP},
3291     * the user may specify which view to go to next.
3292     */
3293    private int mNextFocusUpId = View.NO_ID;
3294
3295    /**
3296     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3297     * the user may specify which view to go to next.
3298     */
3299    private int mNextFocusDownId = View.NO_ID;
3300
3301    /**
3302     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3303     * the user may specify which view to go to next.
3304     */
3305    int mNextFocusForwardId = View.NO_ID;
3306
3307    private CheckForLongPress mPendingCheckForLongPress;
3308    private CheckForTap mPendingCheckForTap = null;
3309    private PerformClick mPerformClick;
3310    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3311
3312    private UnsetPressedState mUnsetPressedState;
3313
3314    /**
3315     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3316     * up event while a long press is invoked as soon as the long press duration is reached, so
3317     * a long press could be performed before the tap is checked, in which case the tap's action
3318     * should not be invoked.
3319     */
3320    private boolean mHasPerformedLongPress;
3321
3322    /**
3323     * The minimum height of the view. We'll try our best to have the height
3324     * of this view to at least this amount.
3325     */
3326    @ViewDebug.ExportedProperty(category = "measurement")
3327    private int mMinHeight;
3328
3329    /**
3330     * The minimum width of the view. We'll try our best to have the width
3331     * of this view to at least this amount.
3332     */
3333    @ViewDebug.ExportedProperty(category = "measurement")
3334    private int mMinWidth;
3335
3336    /**
3337     * The delegate to handle touch events that are physically in this view
3338     * but should be handled by another view.
3339     */
3340    private TouchDelegate mTouchDelegate = null;
3341
3342    /**
3343     * Solid color to use as a background when creating the drawing cache. Enables
3344     * the cache to use 16 bit bitmaps instead of 32 bit.
3345     */
3346    private int mDrawingCacheBackgroundColor = 0;
3347
3348    /**
3349     * Special tree observer used when mAttachInfo is null.
3350     */
3351    private ViewTreeObserver mFloatingTreeObserver;
3352
3353    /**
3354     * Cache the touch slop from the context that created the view.
3355     */
3356    private int mTouchSlop;
3357
3358    /**
3359     * Object that handles automatic animation of view properties.
3360     */
3361    private ViewPropertyAnimator mAnimator = null;
3362
3363    /**
3364     * Flag indicating that a drag can cross window boundaries.  When
3365     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3366     * with this flag set, all visible applications will be able to participate
3367     * in the drag operation and receive the dragged content.
3368     *
3369     * @hide
3370     */
3371    public static final int DRAG_FLAG_GLOBAL = 1;
3372
3373    /**
3374     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3375     */
3376    private float mVerticalScrollFactor;
3377
3378    /**
3379     * Position of the vertical scroll bar.
3380     */
3381    private int mVerticalScrollbarPosition;
3382
3383    /**
3384     * Position the scroll bar at the default position as determined by the system.
3385     */
3386    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3387
3388    /**
3389     * Position the scroll bar along the left edge.
3390     */
3391    public static final int SCROLLBAR_POSITION_LEFT = 1;
3392
3393    /**
3394     * Position the scroll bar along the right edge.
3395     */
3396    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3397
3398    /**
3399     * Indicates that the view does not have a layer.
3400     *
3401     * @see #getLayerType()
3402     * @see #setLayerType(int, android.graphics.Paint)
3403     * @see #LAYER_TYPE_SOFTWARE
3404     * @see #LAYER_TYPE_HARDWARE
3405     */
3406    public static final int LAYER_TYPE_NONE = 0;
3407
3408    /**
3409     * <p>Indicates that the view has a software layer. A software layer is backed
3410     * by a bitmap and causes the view to be rendered using Android's software
3411     * rendering pipeline, even if hardware acceleration is enabled.</p>
3412     *
3413     * <p>Software layers have various usages:</p>
3414     * <p>When the application is not using hardware acceleration, a software layer
3415     * is useful to apply a specific color filter and/or blending mode and/or
3416     * translucency to a view and all its children.</p>
3417     * <p>When the application is using hardware acceleration, a software layer
3418     * is useful to render drawing primitives not supported by the hardware
3419     * accelerated pipeline. It can also be used to cache a complex view tree
3420     * into a texture and reduce the complexity of drawing operations. For instance,
3421     * when animating a complex view tree with a translation, a software layer can
3422     * be used to render the view tree only once.</p>
3423     * <p>Software layers should be avoided when the affected view tree updates
3424     * often. Every update will require to re-render the software layer, which can
3425     * potentially be slow (particularly when hardware acceleration is turned on
3426     * since the layer will have to be uploaded into a hardware texture after every
3427     * update.)</p>
3428     *
3429     * @see #getLayerType()
3430     * @see #setLayerType(int, android.graphics.Paint)
3431     * @see #LAYER_TYPE_NONE
3432     * @see #LAYER_TYPE_HARDWARE
3433     */
3434    public static final int LAYER_TYPE_SOFTWARE = 1;
3435
3436    /**
3437     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3438     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3439     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3440     * rendering pipeline, but only if hardware acceleration is turned on for the
3441     * view hierarchy. When hardware acceleration is turned off, hardware layers
3442     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3443     *
3444     * <p>A hardware layer is useful to apply a specific color filter and/or
3445     * blending mode and/or translucency to a view and all its children.</p>
3446     * <p>A hardware layer can be used to cache a complex view tree into a
3447     * texture and reduce the complexity of drawing operations. For instance,
3448     * when animating a complex view tree with a translation, a hardware layer can
3449     * be used to render the view tree only once.</p>
3450     * <p>A hardware layer can also be used to increase the rendering quality when
3451     * rotation transformations are applied on a view. It can also be used to
3452     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3453     *
3454     * @see #getLayerType()
3455     * @see #setLayerType(int, android.graphics.Paint)
3456     * @see #LAYER_TYPE_NONE
3457     * @see #LAYER_TYPE_SOFTWARE
3458     */
3459    public static final int LAYER_TYPE_HARDWARE = 2;
3460
3461    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3462            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3463            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3464            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3465    })
3466    int mLayerType = LAYER_TYPE_NONE;
3467    Paint mLayerPaint;
3468    Rect mLocalDirtyRect;
3469    private HardwareLayer mHardwareLayer;
3470
3471    /**
3472     * Set to true when drawing cache is enabled and cannot be created.
3473     *
3474     * @hide
3475     */
3476    public boolean mCachingFailed;
3477    private Bitmap mDrawingCache;
3478    private Bitmap mUnscaledDrawingCache;
3479
3480    /**
3481     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3482     * <p>
3483     * When non-null and valid, this is expected to contain an up-to-date copy
3484     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3485     * cleanup.
3486     */
3487    final RenderNode mRenderNode;
3488
3489    /**
3490     * Set to true when the view is sending hover accessibility events because it
3491     * is the innermost hovered view.
3492     */
3493    private boolean mSendingHoverAccessibilityEvents;
3494
3495    /**
3496     * Delegate for injecting accessibility functionality.
3497     */
3498    AccessibilityDelegate mAccessibilityDelegate;
3499
3500    /**
3501     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3502     * and add/remove objects to/from the overlay directly through the Overlay methods.
3503     */
3504    ViewOverlay mOverlay;
3505
3506    /**
3507     * The currently active parent view for receiving delegated nested scrolling events.
3508     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3509     * by {@link #stopNestedScroll()} at the same point where we clear
3510     * requestDisallowInterceptTouchEvent.
3511     */
3512    private ViewParent mNestedScrollingParent;
3513
3514    /**
3515     * Consistency verifier for debugging purposes.
3516     * @hide
3517     */
3518    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3519            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3520                    new InputEventConsistencyVerifier(this, 0) : null;
3521
3522    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3523
3524    private int[] mTempNestedScrollConsumed;
3525
3526    /**
3527     * Simple constructor to use when creating a view from code.
3528     *
3529     * @param context The Context the view is running in, through which it can
3530     *        access the current theme, resources, etc.
3531     */
3532    public View(Context context) {
3533        mContext = context;
3534        mResources = context != null ? context.getResources() : null;
3535        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3536        // Set some flags defaults
3537        mPrivateFlags2 =
3538                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3539                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3540                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3541                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3542                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3543                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3544        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3545        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3546        mUserPaddingStart = UNDEFINED_PADDING;
3547        mUserPaddingEnd = UNDEFINED_PADDING;
3548        mRenderNode = RenderNode.create(getClass().getName());
3549
3550        if (!sCompatibilityDone && context != null) {
3551            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3552
3553            // Older apps may need this compatibility hack for measurement.
3554            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3555
3556            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3557            // of whether a layout was requested on that View.
3558            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3559
3560            // Older apps may need this to ignore the clip bounds
3561            sIgnoreClipBoundsForChildren = targetSdkVersion < L;
3562
3563            sCompatibilityDone = true;
3564        }
3565    }
3566
3567    /**
3568     * Constructor that is called when inflating a view from XML. This is called
3569     * when a view is being constructed from an XML file, supplying attributes
3570     * that were specified in the XML file. This version uses a default style of
3571     * 0, so the only attribute values applied are those in the Context's Theme
3572     * and the given AttributeSet.
3573     *
3574     * <p>
3575     * The method onFinishInflate() will be called after all children have been
3576     * added.
3577     *
3578     * @param context The Context the view is running in, through which it can
3579     *        access the current theme, resources, etc.
3580     * @param attrs The attributes of the XML tag that is inflating the view.
3581     * @see #View(Context, AttributeSet, int)
3582     */
3583    public View(Context context, AttributeSet attrs) {
3584        this(context, attrs, 0);
3585    }
3586
3587    /**
3588     * Perform inflation from XML and apply a class-specific base style from a
3589     * theme attribute. This constructor of View allows subclasses to use their
3590     * own base style when they are inflating. For example, a Button class's
3591     * constructor would call this version of the super class constructor and
3592     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3593     * allows the theme's button style to modify all of the base view attributes
3594     * (in particular its background) as well as the Button class's attributes.
3595     *
3596     * @param context The Context the view is running in, through which it can
3597     *        access the current theme, resources, etc.
3598     * @param attrs The attributes of the XML tag that is inflating the view.
3599     * @param defStyleAttr An attribute in the current theme that contains a
3600     *        reference to a style resource that supplies default values for
3601     *        the view. Can be 0 to not look for defaults.
3602     * @see #View(Context, AttributeSet)
3603     */
3604    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3605        this(context, attrs, defStyleAttr, 0);
3606    }
3607
3608    /**
3609     * Perform inflation from XML and apply a class-specific base style from a
3610     * theme attribute or style resource. This constructor of View allows
3611     * subclasses to use their own base style when they are inflating.
3612     * <p>
3613     * When determining the final value of a particular attribute, there are
3614     * four inputs that come into play:
3615     * <ol>
3616     * <li>Any attribute values in the given AttributeSet.
3617     * <li>The style resource specified in the AttributeSet (named "style").
3618     * <li>The default style specified by <var>defStyleAttr</var>.
3619     * <li>The default style specified by <var>defStyleRes</var>.
3620     * <li>The base values in this theme.
3621     * </ol>
3622     * <p>
3623     * Each of these inputs is considered in-order, with the first listed taking
3624     * precedence over the following ones. In other words, if in the
3625     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3626     * , then the button's text will <em>always</em> be black, regardless of
3627     * what is specified in any of the styles.
3628     *
3629     * @param context The Context the view is running in, through which it can
3630     *        access the current theme, resources, etc.
3631     * @param attrs The attributes of the XML tag that is inflating the view.
3632     * @param defStyleAttr An attribute in the current theme that contains a
3633     *        reference to a style resource that supplies default values for
3634     *        the view. Can be 0 to not look for defaults.
3635     * @param defStyleRes A resource identifier of a style resource that
3636     *        supplies default values for the view, used only if
3637     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3638     *        to not look for defaults.
3639     * @see #View(Context, AttributeSet, int)
3640     */
3641    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3642        this(context);
3643
3644        final TypedArray a = context.obtainStyledAttributes(
3645                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3646
3647        Drawable background = null;
3648
3649        int leftPadding = -1;
3650        int topPadding = -1;
3651        int rightPadding = -1;
3652        int bottomPadding = -1;
3653        int startPadding = UNDEFINED_PADDING;
3654        int endPadding = UNDEFINED_PADDING;
3655
3656        int padding = -1;
3657
3658        int viewFlagValues = 0;
3659        int viewFlagMasks = 0;
3660
3661        boolean setScrollContainer = false;
3662
3663        int x = 0;
3664        int y = 0;
3665
3666        float tx = 0;
3667        float ty = 0;
3668        float tz = 0;
3669        float elevation = 0;
3670        float rotation = 0;
3671        float rotationX = 0;
3672        float rotationY = 0;
3673        float sx = 1f;
3674        float sy = 1f;
3675        boolean transformSet = false;
3676
3677        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3678        int overScrollMode = mOverScrollMode;
3679        boolean initializeScrollbars = false;
3680
3681        boolean startPaddingDefined = false;
3682        boolean endPaddingDefined = false;
3683        boolean leftPaddingDefined = false;
3684        boolean rightPaddingDefined = false;
3685
3686        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3687
3688        final int N = a.getIndexCount();
3689        for (int i = 0; i < N; i++) {
3690            int attr = a.getIndex(i);
3691            switch (attr) {
3692                case com.android.internal.R.styleable.View_background:
3693                    background = a.getDrawable(attr);
3694                    break;
3695                case com.android.internal.R.styleable.View_padding:
3696                    padding = a.getDimensionPixelSize(attr, -1);
3697                    mUserPaddingLeftInitial = padding;
3698                    mUserPaddingRightInitial = padding;
3699                    leftPaddingDefined = true;
3700                    rightPaddingDefined = true;
3701                    break;
3702                 case com.android.internal.R.styleable.View_paddingLeft:
3703                    leftPadding = a.getDimensionPixelSize(attr, -1);
3704                    mUserPaddingLeftInitial = leftPadding;
3705                    leftPaddingDefined = true;
3706                    break;
3707                case com.android.internal.R.styleable.View_paddingTop:
3708                    topPadding = a.getDimensionPixelSize(attr, -1);
3709                    break;
3710                case com.android.internal.R.styleable.View_paddingRight:
3711                    rightPadding = a.getDimensionPixelSize(attr, -1);
3712                    mUserPaddingRightInitial = rightPadding;
3713                    rightPaddingDefined = true;
3714                    break;
3715                case com.android.internal.R.styleable.View_paddingBottom:
3716                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3717                    break;
3718                case com.android.internal.R.styleable.View_paddingStart:
3719                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3720                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3721                    break;
3722                case com.android.internal.R.styleable.View_paddingEnd:
3723                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3724                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3725                    break;
3726                case com.android.internal.R.styleable.View_scrollX:
3727                    x = a.getDimensionPixelOffset(attr, 0);
3728                    break;
3729                case com.android.internal.R.styleable.View_scrollY:
3730                    y = a.getDimensionPixelOffset(attr, 0);
3731                    break;
3732                case com.android.internal.R.styleable.View_alpha:
3733                    setAlpha(a.getFloat(attr, 1f));
3734                    break;
3735                case com.android.internal.R.styleable.View_transformPivotX:
3736                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3737                    break;
3738                case com.android.internal.R.styleable.View_transformPivotY:
3739                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3740                    break;
3741                case com.android.internal.R.styleable.View_translationX:
3742                    tx = a.getDimensionPixelOffset(attr, 0);
3743                    transformSet = true;
3744                    break;
3745                case com.android.internal.R.styleable.View_translationY:
3746                    ty = a.getDimensionPixelOffset(attr, 0);
3747                    transformSet = true;
3748                    break;
3749                case com.android.internal.R.styleable.View_translationZ:
3750                    tz = a.getDimensionPixelOffset(attr, 0);
3751                    transformSet = true;
3752                    break;
3753                case com.android.internal.R.styleable.View_elevation:
3754                    elevation = a.getDimensionPixelOffset(attr, 0);
3755                    transformSet = true;
3756                    break;
3757                case com.android.internal.R.styleable.View_rotation:
3758                    rotation = a.getFloat(attr, 0);
3759                    transformSet = true;
3760                    break;
3761                case com.android.internal.R.styleable.View_rotationX:
3762                    rotationX = a.getFloat(attr, 0);
3763                    transformSet = true;
3764                    break;
3765                case com.android.internal.R.styleable.View_rotationY:
3766                    rotationY = a.getFloat(attr, 0);
3767                    transformSet = true;
3768                    break;
3769                case com.android.internal.R.styleable.View_scaleX:
3770                    sx = a.getFloat(attr, 1f);
3771                    transformSet = true;
3772                    break;
3773                case com.android.internal.R.styleable.View_scaleY:
3774                    sy = a.getFloat(attr, 1f);
3775                    transformSet = true;
3776                    break;
3777                case com.android.internal.R.styleable.View_id:
3778                    mID = a.getResourceId(attr, NO_ID);
3779                    break;
3780                case com.android.internal.R.styleable.View_tag:
3781                    mTag = a.getText(attr);
3782                    break;
3783                case com.android.internal.R.styleable.View_fitsSystemWindows:
3784                    if (a.getBoolean(attr, false)) {
3785                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3786                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3787                    }
3788                    break;
3789                case com.android.internal.R.styleable.View_focusable:
3790                    if (a.getBoolean(attr, false)) {
3791                        viewFlagValues |= FOCUSABLE;
3792                        viewFlagMasks |= FOCUSABLE_MASK;
3793                    }
3794                    break;
3795                case com.android.internal.R.styleable.View_focusableInTouchMode:
3796                    if (a.getBoolean(attr, false)) {
3797                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3798                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3799                    }
3800                    break;
3801                case com.android.internal.R.styleable.View_clickable:
3802                    if (a.getBoolean(attr, false)) {
3803                        viewFlagValues |= CLICKABLE;
3804                        viewFlagMasks |= CLICKABLE;
3805                    }
3806                    break;
3807                case com.android.internal.R.styleable.View_longClickable:
3808                    if (a.getBoolean(attr, false)) {
3809                        viewFlagValues |= LONG_CLICKABLE;
3810                        viewFlagMasks |= LONG_CLICKABLE;
3811                    }
3812                    break;
3813                case com.android.internal.R.styleable.View_saveEnabled:
3814                    if (!a.getBoolean(attr, true)) {
3815                        viewFlagValues |= SAVE_DISABLED;
3816                        viewFlagMasks |= SAVE_DISABLED_MASK;
3817                    }
3818                    break;
3819                case com.android.internal.R.styleable.View_duplicateParentState:
3820                    if (a.getBoolean(attr, false)) {
3821                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3822                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3823                    }
3824                    break;
3825                case com.android.internal.R.styleable.View_visibility:
3826                    final int visibility = a.getInt(attr, 0);
3827                    if (visibility != 0) {
3828                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3829                        viewFlagMasks |= VISIBILITY_MASK;
3830                    }
3831                    break;
3832                case com.android.internal.R.styleable.View_layoutDirection:
3833                    // Clear any layout direction flags (included resolved bits) already set
3834                    mPrivateFlags2 &=
3835                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3836                    // Set the layout direction flags depending on the value of the attribute
3837                    final int layoutDirection = a.getInt(attr, -1);
3838                    final int value = (layoutDirection != -1) ?
3839                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3840                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3841                    break;
3842                case com.android.internal.R.styleable.View_drawingCacheQuality:
3843                    final int cacheQuality = a.getInt(attr, 0);
3844                    if (cacheQuality != 0) {
3845                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3846                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3847                    }
3848                    break;
3849                case com.android.internal.R.styleable.View_contentDescription:
3850                    setContentDescription(a.getString(attr));
3851                    break;
3852                case com.android.internal.R.styleable.View_labelFor:
3853                    setLabelFor(a.getResourceId(attr, NO_ID));
3854                    break;
3855                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3856                    if (!a.getBoolean(attr, true)) {
3857                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3858                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3859                    }
3860                    break;
3861                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3862                    if (!a.getBoolean(attr, true)) {
3863                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3864                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3865                    }
3866                    break;
3867                case R.styleable.View_scrollbars:
3868                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3869                    if (scrollbars != SCROLLBARS_NONE) {
3870                        viewFlagValues |= scrollbars;
3871                        viewFlagMasks |= SCROLLBARS_MASK;
3872                        initializeScrollbars = true;
3873                    }
3874                    break;
3875                //noinspection deprecation
3876                case R.styleable.View_fadingEdge:
3877                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3878                        // Ignore the attribute starting with ICS
3879                        break;
3880                    }
3881                    // With builds < ICS, fall through and apply fading edges
3882                case R.styleable.View_requiresFadingEdge:
3883                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3884                    if (fadingEdge != FADING_EDGE_NONE) {
3885                        viewFlagValues |= fadingEdge;
3886                        viewFlagMasks |= FADING_EDGE_MASK;
3887                        initializeFadingEdge(a);
3888                    }
3889                    break;
3890                case R.styleable.View_scrollbarStyle:
3891                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3892                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3893                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3894                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3895                    }
3896                    break;
3897                case R.styleable.View_isScrollContainer:
3898                    setScrollContainer = true;
3899                    if (a.getBoolean(attr, false)) {
3900                        setScrollContainer(true);
3901                    }
3902                    break;
3903                case com.android.internal.R.styleable.View_keepScreenOn:
3904                    if (a.getBoolean(attr, false)) {
3905                        viewFlagValues |= KEEP_SCREEN_ON;
3906                        viewFlagMasks |= KEEP_SCREEN_ON;
3907                    }
3908                    break;
3909                case R.styleable.View_filterTouchesWhenObscured:
3910                    if (a.getBoolean(attr, false)) {
3911                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3912                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3913                    }
3914                    break;
3915                case R.styleable.View_nextFocusLeft:
3916                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3917                    break;
3918                case R.styleable.View_nextFocusRight:
3919                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3920                    break;
3921                case R.styleable.View_nextFocusUp:
3922                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3923                    break;
3924                case R.styleable.View_nextFocusDown:
3925                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3926                    break;
3927                case R.styleable.View_nextFocusForward:
3928                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3929                    break;
3930                case R.styleable.View_minWidth:
3931                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3932                    break;
3933                case R.styleable.View_minHeight:
3934                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3935                    break;
3936                case R.styleable.View_onClick:
3937                    if (context.isRestricted()) {
3938                        throw new IllegalStateException("The android:onClick attribute cannot "
3939                                + "be used within a restricted context");
3940                    }
3941
3942                    final String handlerName = a.getString(attr);
3943                    if (handlerName != null) {
3944                        setOnClickListener(new OnClickListener() {
3945                            private Method mHandler;
3946
3947                            public void onClick(View v) {
3948                                if (mHandler == null) {
3949                                    try {
3950                                        mHandler = getContext().getClass().getMethod(handlerName,
3951                                                View.class);
3952                                    } catch (NoSuchMethodException e) {
3953                                        int id = getId();
3954                                        String idText = id == NO_ID ? "" : " with id '"
3955                                                + getContext().getResources().getResourceEntryName(
3956                                                    id) + "'";
3957                                        throw new IllegalStateException("Could not find a method " +
3958                                                handlerName + "(View) in the activity "
3959                                                + getContext().getClass() + " for onClick handler"
3960                                                + " on view " + View.this.getClass() + idText, e);
3961                                    }
3962                                }
3963
3964                                try {
3965                                    mHandler.invoke(getContext(), View.this);
3966                                } catch (IllegalAccessException e) {
3967                                    throw new IllegalStateException("Could not execute non "
3968                                            + "public method of the activity", e);
3969                                } catch (InvocationTargetException e) {
3970                                    throw new IllegalStateException("Could not execute "
3971                                            + "method of the activity", e);
3972                                }
3973                            }
3974                        });
3975                    }
3976                    break;
3977                case R.styleable.View_overScrollMode:
3978                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3979                    break;
3980                case R.styleable.View_verticalScrollbarPosition:
3981                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3982                    break;
3983                case R.styleable.View_layerType:
3984                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3985                    break;
3986                case R.styleable.View_textDirection:
3987                    // Clear any text direction flag already set
3988                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3989                    // Set the text direction flags depending on the value of the attribute
3990                    final int textDirection = a.getInt(attr, -1);
3991                    if (textDirection != -1) {
3992                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3993                    }
3994                    break;
3995                case R.styleable.View_textAlignment:
3996                    // Clear any text alignment flag already set
3997                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3998                    // Set the text alignment flag depending on the value of the attribute
3999                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4000                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4001                    break;
4002                case R.styleable.View_importantForAccessibility:
4003                    setImportantForAccessibility(a.getInt(attr,
4004                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4005                    break;
4006                case R.styleable.View_accessibilityLiveRegion:
4007                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4008                    break;
4009                case R.styleable.View_viewName:
4010                    setViewName(a.getString(attr));
4011                    break;
4012                case R.styleable.View_nestedScrollingEnabled:
4013                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4014                    break;
4015                case R.styleable.View_stateListAnimator:
4016                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4017                            a.getResourceId(attr, 0)));
4018                    break;
4019            }
4020        }
4021
4022        setOverScrollMode(overScrollMode);
4023
4024        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4025        // the resolved layout direction). Those cached values will be used later during padding
4026        // resolution.
4027        mUserPaddingStart = startPadding;
4028        mUserPaddingEnd = endPadding;
4029
4030        if (background != null) {
4031            setBackground(background);
4032        }
4033
4034        // setBackground above will record that padding is currently provided by the background.
4035        // If we have padding specified via xml, record that here instead and use it.
4036        mLeftPaddingDefined = leftPaddingDefined;
4037        mRightPaddingDefined = rightPaddingDefined;
4038
4039        if (padding >= 0) {
4040            leftPadding = padding;
4041            topPadding = padding;
4042            rightPadding = padding;
4043            bottomPadding = padding;
4044            mUserPaddingLeftInitial = padding;
4045            mUserPaddingRightInitial = padding;
4046        }
4047
4048        if (isRtlCompatibilityMode()) {
4049            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4050            // left / right padding are used if defined (meaning here nothing to do). If they are not
4051            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4052            // start / end and resolve them as left / right (layout direction is not taken into account).
4053            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4054            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4055            // defined.
4056            if (!mLeftPaddingDefined && startPaddingDefined) {
4057                leftPadding = startPadding;
4058            }
4059            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4060            if (!mRightPaddingDefined && endPaddingDefined) {
4061                rightPadding = endPadding;
4062            }
4063            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4064        } else {
4065            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4066            // values defined. Otherwise, left /right values are used.
4067            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4068            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4069            // defined.
4070            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4071
4072            if (mLeftPaddingDefined && !hasRelativePadding) {
4073                mUserPaddingLeftInitial = leftPadding;
4074            }
4075            if (mRightPaddingDefined && !hasRelativePadding) {
4076                mUserPaddingRightInitial = rightPadding;
4077            }
4078        }
4079
4080        internalSetPadding(
4081                mUserPaddingLeftInitial,
4082                topPadding >= 0 ? topPadding : mPaddingTop,
4083                mUserPaddingRightInitial,
4084                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4085
4086        if (viewFlagMasks != 0) {
4087            setFlags(viewFlagValues, viewFlagMasks);
4088        }
4089
4090        if (initializeScrollbars) {
4091            initializeScrollbars(a);
4092        }
4093
4094        a.recycle();
4095
4096        // Needs to be called after mViewFlags is set
4097        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4098            recomputePadding();
4099        }
4100
4101        if (x != 0 || y != 0) {
4102            scrollTo(x, y);
4103        }
4104
4105        if (transformSet) {
4106            setTranslationX(tx);
4107            setTranslationY(ty);
4108            setTranslationZ(tz);
4109            setElevation(elevation);
4110            setRotation(rotation);
4111            setRotationX(rotationX);
4112            setRotationY(rotationY);
4113            setScaleX(sx);
4114            setScaleY(sy);
4115        }
4116
4117        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4118            setScrollContainer(true);
4119        }
4120
4121        computeOpaqueFlags();
4122    }
4123
4124    /**
4125     * Non-public constructor for use in testing
4126     */
4127    View() {
4128        mResources = null;
4129        mRenderNode = RenderNode.create(getClass().getName());
4130    }
4131
4132    public String toString() {
4133        StringBuilder out = new StringBuilder(128);
4134        out.append(getClass().getName());
4135        out.append('{');
4136        out.append(Integer.toHexString(System.identityHashCode(this)));
4137        out.append(' ');
4138        switch (mViewFlags&VISIBILITY_MASK) {
4139            case VISIBLE: out.append('V'); break;
4140            case INVISIBLE: out.append('I'); break;
4141            case GONE: out.append('G'); break;
4142            default: out.append('.'); break;
4143        }
4144        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4145        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4146        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4147        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4148        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4149        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4150        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4151        out.append(' ');
4152        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4153        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4154        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4155        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4156            out.append('p');
4157        } else {
4158            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4159        }
4160        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4161        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4162        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4163        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4164        out.append(' ');
4165        out.append(mLeft);
4166        out.append(',');
4167        out.append(mTop);
4168        out.append('-');
4169        out.append(mRight);
4170        out.append(',');
4171        out.append(mBottom);
4172        final int id = getId();
4173        if (id != NO_ID) {
4174            out.append(" #");
4175            out.append(Integer.toHexString(id));
4176            final Resources r = mResources;
4177            if (Resources.resourceHasPackage(id) && r != null) {
4178                try {
4179                    String pkgname;
4180                    switch (id&0xff000000) {
4181                        case 0x7f000000:
4182                            pkgname="app";
4183                            break;
4184                        case 0x01000000:
4185                            pkgname="android";
4186                            break;
4187                        default:
4188                            pkgname = r.getResourcePackageName(id);
4189                            break;
4190                    }
4191                    String typename = r.getResourceTypeName(id);
4192                    String entryname = r.getResourceEntryName(id);
4193                    out.append(" ");
4194                    out.append(pkgname);
4195                    out.append(":");
4196                    out.append(typename);
4197                    out.append("/");
4198                    out.append(entryname);
4199                } catch (Resources.NotFoundException e) {
4200                }
4201            }
4202        }
4203        out.append("}");
4204        return out.toString();
4205    }
4206
4207    /**
4208     * <p>
4209     * Initializes the fading edges from a given set of styled attributes. This
4210     * method should be called by subclasses that need fading edges and when an
4211     * instance of these subclasses is created programmatically rather than
4212     * being inflated from XML. This method is automatically called when the XML
4213     * is inflated.
4214     * </p>
4215     *
4216     * @param a the styled attributes set to initialize the fading edges from
4217     */
4218    protected void initializeFadingEdge(TypedArray a) {
4219        initScrollCache();
4220
4221        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4222                R.styleable.View_fadingEdgeLength,
4223                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4224    }
4225
4226    /**
4227     * Returns the size of the vertical faded edges used to indicate that more
4228     * content in this view is visible.
4229     *
4230     * @return The size in pixels of the vertical faded edge or 0 if vertical
4231     *         faded edges are not enabled for this view.
4232     * @attr ref android.R.styleable#View_fadingEdgeLength
4233     */
4234    public int getVerticalFadingEdgeLength() {
4235        if (isVerticalFadingEdgeEnabled()) {
4236            ScrollabilityCache cache = mScrollCache;
4237            if (cache != null) {
4238                return cache.fadingEdgeLength;
4239            }
4240        }
4241        return 0;
4242    }
4243
4244    /**
4245     * Set the size of the faded edge used to indicate that more content in this
4246     * view is available.  Will not change whether the fading edge is enabled; use
4247     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4248     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4249     * for the vertical or horizontal fading edges.
4250     *
4251     * @param length The size in pixels of the faded edge used to indicate that more
4252     *        content in this view is visible.
4253     */
4254    public void setFadingEdgeLength(int length) {
4255        initScrollCache();
4256        mScrollCache.fadingEdgeLength = length;
4257    }
4258
4259    /**
4260     * Returns the size of the horizontal faded edges used to indicate that more
4261     * content in this view is visible.
4262     *
4263     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4264     *         faded edges are not enabled for this view.
4265     * @attr ref android.R.styleable#View_fadingEdgeLength
4266     */
4267    public int getHorizontalFadingEdgeLength() {
4268        if (isHorizontalFadingEdgeEnabled()) {
4269            ScrollabilityCache cache = mScrollCache;
4270            if (cache != null) {
4271                return cache.fadingEdgeLength;
4272            }
4273        }
4274        return 0;
4275    }
4276
4277    /**
4278     * Returns the width of the vertical scrollbar.
4279     *
4280     * @return The width in pixels of the vertical scrollbar or 0 if there
4281     *         is no vertical scrollbar.
4282     */
4283    public int getVerticalScrollbarWidth() {
4284        ScrollabilityCache cache = mScrollCache;
4285        if (cache != null) {
4286            ScrollBarDrawable scrollBar = cache.scrollBar;
4287            if (scrollBar != null) {
4288                int size = scrollBar.getSize(true);
4289                if (size <= 0) {
4290                    size = cache.scrollBarSize;
4291                }
4292                return size;
4293            }
4294            return 0;
4295        }
4296        return 0;
4297    }
4298
4299    /**
4300     * Returns the height of the horizontal scrollbar.
4301     *
4302     * @return The height in pixels of the horizontal scrollbar or 0 if
4303     *         there is no horizontal scrollbar.
4304     */
4305    protected int getHorizontalScrollbarHeight() {
4306        ScrollabilityCache cache = mScrollCache;
4307        if (cache != null) {
4308            ScrollBarDrawable scrollBar = cache.scrollBar;
4309            if (scrollBar != null) {
4310                int size = scrollBar.getSize(false);
4311                if (size <= 0) {
4312                    size = cache.scrollBarSize;
4313                }
4314                return size;
4315            }
4316            return 0;
4317        }
4318        return 0;
4319    }
4320
4321    /**
4322     * <p>
4323     * Initializes the scrollbars from a given set of styled attributes. This
4324     * method should be called by subclasses that need scrollbars and when an
4325     * instance of these subclasses is created programmatically rather than
4326     * being inflated from XML. This method is automatically called when the XML
4327     * is inflated.
4328     * </p>
4329     *
4330     * @param a the styled attributes set to initialize the scrollbars from
4331     */
4332    protected void initializeScrollbars(TypedArray a) {
4333        initScrollCache();
4334
4335        final ScrollabilityCache scrollabilityCache = mScrollCache;
4336
4337        if (scrollabilityCache.scrollBar == null) {
4338            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4339        }
4340
4341        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4342
4343        if (!fadeScrollbars) {
4344            scrollabilityCache.state = ScrollabilityCache.ON;
4345        }
4346        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4347
4348
4349        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4350                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4351                        .getScrollBarFadeDuration());
4352        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4353                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4354                ViewConfiguration.getScrollDefaultDelay());
4355
4356
4357        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4358                com.android.internal.R.styleable.View_scrollbarSize,
4359                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4360
4361        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4362        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4363
4364        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4365        if (thumb != null) {
4366            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4367        }
4368
4369        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4370                false);
4371        if (alwaysDraw) {
4372            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4373        }
4374
4375        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4376        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4377
4378        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4379        if (thumb != null) {
4380            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4381        }
4382
4383        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4384                false);
4385        if (alwaysDraw) {
4386            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4387        }
4388
4389        // Apply layout direction to the new Drawables if needed
4390        final int layoutDirection = getLayoutDirection();
4391        if (track != null) {
4392            track.setLayoutDirection(layoutDirection);
4393        }
4394        if (thumb != null) {
4395            thumb.setLayoutDirection(layoutDirection);
4396        }
4397
4398        // Re-apply user/background padding so that scrollbar(s) get added
4399        resolvePadding();
4400    }
4401
4402    /**
4403     * <p>
4404     * Initalizes the scrollability cache if necessary.
4405     * </p>
4406     */
4407    private void initScrollCache() {
4408        if (mScrollCache == null) {
4409            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4410        }
4411    }
4412
4413    private ScrollabilityCache getScrollCache() {
4414        initScrollCache();
4415        return mScrollCache;
4416    }
4417
4418    /**
4419     * Set the position of the vertical scroll bar. Should be one of
4420     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4421     * {@link #SCROLLBAR_POSITION_RIGHT}.
4422     *
4423     * @param position Where the vertical scroll bar should be positioned.
4424     */
4425    public void setVerticalScrollbarPosition(int position) {
4426        if (mVerticalScrollbarPosition != position) {
4427            mVerticalScrollbarPosition = position;
4428            computeOpaqueFlags();
4429            resolvePadding();
4430        }
4431    }
4432
4433    /**
4434     * @return The position where the vertical scroll bar will show, if applicable.
4435     * @see #setVerticalScrollbarPosition(int)
4436     */
4437    public int getVerticalScrollbarPosition() {
4438        return mVerticalScrollbarPosition;
4439    }
4440
4441    ListenerInfo getListenerInfo() {
4442        if (mListenerInfo != null) {
4443            return mListenerInfo;
4444        }
4445        mListenerInfo = new ListenerInfo();
4446        return mListenerInfo;
4447    }
4448
4449    /**
4450     * Register a callback to be invoked when focus of this view changed.
4451     *
4452     * @param l The callback that will run.
4453     */
4454    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4455        getListenerInfo().mOnFocusChangeListener = l;
4456    }
4457
4458    /**
4459     * Add a listener that will be called when the bounds of the view change due to
4460     * layout processing.
4461     *
4462     * @param listener The listener that will be called when layout bounds change.
4463     */
4464    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4465        ListenerInfo li = getListenerInfo();
4466        if (li.mOnLayoutChangeListeners == null) {
4467            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4468        }
4469        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4470            li.mOnLayoutChangeListeners.add(listener);
4471        }
4472    }
4473
4474    /**
4475     * Remove a listener for layout changes.
4476     *
4477     * @param listener The listener for layout bounds change.
4478     */
4479    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4480        ListenerInfo li = mListenerInfo;
4481        if (li == null || li.mOnLayoutChangeListeners == null) {
4482            return;
4483        }
4484        li.mOnLayoutChangeListeners.remove(listener);
4485    }
4486
4487    /**
4488     * Add a listener for attach state changes.
4489     *
4490     * This listener will be called whenever this view is attached or detached
4491     * from a window. Remove the listener using
4492     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4493     *
4494     * @param listener Listener to attach
4495     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4496     */
4497    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4498        ListenerInfo li = getListenerInfo();
4499        if (li.mOnAttachStateChangeListeners == null) {
4500            li.mOnAttachStateChangeListeners
4501                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4502        }
4503        li.mOnAttachStateChangeListeners.add(listener);
4504    }
4505
4506    /**
4507     * Remove a listener for attach state changes. The listener will receive no further
4508     * notification of window attach/detach events.
4509     *
4510     * @param listener Listener to remove
4511     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4512     */
4513    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4514        ListenerInfo li = mListenerInfo;
4515        if (li == null || li.mOnAttachStateChangeListeners == null) {
4516            return;
4517        }
4518        li.mOnAttachStateChangeListeners.remove(listener);
4519    }
4520
4521    /**
4522     * Returns the focus-change callback registered for this view.
4523     *
4524     * @return The callback, or null if one is not registered.
4525     */
4526    public OnFocusChangeListener getOnFocusChangeListener() {
4527        ListenerInfo li = mListenerInfo;
4528        return li != null ? li.mOnFocusChangeListener : null;
4529    }
4530
4531    /**
4532     * Register a callback to be invoked when this view is clicked. If this view is not
4533     * clickable, it becomes clickable.
4534     *
4535     * @param l The callback that will run
4536     *
4537     * @see #setClickable(boolean)
4538     */
4539    public void setOnClickListener(OnClickListener l) {
4540        if (!isClickable()) {
4541            setClickable(true);
4542        }
4543        getListenerInfo().mOnClickListener = l;
4544    }
4545
4546    /**
4547     * Return whether this view has an attached OnClickListener.  Returns
4548     * true if there is a listener, false if there is none.
4549     */
4550    public boolean hasOnClickListeners() {
4551        ListenerInfo li = mListenerInfo;
4552        return (li != null && li.mOnClickListener != null);
4553    }
4554
4555    /**
4556     * Register a callback to be invoked when this view is clicked and held. If this view is not
4557     * long clickable, it becomes long clickable.
4558     *
4559     * @param l The callback that will run
4560     *
4561     * @see #setLongClickable(boolean)
4562     */
4563    public void setOnLongClickListener(OnLongClickListener l) {
4564        if (!isLongClickable()) {
4565            setLongClickable(true);
4566        }
4567        getListenerInfo().mOnLongClickListener = l;
4568    }
4569
4570    /**
4571     * Register a callback to be invoked when the context menu for this view is
4572     * being built. If this view is not long clickable, it becomes long clickable.
4573     *
4574     * @param l The callback that will run
4575     *
4576     */
4577    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4578        if (!isLongClickable()) {
4579            setLongClickable(true);
4580        }
4581        getListenerInfo().mOnCreateContextMenuListener = l;
4582    }
4583
4584    /**
4585     * Call this view's OnClickListener, if it is defined.  Performs all normal
4586     * actions associated with clicking: reporting accessibility event, playing
4587     * a sound, etc.
4588     *
4589     * @return True there was an assigned OnClickListener that was called, false
4590     *         otherwise is returned.
4591     */
4592    public boolean performClick() {
4593        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4594
4595        ListenerInfo li = mListenerInfo;
4596        if (li != null && li.mOnClickListener != null) {
4597            playSoundEffect(SoundEffectConstants.CLICK);
4598            li.mOnClickListener.onClick(this);
4599            return true;
4600        }
4601
4602        return false;
4603    }
4604
4605    /**
4606     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4607     * this only calls the listener, and does not do any associated clicking
4608     * actions like reporting an accessibility event.
4609     *
4610     * @return True there was an assigned OnClickListener that was called, false
4611     *         otherwise is returned.
4612     */
4613    public boolean callOnClick() {
4614        ListenerInfo li = mListenerInfo;
4615        if (li != null && li.mOnClickListener != null) {
4616            li.mOnClickListener.onClick(this);
4617            return true;
4618        }
4619        return false;
4620    }
4621
4622    /**
4623     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4624     * OnLongClickListener did not consume the event.
4625     *
4626     * @return True if one of the above receivers consumed the event, false otherwise.
4627     */
4628    public boolean performLongClick() {
4629        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4630
4631        boolean handled = false;
4632        ListenerInfo li = mListenerInfo;
4633        if (li != null && li.mOnLongClickListener != null) {
4634            handled = li.mOnLongClickListener.onLongClick(View.this);
4635        }
4636        if (!handled) {
4637            handled = showContextMenu();
4638        }
4639        if (handled) {
4640            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4641        }
4642        return handled;
4643    }
4644
4645    /**
4646     * Performs button-related actions during a touch down event.
4647     *
4648     * @param event The event.
4649     * @return True if the down was consumed.
4650     *
4651     * @hide
4652     */
4653    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4654        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4655            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4656                return true;
4657            }
4658        }
4659        return false;
4660    }
4661
4662    /**
4663     * Bring up the context menu for this view.
4664     *
4665     * @return Whether a context menu was displayed.
4666     */
4667    public boolean showContextMenu() {
4668        return getParent().showContextMenuForChild(this);
4669    }
4670
4671    /**
4672     * Bring up the context menu for this view, referring to the item under the specified point.
4673     *
4674     * @param x The referenced x coordinate.
4675     * @param y The referenced y coordinate.
4676     * @param metaState The keyboard modifiers that were pressed.
4677     * @return Whether a context menu was displayed.
4678     *
4679     * @hide
4680     */
4681    public boolean showContextMenu(float x, float y, int metaState) {
4682        return showContextMenu();
4683    }
4684
4685    /**
4686     * Start an action mode.
4687     *
4688     * @param callback Callback that will control the lifecycle of the action mode
4689     * @return The new action mode if it is started, null otherwise
4690     *
4691     * @see ActionMode
4692     */
4693    public ActionMode startActionMode(ActionMode.Callback callback) {
4694        ViewParent parent = getParent();
4695        if (parent == null) return null;
4696        return parent.startActionModeForChild(this, callback);
4697    }
4698
4699    /**
4700     * Register a callback to be invoked when a hardware key is pressed in this view.
4701     * Key presses in software input methods will generally not trigger the methods of
4702     * this listener.
4703     * @param l the key listener to attach to this view
4704     */
4705    public void setOnKeyListener(OnKeyListener l) {
4706        getListenerInfo().mOnKeyListener = l;
4707    }
4708
4709    /**
4710     * Register a callback to be invoked when a touch event is sent to this view.
4711     * @param l the touch listener to attach to this view
4712     */
4713    public void setOnTouchListener(OnTouchListener l) {
4714        getListenerInfo().mOnTouchListener = l;
4715    }
4716
4717    /**
4718     * Register a callback to be invoked when a generic motion event is sent to this view.
4719     * @param l the generic motion listener to attach to this view
4720     */
4721    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4722        getListenerInfo().mOnGenericMotionListener = l;
4723    }
4724
4725    /**
4726     * Register a callback to be invoked when a hover event is sent to this view.
4727     * @param l the hover listener to attach to this view
4728     */
4729    public void setOnHoverListener(OnHoverListener l) {
4730        getListenerInfo().mOnHoverListener = l;
4731    }
4732
4733    /**
4734     * Register a drag event listener callback object for this View. The parameter is
4735     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4736     * View, the system calls the
4737     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4738     * @param l An implementation of {@link android.view.View.OnDragListener}.
4739     */
4740    public void setOnDragListener(OnDragListener l) {
4741        getListenerInfo().mOnDragListener = l;
4742    }
4743
4744    /**
4745     * Give this view focus. This will cause
4746     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4747     *
4748     * Note: this does not check whether this {@link View} should get focus, it just
4749     * gives it focus no matter what.  It should only be called internally by framework
4750     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4751     *
4752     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4753     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4754     *        focus moved when requestFocus() is called. It may not always
4755     *        apply, in which case use the default View.FOCUS_DOWN.
4756     * @param previouslyFocusedRect The rectangle of the view that had focus
4757     *        prior in this View's coordinate system.
4758     */
4759    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4760        if (DBG) {
4761            System.out.println(this + " requestFocus()");
4762        }
4763
4764        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4765            mPrivateFlags |= PFLAG_FOCUSED;
4766
4767            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4768
4769            if (mParent != null) {
4770                mParent.requestChildFocus(this, this);
4771            }
4772
4773            if (mAttachInfo != null) {
4774                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4775            }
4776
4777            onFocusChanged(true, direction, previouslyFocusedRect);
4778            manageFocusHotspot(true, oldFocus);
4779            refreshDrawableState();
4780        }
4781    }
4782
4783    /**
4784     * Forwards focus information to the background drawable, if necessary. When
4785     * the view is gaining focus, <code>v</code> is the previous focus holder.
4786     * When the view is losing focus, <code>v</code> is the next focus holder.
4787     *
4788     * @param focused whether this view is focused
4789     * @param v previous or the next focus holder, or null if none
4790     */
4791    private void manageFocusHotspot(boolean focused, View v) {
4792        if (mBackground == null) {
4793            return;
4794        }
4795
4796        final Rect r = new Rect();
4797        if (!focused && v != null) {
4798            v.getBoundsOnScreen(r);
4799            final int[] location = new int[2];
4800            getLocationOnScreen(location);
4801            r.offset(-location[0], -location[1]);
4802        } else {
4803            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4804        }
4805
4806        final float x = r.exactCenterX();
4807        final float y = r.exactCenterY();
4808        mBackground.setHotspot(x, y);
4809    }
4810
4811    /**
4812     * Request that a rectangle of this view be visible on the screen,
4813     * scrolling if necessary just enough.
4814     *
4815     * <p>A View should call this if it maintains some notion of which part
4816     * of its content is interesting.  For example, a text editing view
4817     * should call this when its cursor moves.
4818     *
4819     * @param rectangle The rectangle.
4820     * @return Whether any parent scrolled.
4821     */
4822    public boolean requestRectangleOnScreen(Rect rectangle) {
4823        return requestRectangleOnScreen(rectangle, false);
4824    }
4825
4826    /**
4827     * Request that a rectangle of this view be visible on the screen,
4828     * scrolling if necessary just enough.
4829     *
4830     * <p>A View should call this if it maintains some notion of which part
4831     * of its content is interesting.  For example, a text editing view
4832     * should call this when its cursor moves.
4833     *
4834     * <p>When <code>immediate</code> is set to true, scrolling will not be
4835     * animated.
4836     *
4837     * @param rectangle The rectangle.
4838     * @param immediate True to forbid animated scrolling, false otherwise
4839     * @return Whether any parent scrolled.
4840     */
4841    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4842        if (mParent == null) {
4843            return false;
4844        }
4845
4846        View child = this;
4847
4848        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4849        position.set(rectangle);
4850
4851        ViewParent parent = mParent;
4852        boolean scrolled = false;
4853        while (parent != null) {
4854            rectangle.set((int) position.left, (int) position.top,
4855                    (int) position.right, (int) position.bottom);
4856
4857            scrolled |= parent.requestChildRectangleOnScreen(child,
4858                    rectangle, immediate);
4859
4860            if (!child.hasIdentityMatrix()) {
4861                child.getMatrix().mapRect(position);
4862            }
4863
4864            position.offset(child.mLeft, child.mTop);
4865
4866            if (!(parent instanceof View)) {
4867                break;
4868            }
4869
4870            View parentView = (View) parent;
4871
4872            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4873
4874            child = parentView;
4875            parent = child.getParent();
4876        }
4877
4878        return scrolled;
4879    }
4880
4881    /**
4882     * Called when this view wants to give up focus. If focus is cleared
4883     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4884     * <p>
4885     * <strong>Note:</strong> When a View clears focus the framework is trying
4886     * to give focus to the first focusable View from the top. Hence, if this
4887     * View is the first from the top that can take focus, then all callbacks
4888     * related to clearing focus will be invoked after wich the framework will
4889     * give focus to this view.
4890     * </p>
4891     */
4892    public void clearFocus() {
4893        if (DBG) {
4894            System.out.println(this + " clearFocus()");
4895        }
4896
4897        clearFocusInternal(null, true, true);
4898    }
4899
4900    /**
4901     * Clears focus from the view, optionally propagating the change up through
4902     * the parent hierarchy and requesting that the root view place new focus.
4903     *
4904     * @param propagate whether to propagate the change up through the parent
4905     *            hierarchy
4906     * @param refocus when propagate is true, specifies whether to request the
4907     *            root view place new focus
4908     */
4909    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4910        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4911            mPrivateFlags &= ~PFLAG_FOCUSED;
4912
4913            if (propagate && mParent != null) {
4914                mParent.clearChildFocus(this);
4915            }
4916
4917            onFocusChanged(false, 0, null);
4918
4919            manageFocusHotspot(false, focused);
4920            refreshDrawableState();
4921
4922            if (propagate && (!refocus || !rootViewRequestFocus())) {
4923                notifyGlobalFocusCleared(this);
4924            }
4925        }
4926    }
4927
4928    void notifyGlobalFocusCleared(View oldFocus) {
4929        if (oldFocus != null && mAttachInfo != null) {
4930            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4931        }
4932    }
4933
4934    boolean rootViewRequestFocus() {
4935        final View root = getRootView();
4936        return root != null && root.requestFocus();
4937    }
4938
4939    /**
4940     * Called internally by the view system when a new view is getting focus.
4941     * This is what clears the old focus.
4942     * <p>
4943     * <b>NOTE:</b> The parent view's focused child must be updated manually
4944     * after calling this method. Otherwise, the view hierarchy may be left in
4945     * an inconstent state.
4946     */
4947    void unFocus(View focused) {
4948        if (DBG) {
4949            System.out.println(this + " unFocus()");
4950        }
4951
4952        clearFocusInternal(focused, false, false);
4953    }
4954
4955    /**
4956     * Returns true if this view has focus iteself, or is the ancestor of the
4957     * view that has focus.
4958     *
4959     * @return True if this view has or contains focus, false otherwise.
4960     */
4961    @ViewDebug.ExportedProperty(category = "focus")
4962    public boolean hasFocus() {
4963        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4964    }
4965
4966    /**
4967     * Returns true if this view is focusable or if it contains a reachable View
4968     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4969     * is a View whose parents do not block descendants focus.
4970     *
4971     * Only {@link #VISIBLE} views are considered focusable.
4972     *
4973     * @return True if the view is focusable or if the view contains a focusable
4974     *         View, false otherwise.
4975     *
4976     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4977     */
4978    public boolean hasFocusable() {
4979        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4980    }
4981
4982    /**
4983     * Called by the view system when the focus state of this view changes.
4984     * When the focus change event is caused by directional navigation, direction
4985     * and previouslyFocusedRect provide insight into where the focus is coming from.
4986     * When overriding, be sure to call up through to the super class so that
4987     * the standard focus handling will occur.
4988     *
4989     * @param gainFocus True if the View has focus; false otherwise.
4990     * @param direction The direction focus has moved when requestFocus()
4991     *                  is called to give this view focus. Values are
4992     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4993     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4994     *                  It may not always apply, in which case use the default.
4995     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4996     *        system, of the previously focused view.  If applicable, this will be
4997     *        passed in as finer grained information about where the focus is coming
4998     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4999     */
5000    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5001            @Nullable Rect previouslyFocusedRect) {
5002        if (gainFocus) {
5003            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5004        } else {
5005            notifyViewAccessibilityStateChangedIfNeeded(
5006                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5007        }
5008
5009        InputMethodManager imm = InputMethodManager.peekInstance();
5010        if (!gainFocus) {
5011            if (isPressed()) {
5012                setPressed(false);
5013            }
5014            if (imm != null && mAttachInfo != null
5015                    && mAttachInfo.mHasWindowFocus) {
5016                imm.focusOut(this);
5017            }
5018            onFocusLost();
5019        } else if (imm != null && mAttachInfo != null
5020                && mAttachInfo.mHasWindowFocus) {
5021            imm.focusIn(this);
5022        }
5023
5024        invalidate(true);
5025        ListenerInfo li = mListenerInfo;
5026        if (li != null && li.mOnFocusChangeListener != null) {
5027            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5028        }
5029
5030        if (mAttachInfo != null) {
5031            mAttachInfo.mKeyDispatchState.reset(this);
5032        }
5033    }
5034
5035    /**
5036     * Sends an accessibility event of the given type. If accessibility is
5037     * not enabled this method has no effect. The default implementation calls
5038     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5039     * to populate information about the event source (this View), then calls
5040     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5041     * populate the text content of the event source including its descendants,
5042     * and last calls
5043     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5044     * on its parent to resuest sending of the event to interested parties.
5045     * <p>
5046     * If an {@link AccessibilityDelegate} has been specified via calling
5047     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5048     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5049     * responsible for handling this call.
5050     * </p>
5051     *
5052     * @param eventType The type of the event to send, as defined by several types from
5053     * {@link android.view.accessibility.AccessibilityEvent}, such as
5054     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5055     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5056     *
5057     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5058     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5059     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5060     * @see AccessibilityDelegate
5061     */
5062    public void sendAccessibilityEvent(int eventType) {
5063        if (mAccessibilityDelegate != null) {
5064            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5065        } else {
5066            sendAccessibilityEventInternal(eventType);
5067        }
5068    }
5069
5070    /**
5071     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5072     * {@link AccessibilityEvent} to make an announcement which is related to some
5073     * sort of a context change for which none of the events representing UI transitions
5074     * is a good fit. For example, announcing a new page in a book. If accessibility
5075     * is not enabled this method does nothing.
5076     *
5077     * @param text The announcement text.
5078     */
5079    public void announceForAccessibility(CharSequence text) {
5080        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5081            AccessibilityEvent event = AccessibilityEvent.obtain(
5082                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5083            onInitializeAccessibilityEvent(event);
5084            event.getText().add(text);
5085            event.setContentDescription(null);
5086            mParent.requestSendAccessibilityEvent(this, event);
5087        }
5088    }
5089
5090    /**
5091     * @see #sendAccessibilityEvent(int)
5092     *
5093     * Note: Called from the default {@link AccessibilityDelegate}.
5094     */
5095    void sendAccessibilityEventInternal(int eventType) {
5096        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5097            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5098        }
5099    }
5100
5101    /**
5102     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5103     * takes as an argument an empty {@link AccessibilityEvent} and does not
5104     * perform a check whether accessibility is enabled.
5105     * <p>
5106     * If an {@link AccessibilityDelegate} has been specified via calling
5107     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5108     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5109     * is responsible for handling this call.
5110     * </p>
5111     *
5112     * @param event The event to send.
5113     *
5114     * @see #sendAccessibilityEvent(int)
5115     */
5116    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5117        if (mAccessibilityDelegate != null) {
5118            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5119        } else {
5120            sendAccessibilityEventUncheckedInternal(event);
5121        }
5122    }
5123
5124    /**
5125     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5126     *
5127     * Note: Called from the default {@link AccessibilityDelegate}.
5128     */
5129    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5130        if (!isShown()) {
5131            return;
5132        }
5133        onInitializeAccessibilityEvent(event);
5134        // Only a subset of accessibility events populates text content.
5135        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5136            dispatchPopulateAccessibilityEvent(event);
5137        }
5138        // In the beginning we called #isShown(), so we know that getParent() is not null.
5139        getParent().requestSendAccessibilityEvent(this, event);
5140    }
5141
5142    /**
5143     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5144     * to its children for adding their text content to the event. Note that the
5145     * event text is populated in a separate dispatch path since we add to the
5146     * event not only the text of the source but also the text of all its descendants.
5147     * A typical implementation will call
5148     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5149     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5150     * on each child. Override this method if custom population of the event text
5151     * content is required.
5152     * <p>
5153     * If an {@link AccessibilityDelegate} has been specified via calling
5154     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5155     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5156     * is responsible for handling this call.
5157     * </p>
5158     * <p>
5159     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5160     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5161     * </p>
5162     *
5163     * @param event The event.
5164     *
5165     * @return True if the event population was completed.
5166     */
5167    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5168        if (mAccessibilityDelegate != null) {
5169            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5170        } else {
5171            return dispatchPopulateAccessibilityEventInternal(event);
5172        }
5173    }
5174
5175    /**
5176     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5177     *
5178     * Note: Called from the default {@link AccessibilityDelegate}.
5179     */
5180    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5181        onPopulateAccessibilityEvent(event);
5182        return false;
5183    }
5184
5185    /**
5186     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5187     * giving a chance to this View to populate the accessibility event with its
5188     * text content. While this method is free to modify event
5189     * attributes other than text content, doing so should normally be performed in
5190     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5191     * <p>
5192     * Example: Adding formatted date string to an accessibility event in addition
5193     *          to the text added by the super implementation:
5194     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5195     *     super.onPopulateAccessibilityEvent(event);
5196     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5197     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5198     *         mCurrentDate.getTimeInMillis(), flags);
5199     *     event.getText().add(selectedDateUtterance);
5200     * }</pre>
5201     * <p>
5202     * If an {@link AccessibilityDelegate} has been specified via calling
5203     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5204     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5205     * is responsible for handling this call.
5206     * </p>
5207     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5208     * information to the event, in case the default implementation has basic information to add.
5209     * </p>
5210     *
5211     * @param event The accessibility event which to populate.
5212     *
5213     * @see #sendAccessibilityEvent(int)
5214     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5215     */
5216    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5217        if (mAccessibilityDelegate != null) {
5218            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5219        } else {
5220            onPopulateAccessibilityEventInternal(event);
5221        }
5222    }
5223
5224    /**
5225     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5226     *
5227     * Note: Called from the default {@link AccessibilityDelegate}.
5228     */
5229    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5230    }
5231
5232    /**
5233     * Initializes an {@link AccessibilityEvent} with information about
5234     * this View which is the event source. In other words, the source of
5235     * an accessibility event is the view whose state change triggered firing
5236     * the event.
5237     * <p>
5238     * Example: Setting the password property of an event in addition
5239     *          to properties set by the super implementation:
5240     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5241     *     super.onInitializeAccessibilityEvent(event);
5242     *     event.setPassword(true);
5243     * }</pre>
5244     * <p>
5245     * If an {@link AccessibilityDelegate} has been specified via calling
5246     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5247     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5248     * is responsible for handling this call.
5249     * </p>
5250     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5251     * information to the event, in case the default implementation has basic information to add.
5252     * </p>
5253     * @param event The event to initialize.
5254     *
5255     * @see #sendAccessibilityEvent(int)
5256     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5257     */
5258    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5259        if (mAccessibilityDelegate != null) {
5260            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5261        } else {
5262            onInitializeAccessibilityEventInternal(event);
5263        }
5264    }
5265
5266    /**
5267     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5268     *
5269     * Note: Called from the default {@link AccessibilityDelegate}.
5270     */
5271    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5272        event.setSource(this);
5273        event.setClassName(View.class.getName());
5274        event.setPackageName(getContext().getPackageName());
5275        event.setEnabled(isEnabled());
5276        event.setContentDescription(mContentDescription);
5277
5278        switch (event.getEventType()) {
5279            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5280                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5281                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5282                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5283                event.setItemCount(focusablesTempList.size());
5284                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5285                if (mAttachInfo != null) {
5286                    focusablesTempList.clear();
5287                }
5288            } break;
5289            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5290                CharSequence text = getIterableTextForAccessibility();
5291                if (text != null && text.length() > 0) {
5292                    event.setFromIndex(getAccessibilitySelectionStart());
5293                    event.setToIndex(getAccessibilitySelectionEnd());
5294                    event.setItemCount(text.length());
5295                }
5296            } break;
5297        }
5298    }
5299
5300    /**
5301     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5302     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5303     * This method is responsible for obtaining an accessibility node info from a
5304     * pool of reusable instances and calling
5305     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5306     * initialize the former.
5307     * <p>
5308     * Note: The client is responsible for recycling the obtained instance by calling
5309     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5310     * </p>
5311     *
5312     * @return A populated {@link AccessibilityNodeInfo}.
5313     *
5314     * @see AccessibilityNodeInfo
5315     */
5316    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5317        if (mAccessibilityDelegate != null) {
5318            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5319        } else {
5320            return createAccessibilityNodeInfoInternal();
5321        }
5322    }
5323
5324    /**
5325     * @see #createAccessibilityNodeInfo()
5326     */
5327    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5328        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5329        if (provider != null) {
5330            return provider.createAccessibilityNodeInfo(View.NO_ID);
5331        } else {
5332            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5333            onInitializeAccessibilityNodeInfo(info);
5334            return info;
5335        }
5336    }
5337
5338    /**
5339     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5340     * The base implementation sets:
5341     * <ul>
5342     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5343     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5344     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5345     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5346     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5347     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5348     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5349     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5350     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5351     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5352     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5353     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5354     * </ul>
5355     * <p>
5356     * Subclasses should override this method, call the super implementation,
5357     * and set additional attributes.
5358     * </p>
5359     * <p>
5360     * If an {@link AccessibilityDelegate} has been specified via calling
5361     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5362     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5363     * is responsible for handling this call.
5364     * </p>
5365     *
5366     * @param info The instance to initialize.
5367     */
5368    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5369        if (mAccessibilityDelegate != null) {
5370            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5371        } else {
5372            onInitializeAccessibilityNodeInfoInternal(info);
5373        }
5374    }
5375
5376    /**
5377     * Gets the location of this view in screen coordintates.
5378     *
5379     * @param outRect The output location
5380     */
5381    void getBoundsOnScreen(Rect outRect) {
5382        if (mAttachInfo == null) {
5383            return;
5384        }
5385
5386        RectF position = mAttachInfo.mTmpTransformRect;
5387        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5388
5389        if (!hasIdentityMatrix()) {
5390            getMatrix().mapRect(position);
5391        }
5392
5393        position.offset(mLeft, mTop);
5394
5395        ViewParent parent = mParent;
5396        while (parent instanceof View) {
5397            View parentView = (View) parent;
5398
5399            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5400
5401            if (!parentView.hasIdentityMatrix()) {
5402                parentView.getMatrix().mapRect(position);
5403            }
5404
5405            position.offset(parentView.mLeft, parentView.mTop);
5406
5407            parent = parentView.mParent;
5408        }
5409
5410        if (parent instanceof ViewRootImpl) {
5411            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5412            position.offset(0, -viewRootImpl.mCurScrollY);
5413        }
5414
5415        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5416
5417        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5418                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5419    }
5420
5421    /**
5422     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5423     *
5424     * Note: Called from the default {@link AccessibilityDelegate}.
5425     */
5426    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5427        Rect bounds = mAttachInfo.mTmpInvalRect;
5428
5429        getDrawingRect(bounds);
5430        info.setBoundsInParent(bounds);
5431
5432        getBoundsOnScreen(bounds);
5433        info.setBoundsInScreen(bounds);
5434
5435        ViewParent parent = getParentForAccessibility();
5436        if (parent instanceof View) {
5437            info.setParent((View) parent);
5438        }
5439
5440        if (mID != View.NO_ID) {
5441            View rootView = getRootView();
5442            if (rootView == null) {
5443                rootView = this;
5444            }
5445            View label = rootView.findLabelForView(this, mID);
5446            if (label != null) {
5447                info.setLabeledBy(label);
5448            }
5449
5450            if ((mAttachInfo.mAccessibilityFetchFlags
5451                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5452                    && Resources.resourceHasPackage(mID)) {
5453                try {
5454                    String viewId = getResources().getResourceName(mID);
5455                    info.setViewIdResourceName(viewId);
5456                } catch (Resources.NotFoundException nfe) {
5457                    /* ignore */
5458                }
5459            }
5460        }
5461
5462        if (mLabelForId != View.NO_ID) {
5463            View rootView = getRootView();
5464            if (rootView == null) {
5465                rootView = this;
5466            }
5467            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5468            if (labeled != null) {
5469                info.setLabelFor(labeled);
5470            }
5471        }
5472
5473        info.setVisibleToUser(isVisibleToUser());
5474
5475        info.setPackageName(mContext.getPackageName());
5476        info.setClassName(View.class.getName());
5477        info.setContentDescription(getContentDescription());
5478
5479        info.setEnabled(isEnabled());
5480        info.setClickable(isClickable());
5481        info.setFocusable(isFocusable());
5482        info.setFocused(isFocused());
5483        info.setAccessibilityFocused(isAccessibilityFocused());
5484        info.setSelected(isSelected());
5485        info.setLongClickable(isLongClickable());
5486        info.setLiveRegion(getAccessibilityLiveRegion());
5487
5488        // TODO: These make sense only if we are in an AdapterView but all
5489        // views can be selected. Maybe from accessibility perspective
5490        // we should report as selectable view in an AdapterView.
5491        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5492        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5493
5494        if (isFocusable()) {
5495            if (isFocused()) {
5496                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5497            } else {
5498                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5499            }
5500        }
5501
5502        if (!isAccessibilityFocused()) {
5503            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5504        } else {
5505            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5506        }
5507
5508        if (isClickable() && isEnabled()) {
5509            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5510        }
5511
5512        if (isLongClickable() && isEnabled()) {
5513            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5514        }
5515
5516        CharSequence text = getIterableTextForAccessibility();
5517        if (text != null && text.length() > 0) {
5518            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5519
5520            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5521            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5522            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5523            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5524                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5525                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5526        }
5527    }
5528
5529    private View findLabelForView(View view, int labeledId) {
5530        if (mMatchLabelForPredicate == null) {
5531            mMatchLabelForPredicate = new MatchLabelForPredicate();
5532        }
5533        mMatchLabelForPredicate.mLabeledId = labeledId;
5534        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5535    }
5536
5537    /**
5538     * Computes whether this view is visible to the user. Such a view is
5539     * attached, visible, all its predecessors are visible, it is not clipped
5540     * entirely by its predecessors, and has an alpha greater than zero.
5541     *
5542     * @return Whether the view is visible on the screen.
5543     *
5544     * @hide
5545     */
5546    protected boolean isVisibleToUser() {
5547        return isVisibleToUser(null);
5548    }
5549
5550    /**
5551     * Computes whether the given portion of this view is visible to the user.
5552     * Such a view is attached, visible, all its predecessors are visible,
5553     * has an alpha greater than zero, and the specified portion is not
5554     * clipped entirely by its predecessors.
5555     *
5556     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5557     *                    <code>null</code>, and the entire view will be tested in this case.
5558     *                    When <code>true</code> is returned by the function, the actual visible
5559     *                    region will be stored in this parameter; that is, if boundInView is fully
5560     *                    contained within the view, no modification will be made, otherwise regions
5561     *                    outside of the visible area of the view will be clipped.
5562     *
5563     * @return Whether the specified portion of the view is visible on the screen.
5564     *
5565     * @hide
5566     */
5567    protected boolean isVisibleToUser(Rect boundInView) {
5568        if (mAttachInfo != null) {
5569            // Attached to invisible window means this view is not visible.
5570            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5571                return false;
5572            }
5573            // An invisible predecessor or one with alpha zero means
5574            // that this view is not visible to the user.
5575            Object current = this;
5576            while (current instanceof View) {
5577                View view = (View) current;
5578                // We have attach info so this view is attached and there is no
5579                // need to check whether we reach to ViewRootImpl on the way up.
5580                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5581                        view.getVisibility() != VISIBLE) {
5582                    return false;
5583                }
5584                current = view.mParent;
5585            }
5586            // Check if the view is entirely covered by its predecessors.
5587            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5588            Point offset = mAttachInfo.mPoint;
5589            if (!getGlobalVisibleRect(visibleRect, offset)) {
5590                return false;
5591            }
5592            // Check if the visible portion intersects the rectangle of interest.
5593            if (boundInView != null) {
5594                visibleRect.offset(-offset.x, -offset.y);
5595                return boundInView.intersect(visibleRect);
5596            }
5597            return true;
5598        }
5599        return false;
5600    }
5601
5602    /**
5603     * Returns the delegate for implementing accessibility support via
5604     * composition. For more details see {@link AccessibilityDelegate}.
5605     *
5606     * @return The delegate, or null if none set.
5607     *
5608     * @hide
5609     */
5610    public AccessibilityDelegate getAccessibilityDelegate() {
5611        return mAccessibilityDelegate;
5612    }
5613
5614    /**
5615     * Sets a delegate for implementing accessibility support via composition as
5616     * opposed to inheritance. The delegate's primary use is for implementing
5617     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5618     *
5619     * @param delegate The delegate instance.
5620     *
5621     * @see AccessibilityDelegate
5622     */
5623    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5624        mAccessibilityDelegate = delegate;
5625    }
5626
5627    /**
5628     * Gets the provider for managing a virtual view hierarchy rooted at this View
5629     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5630     * that explore the window content.
5631     * <p>
5632     * If this method returns an instance, this instance is responsible for managing
5633     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5634     * View including the one representing the View itself. Similarly the returned
5635     * instance is responsible for performing accessibility actions on any virtual
5636     * view or the root view itself.
5637     * </p>
5638     * <p>
5639     * If an {@link AccessibilityDelegate} has been specified via calling
5640     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5641     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5642     * is responsible for handling this call.
5643     * </p>
5644     *
5645     * @return The provider.
5646     *
5647     * @see AccessibilityNodeProvider
5648     */
5649    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5650        if (mAccessibilityDelegate != null) {
5651            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5652        } else {
5653            return null;
5654        }
5655    }
5656
5657    /**
5658     * Gets the unique identifier of this view on the screen for accessibility purposes.
5659     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5660     *
5661     * @return The view accessibility id.
5662     *
5663     * @hide
5664     */
5665    public int getAccessibilityViewId() {
5666        if (mAccessibilityViewId == NO_ID) {
5667            mAccessibilityViewId = sNextAccessibilityViewId++;
5668        }
5669        return mAccessibilityViewId;
5670    }
5671
5672    /**
5673     * Gets the unique identifier of the window in which this View reseides.
5674     *
5675     * @return The window accessibility id.
5676     *
5677     * @hide
5678     */
5679    public int getAccessibilityWindowId() {
5680        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5681                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5682    }
5683
5684    /**
5685     * Gets the {@link View} description. It briefly describes the view and is
5686     * primarily used for accessibility support. Set this property to enable
5687     * better accessibility support for your application. This is especially
5688     * true for views that do not have textual representation (For example,
5689     * ImageButton).
5690     *
5691     * @return The content description.
5692     *
5693     * @attr ref android.R.styleable#View_contentDescription
5694     */
5695    @ViewDebug.ExportedProperty(category = "accessibility")
5696    public CharSequence getContentDescription() {
5697        return mContentDescription;
5698    }
5699
5700    /**
5701     * Sets the {@link View} description. It briefly describes the view and is
5702     * primarily used for accessibility support. Set this property to enable
5703     * better accessibility support for your application. This is especially
5704     * true for views that do not have textual representation (For example,
5705     * ImageButton).
5706     *
5707     * @param contentDescription The content description.
5708     *
5709     * @attr ref android.R.styleable#View_contentDescription
5710     */
5711    @RemotableViewMethod
5712    public void setContentDescription(CharSequence contentDescription) {
5713        if (mContentDescription == null) {
5714            if (contentDescription == null) {
5715                return;
5716            }
5717        } else if (mContentDescription.equals(contentDescription)) {
5718            return;
5719        }
5720        mContentDescription = contentDescription;
5721        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5722        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5723            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5724            notifySubtreeAccessibilityStateChangedIfNeeded();
5725        } else {
5726            notifyViewAccessibilityStateChangedIfNeeded(
5727                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5728        }
5729    }
5730
5731    /**
5732     * Gets the id of a view for which this view serves as a label for
5733     * accessibility purposes.
5734     *
5735     * @return The labeled view id.
5736     */
5737    @ViewDebug.ExportedProperty(category = "accessibility")
5738    public int getLabelFor() {
5739        return mLabelForId;
5740    }
5741
5742    /**
5743     * Sets the id of a view for which this view serves as a label for
5744     * accessibility purposes.
5745     *
5746     * @param id The labeled view id.
5747     */
5748    @RemotableViewMethod
5749    public void setLabelFor(int id) {
5750        mLabelForId = id;
5751        if (mLabelForId != View.NO_ID
5752                && mID == View.NO_ID) {
5753            mID = generateViewId();
5754        }
5755    }
5756
5757    /**
5758     * Invoked whenever this view loses focus, either by losing window focus or by losing
5759     * focus within its window. This method can be used to clear any state tied to the
5760     * focus. For instance, if a button is held pressed with the trackball and the window
5761     * loses focus, this method can be used to cancel the press.
5762     *
5763     * Subclasses of View overriding this method should always call super.onFocusLost().
5764     *
5765     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5766     * @see #onWindowFocusChanged(boolean)
5767     *
5768     * @hide pending API council approval
5769     */
5770    protected void onFocusLost() {
5771        resetPressedState();
5772    }
5773
5774    private void resetPressedState() {
5775        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5776            return;
5777        }
5778
5779        if (isPressed()) {
5780            setPressed(false);
5781
5782            if (!mHasPerformedLongPress) {
5783                removeLongPressCallback();
5784            }
5785        }
5786    }
5787
5788    /**
5789     * Returns true if this view has focus
5790     *
5791     * @return True if this view has focus, false otherwise.
5792     */
5793    @ViewDebug.ExportedProperty(category = "focus")
5794    public boolean isFocused() {
5795        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5796    }
5797
5798    /**
5799     * Find the view in the hierarchy rooted at this view that currently has
5800     * focus.
5801     *
5802     * @return The view that currently has focus, or null if no focused view can
5803     *         be found.
5804     */
5805    public View findFocus() {
5806        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5807    }
5808
5809    /**
5810     * Indicates whether this view is one of the set of scrollable containers in
5811     * its window.
5812     *
5813     * @return whether this view is one of the set of scrollable containers in
5814     * its window
5815     *
5816     * @attr ref android.R.styleable#View_isScrollContainer
5817     */
5818    public boolean isScrollContainer() {
5819        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5820    }
5821
5822    /**
5823     * Change whether this view is one of the set of scrollable containers in
5824     * its window.  This will be used to determine whether the window can
5825     * resize or must pan when a soft input area is open -- scrollable
5826     * containers allow the window to use resize mode since the container
5827     * will appropriately shrink.
5828     *
5829     * @attr ref android.R.styleable#View_isScrollContainer
5830     */
5831    public void setScrollContainer(boolean isScrollContainer) {
5832        if (isScrollContainer) {
5833            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5834                mAttachInfo.mScrollContainers.add(this);
5835                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5836            }
5837            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5838        } else {
5839            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5840                mAttachInfo.mScrollContainers.remove(this);
5841            }
5842            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5843        }
5844    }
5845
5846    /**
5847     * Returns the quality of the drawing cache.
5848     *
5849     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5850     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5851     *
5852     * @see #setDrawingCacheQuality(int)
5853     * @see #setDrawingCacheEnabled(boolean)
5854     * @see #isDrawingCacheEnabled()
5855     *
5856     * @attr ref android.R.styleable#View_drawingCacheQuality
5857     */
5858    @DrawingCacheQuality
5859    public int getDrawingCacheQuality() {
5860        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5861    }
5862
5863    /**
5864     * Set the drawing cache quality of this view. This value is used only when the
5865     * drawing cache is enabled
5866     *
5867     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5868     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5869     *
5870     * @see #getDrawingCacheQuality()
5871     * @see #setDrawingCacheEnabled(boolean)
5872     * @see #isDrawingCacheEnabled()
5873     *
5874     * @attr ref android.R.styleable#View_drawingCacheQuality
5875     */
5876    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5877        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5878    }
5879
5880    /**
5881     * Returns whether the screen should remain on, corresponding to the current
5882     * value of {@link #KEEP_SCREEN_ON}.
5883     *
5884     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5885     *
5886     * @see #setKeepScreenOn(boolean)
5887     *
5888     * @attr ref android.R.styleable#View_keepScreenOn
5889     */
5890    public boolean getKeepScreenOn() {
5891        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5892    }
5893
5894    /**
5895     * Controls whether the screen should remain on, modifying the
5896     * value of {@link #KEEP_SCREEN_ON}.
5897     *
5898     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5899     *
5900     * @see #getKeepScreenOn()
5901     *
5902     * @attr ref android.R.styleable#View_keepScreenOn
5903     */
5904    public void setKeepScreenOn(boolean keepScreenOn) {
5905        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5906    }
5907
5908    /**
5909     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5910     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5911     *
5912     * @attr ref android.R.styleable#View_nextFocusLeft
5913     */
5914    public int getNextFocusLeftId() {
5915        return mNextFocusLeftId;
5916    }
5917
5918    /**
5919     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5920     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5921     * decide automatically.
5922     *
5923     * @attr ref android.R.styleable#View_nextFocusLeft
5924     */
5925    public void setNextFocusLeftId(int nextFocusLeftId) {
5926        mNextFocusLeftId = nextFocusLeftId;
5927    }
5928
5929    /**
5930     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5931     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5932     *
5933     * @attr ref android.R.styleable#View_nextFocusRight
5934     */
5935    public int getNextFocusRightId() {
5936        return mNextFocusRightId;
5937    }
5938
5939    /**
5940     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5941     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5942     * decide automatically.
5943     *
5944     * @attr ref android.R.styleable#View_nextFocusRight
5945     */
5946    public void setNextFocusRightId(int nextFocusRightId) {
5947        mNextFocusRightId = nextFocusRightId;
5948    }
5949
5950    /**
5951     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5952     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5953     *
5954     * @attr ref android.R.styleable#View_nextFocusUp
5955     */
5956    public int getNextFocusUpId() {
5957        return mNextFocusUpId;
5958    }
5959
5960    /**
5961     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5962     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5963     * decide automatically.
5964     *
5965     * @attr ref android.R.styleable#View_nextFocusUp
5966     */
5967    public void setNextFocusUpId(int nextFocusUpId) {
5968        mNextFocusUpId = nextFocusUpId;
5969    }
5970
5971    /**
5972     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5973     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5974     *
5975     * @attr ref android.R.styleable#View_nextFocusDown
5976     */
5977    public int getNextFocusDownId() {
5978        return mNextFocusDownId;
5979    }
5980
5981    /**
5982     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5983     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5984     * decide automatically.
5985     *
5986     * @attr ref android.R.styleable#View_nextFocusDown
5987     */
5988    public void setNextFocusDownId(int nextFocusDownId) {
5989        mNextFocusDownId = nextFocusDownId;
5990    }
5991
5992    /**
5993     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5994     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5995     *
5996     * @attr ref android.R.styleable#View_nextFocusForward
5997     */
5998    public int getNextFocusForwardId() {
5999        return mNextFocusForwardId;
6000    }
6001
6002    /**
6003     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6004     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6005     * decide automatically.
6006     *
6007     * @attr ref android.R.styleable#View_nextFocusForward
6008     */
6009    public void setNextFocusForwardId(int nextFocusForwardId) {
6010        mNextFocusForwardId = nextFocusForwardId;
6011    }
6012
6013    /**
6014     * Returns the visibility of this view and all of its ancestors
6015     *
6016     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6017     */
6018    public boolean isShown() {
6019        View current = this;
6020        //noinspection ConstantConditions
6021        do {
6022            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6023                return false;
6024            }
6025            ViewParent parent = current.mParent;
6026            if (parent == null) {
6027                return false; // We are not attached to the view root
6028            }
6029            if (!(parent instanceof View)) {
6030                return true;
6031            }
6032            current = (View) parent;
6033        } while (current != null);
6034
6035        return false;
6036    }
6037
6038    /**
6039     * Called by the view hierarchy when the content insets for a window have
6040     * changed, to allow it to adjust its content to fit within those windows.
6041     * The content insets tell you the space that the status bar, input method,
6042     * and other system windows infringe on the application's window.
6043     *
6044     * <p>You do not normally need to deal with this function, since the default
6045     * window decoration given to applications takes care of applying it to the
6046     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6047     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6048     * and your content can be placed under those system elements.  You can then
6049     * use this method within your view hierarchy if you have parts of your UI
6050     * which you would like to ensure are not being covered.
6051     *
6052     * <p>The default implementation of this method simply applies the content
6053     * insets to the view's padding, consuming that content (modifying the
6054     * insets to be 0), and returning true.  This behavior is off by default, but can
6055     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6056     *
6057     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6058     * insets object is propagated down the hierarchy, so any changes made to it will
6059     * be seen by all following views (including potentially ones above in
6060     * the hierarchy since this is a depth-first traversal).  The first view
6061     * that returns true will abort the entire traversal.
6062     *
6063     * <p>The default implementation works well for a situation where it is
6064     * used with a container that covers the entire window, allowing it to
6065     * apply the appropriate insets to its content on all edges.  If you need
6066     * a more complicated layout (such as two different views fitting system
6067     * windows, one on the top of the window, and one on the bottom),
6068     * you can override the method and handle the insets however you would like.
6069     * Note that the insets provided by the framework are always relative to the
6070     * far edges of the window, not accounting for the location of the called view
6071     * within that window.  (In fact when this method is called you do not yet know
6072     * where the layout will place the view, as it is done before layout happens.)
6073     *
6074     * <p>Note: unlike many View methods, there is no dispatch phase to this
6075     * call.  If you are overriding it in a ViewGroup and want to allow the
6076     * call to continue to your children, you must be sure to call the super
6077     * implementation.
6078     *
6079     * <p>Here is a sample layout that makes use of fitting system windows
6080     * to have controls for a video view placed inside of the window decorations
6081     * that it hides and shows.  This can be used with code like the second
6082     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6083     *
6084     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6085     *
6086     * @param insets Current content insets of the window.  Prior to
6087     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6088     * the insets or else you and Android will be unhappy.
6089     *
6090     * @return {@code true} if this view applied the insets and it should not
6091     * continue propagating further down the hierarchy, {@code false} otherwise.
6092     * @see #getFitsSystemWindows()
6093     * @see #setFitsSystemWindows(boolean)
6094     * @see #setSystemUiVisibility(int)
6095     *
6096     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6097     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6098     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6099     * to implement handling their own insets.
6100     */
6101    protected boolean fitSystemWindows(Rect insets) {
6102        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6103            // If we're not in the process of dispatching the newer apply insets call,
6104            // that means we're not in the compatibility path. Dispatch into the newer
6105            // apply insets path and take things from there.
6106            try {
6107                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6108                return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets();
6109            } finally {
6110                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6111            }
6112        } else {
6113            // We're being called from the newer apply insets path.
6114            // Perform the standard fallback behavior.
6115            return fitSystemWindowsInt(insets);
6116        }
6117    }
6118
6119    private boolean fitSystemWindowsInt(Rect insets) {
6120        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6121            mUserPaddingStart = UNDEFINED_PADDING;
6122            mUserPaddingEnd = UNDEFINED_PADDING;
6123            Rect localInsets = sThreadLocal.get();
6124            if (localInsets == null) {
6125                localInsets = new Rect();
6126                sThreadLocal.set(localInsets);
6127            }
6128            boolean res = computeFitSystemWindows(insets, localInsets);
6129            mUserPaddingLeftInitial = localInsets.left;
6130            mUserPaddingRightInitial = localInsets.right;
6131            internalSetPadding(localInsets.left, localInsets.top,
6132                    localInsets.right, localInsets.bottom);
6133            return res;
6134        }
6135        return false;
6136    }
6137
6138    /**
6139     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6140     *
6141     * <p>This method should be overridden by views that wish to apply a policy different from or
6142     * in addition to the default behavior. Clients that wish to force a view subtree
6143     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6144     *
6145     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6146     * it will be called during dispatch instead of this method. The listener may optionally
6147     * call this method from its own implementation if it wishes to apply the view's default
6148     * insets policy in addition to its own.</p>
6149     *
6150     * <p>Implementations of this method should either return the insets parameter unchanged
6151     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6152     * that this view applied itself. This allows new inset types added in future platform
6153     * versions to pass through existing implementations unchanged without being erroneously
6154     * consumed.</p>
6155     *
6156     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6157     * property is set then the view will consume the system window insets and apply them
6158     * as padding for the view.</p>
6159     *
6160     * @param insets Insets to apply
6161     * @return The supplied insets with any applied insets consumed
6162     */
6163    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6164        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6165            // We weren't called from within a direct call to fitSystemWindows,
6166            // call into it as a fallback in case we're in a class that overrides it
6167            // and has logic to perform.
6168            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6169                return insets.consumeSystemWindowInsets();
6170            }
6171        } else {
6172            // We were called from within a direct call to fitSystemWindows.
6173            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6174                return insets.consumeSystemWindowInsets();
6175            }
6176        }
6177        return insets;
6178    }
6179
6180    /**
6181     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6182     * window insets to this view. The listener's
6183     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6184     * method will be called instead of the view's
6185     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6186     *
6187     * @param listener Listener to set
6188     *
6189     * @see #onApplyWindowInsets(WindowInsets)
6190     */
6191    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6192        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6193    }
6194
6195    /**
6196     * Request to apply the given window insets to this view or another view in its subtree.
6197     *
6198     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6199     * obscured by window decorations or overlays. This can include the status and navigation bars,
6200     * action bars, input methods and more. New inset categories may be added in the future.
6201     * The method returns the insets provided minus any that were applied by this view or its
6202     * children.</p>
6203     *
6204     * <p>Clients wishing to provide custom behavior should override the
6205     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6206     * {@link OnApplyWindowInsetsListener} via the
6207     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6208     * method.</p>
6209     *
6210     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6211     * </p>
6212     *
6213     * @param insets Insets to apply
6214     * @return The provided insets minus the insets that were consumed
6215     */
6216    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6217        try {
6218            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6219            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6220                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6221            } else {
6222                return onApplyWindowInsets(insets);
6223            }
6224        } finally {
6225            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6226        }
6227    }
6228
6229    /**
6230     * @hide Compute the insets that should be consumed by this view and the ones
6231     * that should propagate to those under it.
6232     */
6233    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6234        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6235                || mAttachInfo == null
6236                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6237                        && !mAttachInfo.mOverscanRequested)) {
6238            outLocalInsets.set(inoutInsets);
6239            inoutInsets.set(0, 0, 0, 0);
6240            return true;
6241        } else {
6242            // The application wants to take care of fitting system window for
6243            // the content...  however we still need to take care of any overscan here.
6244            final Rect overscan = mAttachInfo.mOverscanInsets;
6245            outLocalInsets.set(overscan);
6246            inoutInsets.left -= overscan.left;
6247            inoutInsets.top -= overscan.top;
6248            inoutInsets.right -= overscan.right;
6249            inoutInsets.bottom -= overscan.bottom;
6250            return false;
6251        }
6252    }
6253
6254    /**
6255     * Sets whether or not this view should account for system screen decorations
6256     * such as the status bar and inset its content; that is, controlling whether
6257     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6258     * executed.  See that method for more details.
6259     *
6260     * <p>Note that if you are providing your own implementation of
6261     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6262     * flag to true -- your implementation will be overriding the default
6263     * implementation that checks this flag.
6264     *
6265     * @param fitSystemWindows If true, then the default implementation of
6266     * {@link #fitSystemWindows(Rect)} will be executed.
6267     *
6268     * @attr ref android.R.styleable#View_fitsSystemWindows
6269     * @see #getFitsSystemWindows()
6270     * @see #fitSystemWindows(Rect)
6271     * @see #setSystemUiVisibility(int)
6272     */
6273    public void setFitsSystemWindows(boolean fitSystemWindows) {
6274        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6275    }
6276
6277    /**
6278     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6279     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6280     * will be executed.
6281     *
6282     * @return {@code true} if the default implementation of
6283     * {@link #fitSystemWindows(Rect)} will be executed.
6284     *
6285     * @attr ref android.R.styleable#View_fitsSystemWindows
6286     * @see #setFitsSystemWindows(boolean)
6287     * @see #fitSystemWindows(Rect)
6288     * @see #setSystemUiVisibility(int)
6289     */
6290    public boolean getFitsSystemWindows() {
6291        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6292    }
6293
6294    /** @hide */
6295    public boolean fitsSystemWindows() {
6296        return getFitsSystemWindows();
6297    }
6298
6299    /**
6300     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6301     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6302     */
6303    public void requestFitSystemWindows() {
6304        if (mParent != null) {
6305            mParent.requestFitSystemWindows();
6306        }
6307    }
6308
6309    /**
6310     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6311     */
6312    public void requestApplyInsets() {
6313        requestFitSystemWindows();
6314    }
6315
6316    /**
6317     * For use by PhoneWindow to make its own system window fitting optional.
6318     * @hide
6319     */
6320    public void makeOptionalFitsSystemWindows() {
6321        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6322    }
6323
6324    /**
6325     * Returns the visibility status for this view.
6326     *
6327     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6328     * @attr ref android.R.styleable#View_visibility
6329     */
6330    @ViewDebug.ExportedProperty(mapping = {
6331        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6332        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6333        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6334    })
6335    @Visibility
6336    public int getVisibility() {
6337        return mViewFlags & VISIBILITY_MASK;
6338    }
6339
6340    /**
6341     * Set the enabled state of this view.
6342     *
6343     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6344     * @attr ref android.R.styleable#View_visibility
6345     */
6346    @RemotableViewMethod
6347    public void setVisibility(@Visibility int visibility) {
6348        setFlags(visibility, VISIBILITY_MASK);
6349        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6350    }
6351
6352    /**
6353     * Returns the enabled status for this view. The interpretation of the
6354     * enabled state varies by subclass.
6355     *
6356     * @return True if this view is enabled, false otherwise.
6357     */
6358    @ViewDebug.ExportedProperty
6359    public boolean isEnabled() {
6360        return (mViewFlags & ENABLED_MASK) == ENABLED;
6361    }
6362
6363    /**
6364     * Set the enabled state of this view. The interpretation of the enabled
6365     * state varies by subclass.
6366     *
6367     * @param enabled True if this view is enabled, false otherwise.
6368     */
6369    @RemotableViewMethod
6370    public void setEnabled(boolean enabled) {
6371        if (enabled == isEnabled()) return;
6372
6373        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6374
6375        /*
6376         * The View most likely has to change its appearance, so refresh
6377         * the drawable state.
6378         */
6379        refreshDrawableState();
6380
6381        // Invalidate too, since the default behavior for views is to be
6382        // be drawn at 50% alpha rather than to change the drawable.
6383        invalidate(true);
6384
6385        if (!enabled) {
6386            cancelPendingInputEvents();
6387        }
6388    }
6389
6390    /**
6391     * Set whether this view can receive the focus.
6392     *
6393     * Setting this to false will also ensure that this view is not focusable
6394     * in touch mode.
6395     *
6396     * @param focusable If true, this view can receive the focus.
6397     *
6398     * @see #setFocusableInTouchMode(boolean)
6399     * @attr ref android.R.styleable#View_focusable
6400     */
6401    public void setFocusable(boolean focusable) {
6402        if (!focusable) {
6403            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6404        }
6405        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6406    }
6407
6408    /**
6409     * Set whether this view can receive focus while in touch mode.
6410     *
6411     * Setting this to true will also ensure that this view is focusable.
6412     *
6413     * @param focusableInTouchMode If true, this view can receive the focus while
6414     *   in touch mode.
6415     *
6416     * @see #setFocusable(boolean)
6417     * @attr ref android.R.styleable#View_focusableInTouchMode
6418     */
6419    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6420        // Focusable in touch mode should always be set before the focusable flag
6421        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6422        // which, in touch mode, will not successfully request focus on this view
6423        // because the focusable in touch mode flag is not set
6424        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6425        if (focusableInTouchMode) {
6426            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6427        }
6428    }
6429
6430    /**
6431     * Set whether this view should have sound effects enabled for events such as
6432     * clicking and touching.
6433     *
6434     * <p>You may wish to disable sound effects for a view if you already play sounds,
6435     * for instance, a dial key that plays dtmf tones.
6436     *
6437     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6438     * @see #isSoundEffectsEnabled()
6439     * @see #playSoundEffect(int)
6440     * @attr ref android.R.styleable#View_soundEffectsEnabled
6441     */
6442    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6443        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6444    }
6445
6446    /**
6447     * @return whether this view should have sound effects enabled for events such as
6448     *     clicking and touching.
6449     *
6450     * @see #setSoundEffectsEnabled(boolean)
6451     * @see #playSoundEffect(int)
6452     * @attr ref android.R.styleable#View_soundEffectsEnabled
6453     */
6454    @ViewDebug.ExportedProperty
6455    public boolean isSoundEffectsEnabled() {
6456        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6457    }
6458
6459    /**
6460     * Set whether this view should have haptic feedback for events such as
6461     * long presses.
6462     *
6463     * <p>You may wish to disable haptic feedback if your view already controls
6464     * its own haptic feedback.
6465     *
6466     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6467     * @see #isHapticFeedbackEnabled()
6468     * @see #performHapticFeedback(int)
6469     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6470     */
6471    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6472        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6473    }
6474
6475    /**
6476     * @return whether this view should have haptic feedback enabled for events
6477     * long presses.
6478     *
6479     * @see #setHapticFeedbackEnabled(boolean)
6480     * @see #performHapticFeedback(int)
6481     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6482     */
6483    @ViewDebug.ExportedProperty
6484    public boolean isHapticFeedbackEnabled() {
6485        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6486    }
6487
6488    /**
6489     * Returns the layout direction for this view.
6490     *
6491     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6492     *   {@link #LAYOUT_DIRECTION_RTL},
6493     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6494     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6495     *
6496     * @attr ref android.R.styleable#View_layoutDirection
6497     *
6498     * @hide
6499     */
6500    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6501        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6502        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6503        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6504        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6505    })
6506    @LayoutDir
6507    public int getRawLayoutDirection() {
6508        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6509    }
6510
6511    /**
6512     * Set the layout direction for this view. This will propagate a reset of layout direction
6513     * resolution to the view's children and resolve layout direction for this view.
6514     *
6515     * @param layoutDirection the layout direction to set. Should be one of:
6516     *
6517     * {@link #LAYOUT_DIRECTION_LTR},
6518     * {@link #LAYOUT_DIRECTION_RTL},
6519     * {@link #LAYOUT_DIRECTION_INHERIT},
6520     * {@link #LAYOUT_DIRECTION_LOCALE}.
6521     *
6522     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6523     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6524     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6525     *
6526     * @attr ref android.R.styleable#View_layoutDirection
6527     */
6528    @RemotableViewMethod
6529    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6530        if (getRawLayoutDirection() != layoutDirection) {
6531            // Reset the current layout direction and the resolved one
6532            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6533            resetRtlProperties();
6534            // Set the new layout direction (filtered)
6535            mPrivateFlags2 |=
6536                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6537            // We need to resolve all RTL properties as they all depend on layout direction
6538            resolveRtlPropertiesIfNeeded();
6539            requestLayout();
6540            invalidate(true);
6541        }
6542    }
6543
6544    /**
6545     * Returns the resolved layout direction for this view.
6546     *
6547     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6548     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6549     *
6550     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6551     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6552     *
6553     * @attr ref android.R.styleable#View_layoutDirection
6554     */
6555    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6556        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6557        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6558    })
6559    @ResolvedLayoutDir
6560    public int getLayoutDirection() {
6561        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6562        if (targetSdkVersion < JELLY_BEAN_MR1) {
6563            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6564            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6565        }
6566        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6567                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6568    }
6569
6570    /**
6571     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6572     * layout attribute and/or the inherited value from the parent
6573     *
6574     * @return true if the layout is right-to-left.
6575     *
6576     * @hide
6577     */
6578    @ViewDebug.ExportedProperty(category = "layout")
6579    public boolean isLayoutRtl() {
6580        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6581    }
6582
6583    /**
6584     * Indicates whether the view is currently tracking transient state that the
6585     * app should not need to concern itself with saving and restoring, but that
6586     * the framework should take special note to preserve when possible.
6587     *
6588     * <p>A view with transient state cannot be trivially rebound from an external
6589     * data source, such as an adapter binding item views in a list. This may be
6590     * because the view is performing an animation, tracking user selection
6591     * of content, or similar.</p>
6592     *
6593     * @return true if the view has transient state
6594     */
6595    @ViewDebug.ExportedProperty(category = "layout")
6596    public boolean hasTransientState() {
6597        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6598    }
6599
6600    /**
6601     * Set whether this view is currently tracking transient state that the
6602     * framework should attempt to preserve when possible. This flag is reference counted,
6603     * so every call to setHasTransientState(true) should be paired with a later call
6604     * to setHasTransientState(false).
6605     *
6606     * <p>A view with transient state cannot be trivially rebound from an external
6607     * data source, such as an adapter binding item views in a list. This may be
6608     * because the view is performing an animation, tracking user selection
6609     * of content, or similar.</p>
6610     *
6611     * @param hasTransientState true if this view has transient state
6612     */
6613    public void setHasTransientState(boolean hasTransientState) {
6614        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6615                mTransientStateCount - 1;
6616        if (mTransientStateCount < 0) {
6617            mTransientStateCount = 0;
6618            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6619                    "unmatched pair of setHasTransientState calls");
6620        } else if ((hasTransientState && mTransientStateCount == 1) ||
6621                (!hasTransientState && mTransientStateCount == 0)) {
6622            // update flag if we've just incremented up from 0 or decremented down to 0
6623            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6624                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6625            if (mParent != null) {
6626                try {
6627                    mParent.childHasTransientStateChanged(this, hasTransientState);
6628                } catch (AbstractMethodError e) {
6629                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6630                            " does not fully implement ViewParent", e);
6631                }
6632            }
6633        }
6634    }
6635
6636    /**
6637     * Returns true if this view is currently attached to a window.
6638     */
6639    public boolean isAttachedToWindow() {
6640        return mAttachInfo != null;
6641    }
6642
6643    /**
6644     * Returns true if this view has been through at least one layout since it
6645     * was last attached to or detached from a window.
6646     */
6647    public boolean isLaidOut() {
6648        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6649    }
6650
6651    /**
6652     * If this view doesn't do any drawing on its own, set this flag to
6653     * allow further optimizations. By default, this flag is not set on
6654     * View, but could be set on some View subclasses such as ViewGroup.
6655     *
6656     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6657     * you should clear this flag.
6658     *
6659     * @param willNotDraw whether or not this View draw on its own
6660     */
6661    public void setWillNotDraw(boolean willNotDraw) {
6662        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6663    }
6664
6665    /**
6666     * Returns whether or not this View draws on its own.
6667     *
6668     * @return true if this view has nothing to draw, false otherwise
6669     */
6670    @ViewDebug.ExportedProperty(category = "drawing")
6671    public boolean willNotDraw() {
6672        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6673    }
6674
6675    /**
6676     * When a View's drawing cache is enabled, drawing is redirected to an
6677     * offscreen bitmap. Some views, like an ImageView, must be able to
6678     * bypass this mechanism if they already draw a single bitmap, to avoid
6679     * unnecessary usage of the memory.
6680     *
6681     * @param willNotCacheDrawing true if this view does not cache its
6682     *        drawing, false otherwise
6683     */
6684    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6685        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6686    }
6687
6688    /**
6689     * Returns whether or not this View can cache its drawing or not.
6690     *
6691     * @return true if this view does not cache its drawing, false otherwise
6692     */
6693    @ViewDebug.ExportedProperty(category = "drawing")
6694    public boolean willNotCacheDrawing() {
6695        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6696    }
6697
6698    /**
6699     * Indicates whether this view reacts to click events or not.
6700     *
6701     * @return true if the view is clickable, false otherwise
6702     *
6703     * @see #setClickable(boolean)
6704     * @attr ref android.R.styleable#View_clickable
6705     */
6706    @ViewDebug.ExportedProperty
6707    public boolean isClickable() {
6708        return (mViewFlags & CLICKABLE) == CLICKABLE;
6709    }
6710
6711    /**
6712     * Enables or disables click events for this view. When a view
6713     * is clickable it will change its state to "pressed" on every click.
6714     * Subclasses should set the view clickable to visually react to
6715     * user's clicks.
6716     *
6717     * @param clickable true to make the view clickable, false otherwise
6718     *
6719     * @see #isClickable()
6720     * @attr ref android.R.styleable#View_clickable
6721     */
6722    public void setClickable(boolean clickable) {
6723        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6724    }
6725
6726    /**
6727     * Indicates whether this view reacts to long click events or not.
6728     *
6729     * @return true if the view is long clickable, false otherwise
6730     *
6731     * @see #setLongClickable(boolean)
6732     * @attr ref android.R.styleable#View_longClickable
6733     */
6734    public boolean isLongClickable() {
6735        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6736    }
6737
6738    /**
6739     * Enables or disables long click events for this view. When a view is long
6740     * clickable it reacts to the user holding down the button for a longer
6741     * duration than a tap. This event can either launch the listener or a
6742     * context menu.
6743     *
6744     * @param longClickable true to make the view long clickable, false otherwise
6745     * @see #isLongClickable()
6746     * @attr ref android.R.styleable#View_longClickable
6747     */
6748    public void setLongClickable(boolean longClickable) {
6749        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6750    }
6751
6752    /**
6753     * Sets the pressed state for this view and provides a touch coordinate for
6754     * animation hinting.
6755     *
6756     * @param pressed Pass true to set the View's internal state to "pressed",
6757     *            or false to reverts the View's internal state from a
6758     *            previously set "pressed" state.
6759     * @param x The x coordinate of the touch that caused the press
6760     * @param y The y coordinate of the touch that caused the press
6761     */
6762    private void setPressed(boolean pressed, float x, float y) {
6763        if (pressed) {
6764            setHotspot(x, y);
6765        }
6766
6767        setPressed(pressed);
6768    }
6769
6770    /**
6771     * Sets the pressed state for this view.
6772     *
6773     * @see #isClickable()
6774     * @see #setClickable(boolean)
6775     *
6776     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6777     *        the View's internal state from a previously set "pressed" state.
6778     */
6779    public void setPressed(boolean pressed) {
6780        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6781
6782        if (pressed) {
6783            mPrivateFlags |= PFLAG_PRESSED;
6784        } else {
6785            mPrivateFlags &= ~PFLAG_PRESSED;
6786        }
6787
6788        if (needsRefresh) {
6789            refreshDrawableState();
6790        }
6791        dispatchSetPressed(pressed);
6792    }
6793
6794    /**
6795     * Dispatch setPressed to all of this View's children.
6796     *
6797     * @see #setPressed(boolean)
6798     *
6799     * @param pressed The new pressed state
6800     */
6801    protected void dispatchSetPressed(boolean pressed) {
6802    }
6803
6804    /**
6805     * Indicates whether the view is currently in pressed state. Unless
6806     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6807     * the pressed state.
6808     *
6809     * @see #setPressed(boolean)
6810     * @see #isClickable()
6811     * @see #setClickable(boolean)
6812     *
6813     * @return true if the view is currently pressed, false otherwise
6814     */
6815    public boolean isPressed() {
6816        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6817    }
6818
6819    /**
6820     * Indicates whether this view will save its state (that is,
6821     * whether its {@link #onSaveInstanceState} method will be called).
6822     *
6823     * @return Returns true if the view state saving is enabled, else false.
6824     *
6825     * @see #setSaveEnabled(boolean)
6826     * @attr ref android.R.styleable#View_saveEnabled
6827     */
6828    public boolean isSaveEnabled() {
6829        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6830    }
6831
6832    /**
6833     * Controls whether the saving of this view's state is
6834     * enabled (that is, whether its {@link #onSaveInstanceState} method
6835     * will be called).  Note that even if freezing is enabled, the
6836     * view still must have an id assigned to it (via {@link #setId(int)})
6837     * for its state to be saved.  This flag can only disable the
6838     * saving of this view; any child views may still have their state saved.
6839     *
6840     * @param enabled Set to false to <em>disable</em> state saving, or true
6841     * (the default) to allow it.
6842     *
6843     * @see #isSaveEnabled()
6844     * @see #setId(int)
6845     * @see #onSaveInstanceState()
6846     * @attr ref android.R.styleable#View_saveEnabled
6847     */
6848    public void setSaveEnabled(boolean enabled) {
6849        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6850    }
6851
6852    /**
6853     * Gets whether the framework should discard touches when the view's
6854     * window is obscured by another visible window.
6855     * Refer to the {@link View} security documentation for more details.
6856     *
6857     * @return True if touch filtering is enabled.
6858     *
6859     * @see #setFilterTouchesWhenObscured(boolean)
6860     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6861     */
6862    @ViewDebug.ExportedProperty
6863    public boolean getFilterTouchesWhenObscured() {
6864        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6865    }
6866
6867    /**
6868     * Sets whether the framework should discard touches when the view's
6869     * window is obscured by another visible window.
6870     * Refer to the {@link View} security documentation for more details.
6871     *
6872     * @param enabled True if touch filtering should be enabled.
6873     *
6874     * @see #getFilterTouchesWhenObscured
6875     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6876     */
6877    public void setFilterTouchesWhenObscured(boolean enabled) {
6878        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6879                FILTER_TOUCHES_WHEN_OBSCURED);
6880    }
6881
6882    /**
6883     * Indicates whether the entire hierarchy under this view will save its
6884     * state when a state saving traversal occurs from its parent.  The default
6885     * is true; if false, these views will not be saved unless
6886     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6887     *
6888     * @return Returns true if the view state saving from parent is enabled, else false.
6889     *
6890     * @see #setSaveFromParentEnabled(boolean)
6891     */
6892    public boolean isSaveFromParentEnabled() {
6893        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6894    }
6895
6896    /**
6897     * Controls whether the entire hierarchy under this view will save its
6898     * state when a state saving traversal occurs from its parent.  The default
6899     * is true; if false, these views will not be saved unless
6900     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6901     *
6902     * @param enabled Set to false to <em>disable</em> state saving, or true
6903     * (the default) to allow it.
6904     *
6905     * @see #isSaveFromParentEnabled()
6906     * @see #setId(int)
6907     * @see #onSaveInstanceState()
6908     */
6909    public void setSaveFromParentEnabled(boolean enabled) {
6910        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6911    }
6912
6913
6914    /**
6915     * Returns whether this View is able to take focus.
6916     *
6917     * @return True if this view can take focus, or false otherwise.
6918     * @attr ref android.R.styleable#View_focusable
6919     */
6920    @ViewDebug.ExportedProperty(category = "focus")
6921    public final boolean isFocusable() {
6922        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6923    }
6924
6925    /**
6926     * When a view is focusable, it may not want to take focus when in touch mode.
6927     * For example, a button would like focus when the user is navigating via a D-pad
6928     * so that the user can click on it, but once the user starts touching the screen,
6929     * the button shouldn't take focus
6930     * @return Whether the view is focusable in touch mode.
6931     * @attr ref android.R.styleable#View_focusableInTouchMode
6932     */
6933    @ViewDebug.ExportedProperty
6934    public final boolean isFocusableInTouchMode() {
6935        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6936    }
6937
6938    /**
6939     * Find the nearest view in the specified direction that can take focus.
6940     * This does not actually give focus to that view.
6941     *
6942     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6943     *
6944     * @return The nearest focusable in the specified direction, or null if none
6945     *         can be found.
6946     */
6947    public View focusSearch(@FocusRealDirection int direction) {
6948        if (mParent != null) {
6949            return mParent.focusSearch(this, direction);
6950        } else {
6951            return null;
6952        }
6953    }
6954
6955    /**
6956     * This method is the last chance for the focused view and its ancestors to
6957     * respond to an arrow key. This is called when the focused view did not
6958     * consume the key internally, nor could the view system find a new view in
6959     * the requested direction to give focus to.
6960     *
6961     * @param focused The currently focused view.
6962     * @param direction The direction focus wants to move. One of FOCUS_UP,
6963     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6964     * @return True if the this view consumed this unhandled move.
6965     */
6966    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6967        return false;
6968    }
6969
6970    /**
6971     * If a user manually specified the next view id for a particular direction,
6972     * use the root to look up the view.
6973     * @param root The root view of the hierarchy containing this view.
6974     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6975     * or FOCUS_BACKWARD.
6976     * @return The user specified next view, or null if there is none.
6977     */
6978    View findUserSetNextFocus(View root, @FocusDirection int direction) {
6979        switch (direction) {
6980            case FOCUS_LEFT:
6981                if (mNextFocusLeftId == View.NO_ID) return null;
6982                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6983            case FOCUS_RIGHT:
6984                if (mNextFocusRightId == View.NO_ID) return null;
6985                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6986            case FOCUS_UP:
6987                if (mNextFocusUpId == View.NO_ID) return null;
6988                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6989            case FOCUS_DOWN:
6990                if (mNextFocusDownId == View.NO_ID) return null;
6991                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6992            case FOCUS_FORWARD:
6993                if (mNextFocusForwardId == View.NO_ID) return null;
6994                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6995            case FOCUS_BACKWARD: {
6996                if (mID == View.NO_ID) return null;
6997                final int id = mID;
6998                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6999                    @Override
7000                    public boolean apply(View t) {
7001                        return t.mNextFocusForwardId == id;
7002                    }
7003                });
7004            }
7005        }
7006        return null;
7007    }
7008
7009    private View findViewInsideOutShouldExist(View root, int id) {
7010        if (mMatchIdPredicate == null) {
7011            mMatchIdPredicate = new MatchIdPredicate();
7012        }
7013        mMatchIdPredicate.mId = id;
7014        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7015        if (result == null) {
7016            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7017        }
7018        return result;
7019    }
7020
7021    /**
7022     * Find and return all focusable views that are descendants of this view,
7023     * possibly including this view if it is focusable itself.
7024     *
7025     * @param direction The direction of the focus
7026     * @return A list of focusable views
7027     */
7028    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7029        ArrayList<View> result = new ArrayList<View>(24);
7030        addFocusables(result, direction);
7031        return result;
7032    }
7033
7034    /**
7035     * Add any focusable views that are descendants of this view (possibly
7036     * including this view if it is focusable itself) to views.  If we are in touch mode,
7037     * only add views that are also focusable in touch mode.
7038     *
7039     * @param views Focusable views found so far
7040     * @param direction The direction of the focus
7041     */
7042    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7043        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7044    }
7045
7046    /**
7047     * Adds any focusable views that are descendants of this view (possibly
7048     * including this view if it is focusable itself) to views. This method
7049     * adds all focusable views regardless if we are in touch mode or
7050     * only views focusable in touch mode if we are in touch mode or
7051     * only views that can take accessibility focus if accessibility is enabeld
7052     * depending on the focusable mode paramater.
7053     *
7054     * @param views Focusable views found so far or null if all we are interested is
7055     *        the number of focusables.
7056     * @param direction The direction of the focus.
7057     * @param focusableMode The type of focusables to be added.
7058     *
7059     * @see #FOCUSABLES_ALL
7060     * @see #FOCUSABLES_TOUCH_MODE
7061     */
7062    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7063            @FocusableMode int focusableMode) {
7064        if (views == null) {
7065            return;
7066        }
7067        if (!isFocusable()) {
7068            return;
7069        }
7070        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7071                && isInTouchMode() && !isFocusableInTouchMode()) {
7072            return;
7073        }
7074        views.add(this);
7075    }
7076
7077    /**
7078     * Finds the Views that contain given text. The containment is case insensitive.
7079     * The search is performed by either the text that the View renders or the content
7080     * description that describes the view for accessibility purposes and the view does
7081     * not render or both. Clients can specify how the search is to be performed via
7082     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7083     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7084     *
7085     * @param outViews The output list of matching Views.
7086     * @param searched The text to match against.
7087     *
7088     * @see #FIND_VIEWS_WITH_TEXT
7089     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7090     * @see #setContentDescription(CharSequence)
7091     */
7092    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7093            @FindViewFlags int flags) {
7094        if (getAccessibilityNodeProvider() != null) {
7095            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7096                outViews.add(this);
7097            }
7098        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7099                && (searched != null && searched.length() > 0)
7100                && (mContentDescription != null && mContentDescription.length() > 0)) {
7101            String searchedLowerCase = searched.toString().toLowerCase();
7102            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7103            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7104                outViews.add(this);
7105            }
7106        }
7107    }
7108
7109    /**
7110     * Find and return all touchable views that are descendants of this view,
7111     * possibly including this view if it is touchable itself.
7112     *
7113     * @return A list of touchable views
7114     */
7115    public ArrayList<View> getTouchables() {
7116        ArrayList<View> result = new ArrayList<View>();
7117        addTouchables(result);
7118        return result;
7119    }
7120
7121    /**
7122     * Add any touchable views that are descendants of this view (possibly
7123     * including this view if it is touchable itself) to views.
7124     *
7125     * @param views Touchable views found so far
7126     */
7127    public void addTouchables(ArrayList<View> views) {
7128        final int viewFlags = mViewFlags;
7129
7130        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7131                && (viewFlags & ENABLED_MASK) == ENABLED) {
7132            views.add(this);
7133        }
7134    }
7135
7136    /**
7137     * Returns whether this View is accessibility focused.
7138     *
7139     * @return True if this View is accessibility focused.
7140     */
7141    public boolean isAccessibilityFocused() {
7142        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7143    }
7144
7145    /**
7146     * Call this to try to give accessibility focus to this view.
7147     *
7148     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7149     * returns false or the view is no visible or the view already has accessibility
7150     * focus.
7151     *
7152     * See also {@link #focusSearch(int)}, which is what you call to say that you
7153     * have focus, and you want your parent to look for the next one.
7154     *
7155     * @return Whether this view actually took accessibility focus.
7156     *
7157     * @hide
7158     */
7159    public boolean requestAccessibilityFocus() {
7160        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7161        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7162            return false;
7163        }
7164        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7165            return false;
7166        }
7167        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7168            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7169            ViewRootImpl viewRootImpl = getViewRootImpl();
7170            if (viewRootImpl != null) {
7171                viewRootImpl.setAccessibilityFocus(this, null);
7172            }
7173            Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect();
7174            getDrawingRect(rect);
7175            requestRectangleOnScreen(rect, false);
7176            invalidate();
7177            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7178            return true;
7179        }
7180        return false;
7181    }
7182
7183    /**
7184     * Call this to try to clear accessibility focus of this view.
7185     *
7186     * See also {@link #focusSearch(int)}, which is what you call to say that you
7187     * have focus, and you want your parent to look for the next one.
7188     *
7189     * @hide
7190     */
7191    public void clearAccessibilityFocus() {
7192        clearAccessibilityFocusNoCallbacks();
7193        // Clear the global reference of accessibility focus if this
7194        // view or any of its descendants had accessibility focus.
7195        ViewRootImpl viewRootImpl = getViewRootImpl();
7196        if (viewRootImpl != null) {
7197            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7198            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7199                viewRootImpl.setAccessibilityFocus(null, null);
7200            }
7201        }
7202    }
7203
7204    private void sendAccessibilityHoverEvent(int eventType) {
7205        // Since we are not delivering to a client accessibility events from not
7206        // important views (unless the clinet request that) we need to fire the
7207        // event from the deepest view exposed to the client. As a consequence if
7208        // the user crosses a not exposed view the client will see enter and exit
7209        // of the exposed predecessor followed by and enter and exit of that same
7210        // predecessor when entering and exiting the not exposed descendant. This
7211        // is fine since the client has a clear idea which view is hovered at the
7212        // price of a couple more events being sent. This is a simple and
7213        // working solution.
7214        View source = this;
7215        while (true) {
7216            if (source.includeForAccessibility()) {
7217                source.sendAccessibilityEvent(eventType);
7218                return;
7219            }
7220            ViewParent parent = source.getParent();
7221            if (parent instanceof View) {
7222                source = (View) parent;
7223            } else {
7224                return;
7225            }
7226        }
7227    }
7228
7229    /**
7230     * Clears accessibility focus without calling any callback methods
7231     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7232     * is used for clearing accessibility focus when giving this focus to
7233     * another view.
7234     */
7235    void clearAccessibilityFocusNoCallbacks() {
7236        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7237            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7238            invalidate();
7239            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7240        }
7241    }
7242
7243    /**
7244     * Call this to try to give focus to a specific view or to one of its
7245     * descendants.
7246     *
7247     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7248     * false), or if it is focusable and it is not focusable in touch mode
7249     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7250     *
7251     * See also {@link #focusSearch(int)}, which is what you call to say that you
7252     * have focus, and you want your parent to look for the next one.
7253     *
7254     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7255     * {@link #FOCUS_DOWN} and <code>null</code>.
7256     *
7257     * @return Whether this view or one of its descendants actually took focus.
7258     */
7259    public final boolean requestFocus() {
7260        return requestFocus(View.FOCUS_DOWN);
7261    }
7262
7263    /**
7264     * Call this to try to give focus to a specific view or to one of its
7265     * descendants and give it a hint about what direction focus is heading.
7266     *
7267     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7268     * false), or if it is focusable and it is not focusable in touch mode
7269     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7270     *
7271     * See also {@link #focusSearch(int)}, which is what you call to say that you
7272     * have focus, and you want your parent to look for the next one.
7273     *
7274     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7275     * <code>null</code> set for the previously focused rectangle.
7276     *
7277     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7278     * @return Whether this view or one of its descendants actually took focus.
7279     */
7280    public final boolean requestFocus(int direction) {
7281        return requestFocus(direction, null);
7282    }
7283
7284    /**
7285     * Call this to try to give focus to a specific view or to one of its descendants
7286     * and give it hints about the direction and a specific rectangle that the focus
7287     * is coming from.  The rectangle can help give larger views a finer grained hint
7288     * about where focus is coming from, and therefore, where to show selection, or
7289     * forward focus change internally.
7290     *
7291     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7292     * false), or if it is focusable and it is not focusable in touch mode
7293     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7294     *
7295     * A View will not take focus if it is not visible.
7296     *
7297     * A View will not take focus if one of its parents has
7298     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7299     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7300     *
7301     * See also {@link #focusSearch(int)}, which is what you call to say that you
7302     * have focus, and you want your parent to look for the next one.
7303     *
7304     * You may wish to override this method if your custom {@link View} has an internal
7305     * {@link View} that it wishes to forward the request to.
7306     *
7307     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7308     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7309     *        to give a finer grained hint about where focus is coming from.  May be null
7310     *        if there is no hint.
7311     * @return Whether this view or one of its descendants actually took focus.
7312     */
7313    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7314        return requestFocusNoSearch(direction, previouslyFocusedRect);
7315    }
7316
7317    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7318        // need to be focusable
7319        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7320                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7321            return false;
7322        }
7323
7324        // need to be focusable in touch mode if in touch mode
7325        if (isInTouchMode() &&
7326            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7327               return false;
7328        }
7329
7330        // need to not have any parents blocking us
7331        if (hasAncestorThatBlocksDescendantFocus()) {
7332            return false;
7333        }
7334
7335        handleFocusGainInternal(direction, previouslyFocusedRect);
7336        return true;
7337    }
7338
7339    /**
7340     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7341     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7342     * touch mode to request focus when they are touched.
7343     *
7344     * @return Whether this view or one of its descendants actually took focus.
7345     *
7346     * @see #isInTouchMode()
7347     *
7348     */
7349    public final boolean requestFocusFromTouch() {
7350        // Leave touch mode if we need to
7351        if (isInTouchMode()) {
7352            ViewRootImpl viewRoot = getViewRootImpl();
7353            if (viewRoot != null) {
7354                viewRoot.ensureTouchMode(false);
7355            }
7356        }
7357        return requestFocus(View.FOCUS_DOWN);
7358    }
7359
7360    /**
7361     * @return Whether any ancestor of this view blocks descendant focus.
7362     */
7363    private boolean hasAncestorThatBlocksDescendantFocus() {
7364        ViewParent ancestor = mParent;
7365        while (ancestor instanceof ViewGroup) {
7366            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7367            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7368                return true;
7369            } else {
7370                ancestor = vgAncestor.getParent();
7371            }
7372        }
7373        return false;
7374    }
7375
7376    /**
7377     * Gets the mode for determining whether this View is important for accessibility
7378     * which is if it fires accessibility events and if it is reported to
7379     * accessibility services that query the screen.
7380     *
7381     * @return The mode for determining whether a View is important for accessibility.
7382     *
7383     * @attr ref android.R.styleable#View_importantForAccessibility
7384     *
7385     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7386     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7387     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7388     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7389     */
7390    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7391            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7392            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7393            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7394            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7395                    to = "noHideDescendants")
7396        })
7397    public int getImportantForAccessibility() {
7398        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7399                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7400    }
7401
7402    /**
7403     * Sets the live region mode for this view. This indicates to accessibility
7404     * services whether they should automatically notify the user about changes
7405     * to the view's content description or text, or to the content descriptions
7406     * or text of the view's children (where applicable).
7407     * <p>
7408     * For example, in a login screen with a TextView that displays an "incorrect
7409     * password" notification, that view should be marked as a live region with
7410     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7411     * <p>
7412     * To disable change notifications for this view, use
7413     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7414     * mode for most views.
7415     * <p>
7416     * To indicate that the user should be notified of changes, use
7417     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7418     * <p>
7419     * If the view's changes should interrupt ongoing speech and notify the user
7420     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7421     *
7422     * @param mode The live region mode for this view, one of:
7423     *        <ul>
7424     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7425     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7426     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7427     *        </ul>
7428     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7429     */
7430    public void setAccessibilityLiveRegion(int mode) {
7431        if (mode != getAccessibilityLiveRegion()) {
7432            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7433            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7434                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7435            notifyViewAccessibilityStateChangedIfNeeded(
7436                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7437        }
7438    }
7439
7440    /**
7441     * Gets the live region mode for this View.
7442     *
7443     * @return The live region mode for the view.
7444     *
7445     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7446     *
7447     * @see #setAccessibilityLiveRegion(int)
7448     */
7449    public int getAccessibilityLiveRegion() {
7450        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7451                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7452    }
7453
7454    /**
7455     * Sets how to determine whether this view is important for accessibility
7456     * which is if it fires accessibility events and if it is reported to
7457     * accessibility services that query the screen.
7458     *
7459     * @param mode How to determine whether this view is important for accessibility.
7460     *
7461     * @attr ref android.R.styleable#View_importantForAccessibility
7462     *
7463     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7464     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7465     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7466     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7467     */
7468    public void setImportantForAccessibility(int mode) {
7469        final int oldMode = getImportantForAccessibility();
7470        if (mode != oldMode) {
7471            // If we're moving between AUTO and another state, we might not need
7472            // to send a subtree changed notification. We'll store the computed
7473            // importance, since we'll need to check it later to make sure.
7474            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7475                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7476            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7477            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7478            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7479                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7480            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7481                notifySubtreeAccessibilityStateChangedIfNeeded();
7482            } else {
7483                notifyViewAccessibilityStateChangedIfNeeded(
7484                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7485            }
7486        }
7487    }
7488
7489    /**
7490     * Computes whether this view should be exposed for accessibility. In
7491     * general, views that are interactive or provide information are exposed
7492     * while views that serve only as containers are hidden.
7493     * <p>
7494     * If an ancestor of this view has importance
7495     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7496     * returns <code>false</code>.
7497     * <p>
7498     * Otherwise, the value is computed according to the view's
7499     * {@link #getImportantForAccessibility()} value:
7500     * <ol>
7501     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7502     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7503     * </code>
7504     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7505     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7506     * view satisfies any of the following:
7507     * <ul>
7508     * <li>Is actionable, e.g. {@link #isClickable()},
7509     * {@link #isLongClickable()}, or {@link #isFocusable()}
7510     * <li>Has an {@link AccessibilityDelegate}
7511     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7512     * {@link OnKeyListener}, etc.
7513     * <li>Is an accessibility live region, e.g.
7514     * {@link #getAccessibilityLiveRegion()} is not
7515     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7516     * </ul>
7517     * </ol>
7518     *
7519     * @return Whether the view is exposed for accessibility.
7520     * @see #setImportantForAccessibility(int)
7521     * @see #getImportantForAccessibility()
7522     */
7523    public boolean isImportantForAccessibility() {
7524        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7525                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7526        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7527                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7528            return false;
7529        }
7530
7531        // Check parent mode to ensure we're not hidden.
7532        ViewParent parent = mParent;
7533        while (parent instanceof View) {
7534            if (((View) parent).getImportantForAccessibility()
7535                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7536                return false;
7537            }
7538            parent = parent.getParent();
7539        }
7540
7541        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7542                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7543                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7544    }
7545
7546    /**
7547     * Gets the parent for accessibility purposes. Note that the parent for
7548     * accessibility is not necessary the immediate parent. It is the first
7549     * predecessor that is important for accessibility.
7550     *
7551     * @return The parent for accessibility purposes.
7552     */
7553    public ViewParent getParentForAccessibility() {
7554        if (mParent instanceof View) {
7555            View parentView = (View) mParent;
7556            if (parentView.includeForAccessibility()) {
7557                return mParent;
7558            } else {
7559                return mParent.getParentForAccessibility();
7560            }
7561        }
7562        return null;
7563    }
7564
7565    /**
7566     * Adds the children of a given View for accessibility. Since some Views are
7567     * not important for accessibility the children for accessibility are not
7568     * necessarily direct children of the view, rather they are the first level of
7569     * descendants important for accessibility.
7570     *
7571     * @param children The list of children for accessibility.
7572     */
7573    public void addChildrenForAccessibility(ArrayList<View> children) {
7574
7575    }
7576
7577    /**
7578     * Whether to regard this view for accessibility. A view is regarded for
7579     * accessibility if it is important for accessibility or the querying
7580     * accessibility service has explicitly requested that view not
7581     * important for accessibility are regarded.
7582     *
7583     * @return Whether to regard the view for accessibility.
7584     *
7585     * @hide
7586     */
7587    public boolean includeForAccessibility() {
7588        if (mAttachInfo != null) {
7589            return (mAttachInfo.mAccessibilityFetchFlags
7590                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7591                    || isImportantForAccessibility();
7592        }
7593        return false;
7594    }
7595
7596    /**
7597     * Returns whether the View is considered actionable from
7598     * accessibility perspective. Such view are important for
7599     * accessibility.
7600     *
7601     * @return True if the view is actionable for accessibility.
7602     *
7603     * @hide
7604     */
7605    public boolean isActionableForAccessibility() {
7606        return (isClickable() || isLongClickable() || isFocusable());
7607    }
7608
7609    /**
7610     * Returns whether the View has registered callbacks which makes it
7611     * important for accessibility.
7612     *
7613     * @return True if the view is actionable for accessibility.
7614     */
7615    private boolean hasListenersForAccessibility() {
7616        ListenerInfo info = getListenerInfo();
7617        return mTouchDelegate != null || info.mOnKeyListener != null
7618                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7619                || info.mOnHoverListener != null || info.mOnDragListener != null;
7620    }
7621
7622    /**
7623     * Notifies that the accessibility state of this view changed. The change
7624     * is local to this view and does not represent structural changes such
7625     * as children and parent. For example, the view became focusable. The
7626     * notification is at at most once every
7627     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7628     * to avoid unnecessary load to the system. Also once a view has a pending
7629     * notification this method is a NOP until the notification has been sent.
7630     *
7631     * @hide
7632     */
7633    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7634        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7635            return;
7636        }
7637        if (mSendViewStateChangedAccessibilityEvent == null) {
7638            mSendViewStateChangedAccessibilityEvent =
7639                    new SendViewStateChangedAccessibilityEvent();
7640        }
7641        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7642    }
7643
7644    /**
7645     * Notifies that the accessibility state of this view changed. The change
7646     * is *not* local to this view and does represent structural changes such
7647     * as children and parent. For example, the view size changed. The
7648     * notification is at at most once every
7649     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7650     * to avoid unnecessary load to the system. Also once a view has a pending
7651     * notifucation this method is a NOP until the notification has been sent.
7652     *
7653     * @hide
7654     */
7655    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7656        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7657            return;
7658        }
7659        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7660            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7661            if (mParent != null) {
7662                try {
7663                    mParent.notifySubtreeAccessibilityStateChanged(
7664                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7665                } catch (AbstractMethodError e) {
7666                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7667                            " does not fully implement ViewParent", e);
7668                }
7669            }
7670        }
7671    }
7672
7673    /**
7674     * Reset the flag indicating the accessibility state of the subtree rooted
7675     * at this view changed.
7676     */
7677    void resetSubtreeAccessibilityStateChanged() {
7678        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7679    }
7680
7681    /**
7682     * Performs the specified accessibility action on the view. For
7683     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7684     * <p>
7685     * If an {@link AccessibilityDelegate} has been specified via calling
7686     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7687     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7688     * is responsible for handling this call.
7689     * </p>
7690     *
7691     * @param action The action to perform.
7692     * @param arguments Optional action arguments.
7693     * @return Whether the action was performed.
7694     */
7695    public boolean performAccessibilityAction(int action, Bundle arguments) {
7696      if (mAccessibilityDelegate != null) {
7697          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7698      } else {
7699          return performAccessibilityActionInternal(action, arguments);
7700      }
7701    }
7702
7703   /**
7704    * @see #performAccessibilityAction(int, Bundle)
7705    *
7706    * Note: Called from the default {@link AccessibilityDelegate}.
7707    */
7708    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7709        switch (action) {
7710            case AccessibilityNodeInfo.ACTION_CLICK: {
7711                if (isClickable()) {
7712                    performClick();
7713                    return true;
7714                }
7715            } break;
7716            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7717                if (isLongClickable()) {
7718                    performLongClick();
7719                    return true;
7720                }
7721            } break;
7722            case AccessibilityNodeInfo.ACTION_FOCUS: {
7723                if (!hasFocus()) {
7724                    // Get out of touch mode since accessibility
7725                    // wants to move focus around.
7726                    getViewRootImpl().ensureTouchMode(false);
7727                    return requestFocus();
7728                }
7729            } break;
7730            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7731                if (hasFocus()) {
7732                    clearFocus();
7733                    return !isFocused();
7734                }
7735            } break;
7736            case AccessibilityNodeInfo.ACTION_SELECT: {
7737                if (!isSelected()) {
7738                    setSelected(true);
7739                    return isSelected();
7740                }
7741            } break;
7742            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7743                if (isSelected()) {
7744                    setSelected(false);
7745                    return !isSelected();
7746                }
7747            } break;
7748            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7749                if (!isAccessibilityFocused()) {
7750                    return requestAccessibilityFocus();
7751                }
7752            } break;
7753            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7754                if (isAccessibilityFocused()) {
7755                    clearAccessibilityFocus();
7756                    return true;
7757                }
7758            } break;
7759            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7760                if (arguments != null) {
7761                    final int granularity = arguments.getInt(
7762                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7763                    final boolean extendSelection = arguments.getBoolean(
7764                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7765                    return traverseAtGranularity(granularity, true, extendSelection);
7766                }
7767            } break;
7768            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7769                if (arguments != null) {
7770                    final int granularity = arguments.getInt(
7771                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7772                    final boolean extendSelection = arguments.getBoolean(
7773                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7774                    return traverseAtGranularity(granularity, false, extendSelection);
7775                }
7776            } break;
7777            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7778                CharSequence text = getIterableTextForAccessibility();
7779                if (text == null) {
7780                    return false;
7781                }
7782                final int start = (arguments != null) ? arguments.getInt(
7783                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7784                final int end = (arguments != null) ? arguments.getInt(
7785                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7786                // Only cursor position can be specified (selection length == 0)
7787                if ((getAccessibilitySelectionStart() != start
7788                        || getAccessibilitySelectionEnd() != end)
7789                        && (start == end)) {
7790                    setAccessibilitySelection(start, end);
7791                    notifyViewAccessibilityStateChangedIfNeeded(
7792                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7793                    return true;
7794                }
7795            } break;
7796        }
7797        return false;
7798    }
7799
7800    private boolean traverseAtGranularity(int granularity, boolean forward,
7801            boolean extendSelection) {
7802        CharSequence text = getIterableTextForAccessibility();
7803        if (text == null || text.length() == 0) {
7804            return false;
7805        }
7806        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7807        if (iterator == null) {
7808            return false;
7809        }
7810        int current = getAccessibilitySelectionEnd();
7811        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7812            current = forward ? 0 : text.length();
7813        }
7814        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7815        if (range == null) {
7816            return false;
7817        }
7818        final int segmentStart = range[0];
7819        final int segmentEnd = range[1];
7820        int selectionStart;
7821        int selectionEnd;
7822        if (extendSelection && isAccessibilitySelectionExtendable()) {
7823            selectionStart = getAccessibilitySelectionStart();
7824            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7825                selectionStart = forward ? segmentStart : segmentEnd;
7826            }
7827            selectionEnd = forward ? segmentEnd : segmentStart;
7828        } else {
7829            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7830        }
7831        setAccessibilitySelection(selectionStart, selectionEnd);
7832        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7833                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7834        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7835        return true;
7836    }
7837
7838    /**
7839     * Gets the text reported for accessibility purposes.
7840     *
7841     * @return The accessibility text.
7842     *
7843     * @hide
7844     */
7845    public CharSequence getIterableTextForAccessibility() {
7846        return getContentDescription();
7847    }
7848
7849    /**
7850     * Gets whether accessibility selection can be extended.
7851     *
7852     * @return If selection is extensible.
7853     *
7854     * @hide
7855     */
7856    public boolean isAccessibilitySelectionExtendable() {
7857        return false;
7858    }
7859
7860    /**
7861     * @hide
7862     */
7863    public int getAccessibilitySelectionStart() {
7864        return mAccessibilityCursorPosition;
7865    }
7866
7867    /**
7868     * @hide
7869     */
7870    public int getAccessibilitySelectionEnd() {
7871        return getAccessibilitySelectionStart();
7872    }
7873
7874    /**
7875     * @hide
7876     */
7877    public void setAccessibilitySelection(int start, int end) {
7878        if (start ==  end && end == mAccessibilityCursorPosition) {
7879            return;
7880        }
7881        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7882            mAccessibilityCursorPosition = start;
7883        } else {
7884            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7885        }
7886        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7887    }
7888
7889    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7890            int fromIndex, int toIndex) {
7891        if (mParent == null) {
7892            return;
7893        }
7894        AccessibilityEvent event = AccessibilityEvent.obtain(
7895                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7896        onInitializeAccessibilityEvent(event);
7897        onPopulateAccessibilityEvent(event);
7898        event.setFromIndex(fromIndex);
7899        event.setToIndex(toIndex);
7900        event.setAction(action);
7901        event.setMovementGranularity(granularity);
7902        mParent.requestSendAccessibilityEvent(this, event);
7903    }
7904
7905    /**
7906     * @hide
7907     */
7908    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7909        switch (granularity) {
7910            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7911                CharSequence text = getIterableTextForAccessibility();
7912                if (text != null && text.length() > 0) {
7913                    CharacterTextSegmentIterator iterator =
7914                        CharacterTextSegmentIterator.getInstance(
7915                                mContext.getResources().getConfiguration().locale);
7916                    iterator.initialize(text.toString());
7917                    return iterator;
7918                }
7919            } break;
7920            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7921                CharSequence text = getIterableTextForAccessibility();
7922                if (text != null && text.length() > 0) {
7923                    WordTextSegmentIterator iterator =
7924                        WordTextSegmentIterator.getInstance(
7925                                mContext.getResources().getConfiguration().locale);
7926                    iterator.initialize(text.toString());
7927                    return iterator;
7928                }
7929            } break;
7930            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7931                CharSequence text = getIterableTextForAccessibility();
7932                if (text != null && text.length() > 0) {
7933                    ParagraphTextSegmentIterator iterator =
7934                        ParagraphTextSegmentIterator.getInstance();
7935                    iterator.initialize(text.toString());
7936                    return iterator;
7937                }
7938            } break;
7939        }
7940        return null;
7941    }
7942
7943    /**
7944     * @hide
7945     */
7946    public void dispatchStartTemporaryDetach() {
7947        onStartTemporaryDetach();
7948    }
7949
7950    /**
7951     * This is called when a container is going to temporarily detach a child, with
7952     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7953     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7954     * {@link #onDetachedFromWindow()} when the container is done.
7955     */
7956    public void onStartTemporaryDetach() {
7957        removeUnsetPressCallback();
7958        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7959    }
7960
7961    /**
7962     * @hide
7963     */
7964    public void dispatchFinishTemporaryDetach() {
7965        onFinishTemporaryDetach();
7966    }
7967
7968    /**
7969     * Called after {@link #onStartTemporaryDetach} when the container is done
7970     * changing the view.
7971     */
7972    public void onFinishTemporaryDetach() {
7973    }
7974
7975    /**
7976     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7977     * for this view's window.  Returns null if the view is not currently attached
7978     * to the window.  Normally you will not need to use this directly, but
7979     * just use the standard high-level event callbacks like
7980     * {@link #onKeyDown(int, KeyEvent)}.
7981     */
7982    public KeyEvent.DispatcherState getKeyDispatcherState() {
7983        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7984    }
7985
7986    /**
7987     * Dispatch a key event before it is processed by any input method
7988     * associated with the view hierarchy.  This can be used to intercept
7989     * key events in special situations before the IME consumes them; a
7990     * typical example would be handling the BACK key to update the application's
7991     * UI instead of allowing the IME to see it and close itself.
7992     *
7993     * @param event The key event to be dispatched.
7994     * @return True if the event was handled, false otherwise.
7995     */
7996    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7997        return onKeyPreIme(event.getKeyCode(), event);
7998    }
7999
8000    /**
8001     * Dispatch a key event to the next view on the focus path. This path runs
8002     * from the top of the view tree down to the currently focused view. If this
8003     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8004     * the next node down the focus path. This method also fires any key
8005     * listeners.
8006     *
8007     * @param event The key event to be dispatched.
8008     * @return True if the event was handled, false otherwise.
8009     */
8010    public boolean dispatchKeyEvent(KeyEvent event) {
8011        if (mInputEventConsistencyVerifier != null) {
8012            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8013        }
8014
8015        // Give any attached key listener a first crack at the event.
8016        //noinspection SimplifiableIfStatement
8017        ListenerInfo li = mListenerInfo;
8018        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8019                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8020            return true;
8021        }
8022
8023        if (event.dispatch(this, mAttachInfo != null
8024                ? mAttachInfo.mKeyDispatchState : null, this)) {
8025            return true;
8026        }
8027
8028        if (mInputEventConsistencyVerifier != null) {
8029            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8030        }
8031        return false;
8032    }
8033
8034    /**
8035     * Dispatches a key shortcut event.
8036     *
8037     * @param event The key event to be dispatched.
8038     * @return True if the event was handled by the view, false otherwise.
8039     */
8040    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8041        return onKeyShortcut(event.getKeyCode(), event);
8042    }
8043
8044    /**
8045     * Pass the touch screen motion event down to the target view, or this
8046     * view if it is the target.
8047     *
8048     * @param event The motion event to be dispatched.
8049     * @return True if the event was handled by the view, false otherwise.
8050     */
8051    public boolean dispatchTouchEvent(MotionEvent event) {
8052        boolean result = false;
8053
8054        if (mInputEventConsistencyVerifier != null) {
8055            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8056        }
8057
8058        final int actionMasked = event.getActionMasked();
8059        if (actionMasked == MotionEvent.ACTION_DOWN) {
8060            // Defensive cleanup for new gesture
8061            stopNestedScroll();
8062        }
8063
8064        if (onFilterTouchEventForSecurity(event)) {
8065            //noinspection SimplifiableIfStatement
8066            ListenerInfo li = mListenerInfo;
8067            if (li != null && li.mOnTouchListener != null
8068                    && (mViewFlags & ENABLED_MASK) == ENABLED
8069                    && li.mOnTouchListener.onTouch(this, event)) {
8070                result = true;
8071            }
8072
8073            if (!result && onTouchEvent(event)) {
8074                result = true;
8075            }
8076        }
8077
8078        if (!result && mInputEventConsistencyVerifier != null) {
8079            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8080        }
8081
8082        // Clean up after nested scrolls if this is the end of a gesture;
8083        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8084        // of the gesture.
8085        if (actionMasked == MotionEvent.ACTION_UP ||
8086                actionMasked == MotionEvent.ACTION_CANCEL ||
8087                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8088            stopNestedScroll();
8089        }
8090
8091        return result;
8092    }
8093
8094    /**
8095     * Filter the touch event to apply security policies.
8096     *
8097     * @param event The motion event to be filtered.
8098     * @return True if the event should be dispatched, false if the event should be dropped.
8099     *
8100     * @see #getFilterTouchesWhenObscured
8101     */
8102    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8103        //noinspection RedundantIfStatement
8104        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8105                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8106            // Window is obscured, drop this touch.
8107            return false;
8108        }
8109        return true;
8110    }
8111
8112    /**
8113     * Pass a trackball motion event down to the focused view.
8114     *
8115     * @param event The motion event to be dispatched.
8116     * @return True if the event was handled by the view, false otherwise.
8117     */
8118    public boolean dispatchTrackballEvent(MotionEvent event) {
8119        if (mInputEventConsistencyVerifier != null) {
8120            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8121        }
8122
8123        return onTrackballEvent(event);
8124    }
8125
8126    /**
8127     * Dispatch a generic motion event.
8128     * <p>
8129     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8130     * are delivered to the view under the pointer.  All other generic motion events are
8131     * delivered to the focused view.  Hover events are handled specially and are delivered
8132     * to {@link #onHoverEvent(MotionEvent)}.
8133     * </p>
8134     *
8135     * @param event The motion event to be dispatched.
8136     * @return True if the event was handled by the view, false otherwise.
8137     */
8138    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8139        if (mInputEventConsistencyVerifier != null) {
8140            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8141        }
8142
8143        final int source = event.getSource();
8144        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8145            final int action = event.getAction();
8146            if (action == MotionEvent.ACTION_HOVER_ENTER
8147                    || action == MotionEvent.ACTION_HOVER_MOVE
8148                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8149                if (dispatchHoverEvent(event)) {
8150                    return true;
8151                }
8152            } else if (dispatchGenericPointerEvent(event)) {
8153                return true;
8154            }
8155        } else if (dispatchGenericFocusedEvent(event)) {
8156            return true;
8157        }
8158
8159        if (dispatchGenericMotionEventInternal(event)) {
8160            return true;
8161        }
8162
8163        if (mInputEventConsistencyVerifier != null) {
8164            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8165        }
8166        return false;
8167    }
8168
8169    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8170        //noinspection SimplifiableIfStatement
8171        ListenerInfo li = mListenerInfo;
8172        if (li != null && li.mOnGenericMotionListener != null
8173                && (mViewFlags & ENABLED_MASK) == ENABLED
8174                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8175            return true;
8176        }
8177
8178        if (onGenericMotionEvent(event)) {
8179            return true;
8180        }
8181
8182        if (mInputEventConsistencyVerifier != null) {
8183            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8184        }
8185        return false;
8186    }
8187
8188    /**
8189     * Dispatch a hover event.
8190     * <p>
8191     * Do not call this method directly.
8192     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8193     * </p>
8194     *
8195     * @param event The motion event to be dispatched.
8196     * @return True if the event was handled by the view, false otherwise.
8197     */
8198    protected boolean dispatchHoverEvent(MotionEvent event) {
8199        ListenerInfo li = mListenerInfo;
8200        //noinspection SimplifiableIfStatement
8201        if (li != null && li.mOnHoverListener != null
8202                && (mViewFlags & ENABLED_MASK) == ENABLED
8203                && li.mOnHoverListener.onHover(this, event)) {
8204            return true;
8205        }
8206
8207        return onHoverEvent(event);
8208    }
8209
8210    /**
8211     * Returns true if the view has a child to which it has recently sent
8212     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8213     * it does not have a hovered child, then it must be the innermost hovered view.
8214     * @hide
8215     */
8216    protected boolean hasHoveredChild() {
8217        return false;
8218    }
8219
8220    /**
8221     * Dispatch a generic motion event to the view under the first pointer.
8222     * <p>
8223     * Do not call this method directly.
8224     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8225     * </p>
8226     *
8227     * @param event The motion event to be dispatched.
8228     * @return True if the event was handled by the view, false otherwise.
8229     */
8230    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8231        return false;
8232    }
8233
8234    /**
8235     * Dispatch a generic motion event to the currently focused view.
8236     * <p>
8237     * Do not call this method directly.
8238     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8239     * </p>
8240     *
8241     * @param event The motion event to be dispatched.
8242     * @return True if the event was handled by the view, false otherwise.
8243     */
8244    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8245        return false;
8246    }
8247
8248    /**
8249     * Dispatch a pointer event.
8250     * <p>
8251     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8252     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8253     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8254     * and should not be expected to handle other pointing device features.
8255     * </p>
8256     *
8257     * @param event The motion event to be dispatched.
8258     * @return True if the event was handled by the view, false otherwise.
8259     * @hide
8260     */
8261    public final boolean dispatchPointerEvent(MotionEvent event) {
8262        if (event.isTouchEvent()) {
8263            return dispatchTouchEvent(event);
8264        } else {
8265            return dispatchGenericMotionEvent(event);
8266        }
8267    }
8268
8269    /**
8270     * Called when the window containing this view gains or loses window focus.
8271     * ViewGroups should override to route to their children.
8272     *
8273     * @param hasFocus True if the window containing this view now has focus,
8274     *        false otherwise.
8275     */
8276    public void dispatchWindowFocusChanged(boolean hasFocus) {
8277        onWindowFocusChanged(hasFocus);
8278    }
8279
8280    /**
8281     * Called when the window containing this view gains or loses focus.  Note
8282     * that this is separate from view focus: to receive key events, both
8283     * your view and its window must have focus.  If a window is displayed
8284     * on top of yours that takes input focus, then your own window will lose
8285     * focus but the view focus will remain unchanged.
8286     *
8287     * @param hasWindowFocus True if the window containing this view now has
8288     *        focus, false otherwise.
8289     */
8290    public void onWindowFocusChanged(boolean hasWindowFocus) {
8291        InputMethodManager imm = InputMethodManager.peekInstance();
8292        if (!hasWindowFocus) {
8293            if (isPressed()) {
8294                setPressed(false);
8295            }
8296            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8297                imm.focusOut(this);
8298            }
8299            removeLongPressCallback();
8300            removeTapCallback();
8301            onFocusLost();
8302        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8303            imm.focusIn(this);
8304        }
8305        refreshDrawableState();
8306    }
8307
8308    /**
8309     * Returns true if this view is in a window that currently has window focus.
8310     * Note that this is not the same as the view itself having focus.
8311     *
8312     * @return True if this view is in a window that currently has window focus.
8313     */
8314    public boolean hasWindowFocus() {
8315        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8316    }
8317
8318    /**
8319     * Dispatch a view visibility change down the view hierarchy.
8320     * ViewGroups should override to route to their children.
8321     * @param changedView The view whose visibility changed. Could be 'this' or
8322     * an ancestor view.
8323     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8324     * {@link #INVISIBLE} or {@link #GONE}.
8325     */
8326    protected void dispatchVisibilityChanged(@NonNull View changedView,
8327            @Visibility int visibility) {
8328        onVisibilityChanged(changedView, visibility);
8329    }
8330
8331    /**
8332     * Called when the visibility of the view or an ancestor of the view is changed.
8333     * @param changedView The view whose visibility changed. Could be 'this' or
8334     * an ancestor view.
8335     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8336     * {@link #INVISIBLE} or {@link #GONE}.
8337     */
8338    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8339        if (visibility == VISIBLE) {
8340            if (mAttachInfo != null) {
8341                initialAwakenScrollBars();
8342            } else {
8343                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8344            }
8345        }
8346    }
8347
8348    /**
8349     * Dispatch a hint about whether this view is displayed. For instance, when
8350     * a View moves out of the screen, it might receives a display hint indicating
8351     * the view is not displayed. Applications should not <em>rely</em> on this hint
8352     * as there is no guarantee that they will receive one.
8353     *
8354     * @param hint A hint about whether or not this view is displayed:
8355     * {@link #VISIBLE} or {@link #INVISIBLE}.
8356     */
8357    public void dispatchDisplayHint(@Visibility int hint) {
8358        onDisplayHint(hint);
8359    }
8360
8361    /**
8362     * Gives this view a hint about whether is displayed or not. For instance, when
8363     * a View moves out of the screen, it might receives a display hint indicating
8364     * the view is not displayed. Applications should not <em>rely</em> on this hint
8365     * as there is no guarantee that they will receive one.
8366     *
8367     * @param hint A hint about whether or not this view is displayed:
8368     * {@link #VISIBLE} or {@link #INVISIBLE}.
8369     */
8370    protected void onDisplayHint(@Visibility int hint) {
8371    }
8372
8373    /**
8374     * Dispatch a window visibility change down the view hierarchy.
8375     * ViewGroups should override to route to their children.
8376     *
8377     * @param visibility The new visibility of the window.
8378     *
8379     * @see #onWindowVisibilityChanged(int)
8380     */
8381    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8382        onWindowVisibilityChanged(visibility);
8383    }
8384
8385    /**
8386     * Called when the window containing has change its visibility
8387     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8388     * that this tells you whether or not your window is being made visible
8389     * to the window manager; this does <em>not</em> tell you whether or not
8390     * your window is obscured by other windows on the screen, even if it
8391     * is itself visible.
8392     *
8393     * @param visibility The new visibility of the window.
8394     */
8395    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8396        if (visibility == VISIBLE) {
8397            initialAwakenScrollBars();
8398        }
8399    }
8400
8401    /**
8402     * Returns the current visibility of the window this view is attached to
8403     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8404     *
8405     * @return Returns the current visibility of the view's window.
8406     */
8407    @Visibility
8408    public int getWindowVisibility() {
8409        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8410    }
8411
8412    /**
8413     * Retrieve the overall visible display size in which the window this view is
8414     * attached to has been positioned in.  This takes into account screen
8415     * decorations above the window, for both cases where the window itself
8416     * is being position inside of them or the window is being placed under
8417     * then and covered insets are used for the window to position its content
8418     * inside.  In effect, this tells you the available area where content can
8419     * be placed and remain visible to users.
8420     *
8421     * <p>This function requires an IPC back to the window manager to retrieve
8422     * the requested information, so should not be used in performance critical
8423     * code like drawing.
8424     *
8425     * @param outRect Filled in with the visible display frame.  If the view
8426     * is not attached to a window, this is simply the raw display size.
8427     */
8428    public void getWindowVisibleDisplayFrame(Rect outRect) {
8429        if (mAttachInfo != null) {
8430            try {
8431                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8432            } catch (RemoteException e) {
8433                return;
8434            }
8435            // XXX This is really broken, and probably all needs to be done
8436            // in the window manager, and we need to know more about whether
8437            // we want the area behind or in front of the IME.
8438            final Rect insets = mAttachInfo.mVisibleInsets;
8439            outRect.left += insets.left;
8440            outRect.top += insets.top;
8441            outRect.right -= insets.right;
8442            outRect.bottom -= insets.bottom;
8443            return;
8444        }
8445        // The view is not attached to a display so we don't have a context.
8446        // Make a best guess about the display size.
8447        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8448        d.getRectSize(outRect);
8449    }
8450
8451    /**
8452     * Dispatch a notification about a resource configuration change down
8453     * the view hierarchy.
8454     * ViewGroups should override to route to their children.
8455     *
8456     * @param newConfig The new resource configuration.
8457     *
8458     * @see #onConfigurationChanged(android.content.res.Configuration)
8459     */
8460    public void dispatchConfigurationChanged(Configuration newConfig) {
8461        onConfigurationChanged(newConfig);
8462    }
8463
8464    /**
8465     * Called when the current configuration of the resources being used
8466     * by the application have changed.  You can use this to decide when
8467     * to reload resources that can changed based on orientation and other
8468     * configuration characterstics.  You only need to use this if you are
8469     * not relying on the normal {@link android.app.Activity} mechanism of
8470     * recreating the activity instance upon a configuration change.
8471     *
8472     * @param newConfig The new resource configuration.
8473     */
8474    protected void onConfigurationChanged(Configuration newConfig) {
8475    }
8476
8477    /**
8478     * Private function to aggregate all per-view attributes in to the view
8479     * root.
8480     */
8481    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8482        performCollectViewAttributes(attachInfo, visibility);
8483    }
8484
8485    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8486        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8487            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8488                attachInfo.mKeepScreenOn = true;
8489            }
8490            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8491            ListenerInfo li = mListenerInfo;
8492            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8493                attachInfo.mHasSystemUiListeners = true;
8494            }
8495        }
8496    }
8497
8498    void needGlobalAttributesUpdate(boolean force) {
8499        final AttachInfo ai = mAttachInfo;
8500        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8501            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8502                    || ai.mHasSystemUiListeners) {
8503                ai.mRecomputeGlobalAttributes = true;
8504            }
8505        }
8506    }
8507
8508    /**
8509     * Returns whether the device is currently in touch mode.  Touch mode is entered
8510     * once the user begins interacting with the device by touch, and affects various
8511     * things like whether focus is always visible to the user.
8512     *
8513     * @return Whether the device is in touch mode.
8514     */
8515    @ViewDebug.ExportedProperty
8516    public boolean isInTouchMode() {
8517        if (mAttachInfo != null) {
8518            return mAttachInfo.mInTouchMode;
8519        } else {
8520            return ViewRootImpl.isInTouchMode();
8521        }
8522    }
8523
8524    /**
8525     * Returns the context the view is running in, through which it can
8526     * access the current theme, resources, etc.
8527     *
8528     * @return The view's Context.
8529     */
8530    @ViewDebug.CapturedViewProperty
8531    public final Context getContext() {
8532        return mContext;
8533    }
8534
8535    /**
8536     * Handle a key event before it is processed by any input method
8537     * associated with the view hierarchy.  This can be used to intercept
8538     * key events in special situations before the IME consumes them; a
8539     * typical example would be handling the BACK key to update the application's
8540     * UI instead of allowing the IME to see it and close itself.
8541     *
8542     * @param keyCode The value in event.getKeyCode().
8543     * @param event Description of the key event.
8544     * @return If you handled the event, return true. If you want to allow the
8545     *         event to be handled by the next receiver, return false.
8546     */
8547    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8548        return false;
8549    }
8550
8551    /**
8552     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8553     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8554     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8555     * is released, if the view is enabled and clickable.
8556     *
8557     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8558     * although some may elect to do so in some situations. Do not rely on this to
8559     * catch software key presses.
8560     *
8561     * @param keyCode A key code that represents the button pressed, from
8562     *                {@link android.view.KeyEvent}.
8563     * @param event   The KeyEvent object that defines the button action.
8564     */
8565    public boolean onKeyDown(int keyCode, KeyEvent event) {
8566        boolean result = false;
8567
8568        if (KeyEvent.isConfirmKey(keyCode)) {
8569            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8570                return true;
8571            }
8572            // Long clickable items don't necessarily have to be clickable
8573            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8574                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8575                    (event.getRepeatCount() == 0)) {
8576                setPressed(true);
8577                checkForLongClick(0);
8578                return true;
8579            }
8580        }
8581        return result;
8582    }
8583
8584    /**
8585     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8586     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8587     * the event).
8588     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8589     * although some may elect to do so in some situations. Do not rely on this to
8590     * catch software key presses.
8591     */
8592    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8593        return false;
8594    }
8595
8596    /**
8597     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8598     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8599     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8600     * {@link KeyEvent#KEYCODE_ENTER} is released.
8601     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8602     * although some may elect to do so in some situations. Do not rely on this to
8603     * catch software key presses.
8604     *
8605     * @param keyCode A key code that represents the button pressed, from
8606     *                {@link android.view.KeyEvent}.
8607     * @param event   The KeyEvent object that defines the button action.
8608     */
8609    public boolean onKeyUp(int keyCode, KeyEvent event) {
8610        if (KeyEvent.isConfirmKey(keyCode)) {
8611            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8612                return true;
8613            }
8614            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8615                setPressed(false);
8616
8617                if (!mHasPerformedLongPress) {
8618                    // This is a tap, so remove the longpress check
8619                    removeLongPressCallback();
8620                    return performClick();
8621                }
8622            }
8623        }
8624        return false;
8625    }
8626
8627    /**
8628     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8629     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8630     * the event).
8631     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8632     * although some may elect to do so in some situations. Do not rely on this to
8633     * catch software key presses.
8634     *
8635     * @param keyCode     A key code that represents the button pressed, from
8636     *                    {@link android.view.KeyEvent}.
8637     * @param repeatCount The number of times the action was made.
8638     * @param event       The KeyEvent object that defines the button action.
8639     */
8640    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8641        return false;
8642    }
8643
8644    /**
8645     * Called on the focused view when a key shortcut event is not handled.
8646     * Override this method to implement local key shortcuts for the View.
8647     * Key shortcuts can also be implemented by setting the
8648     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8649     *
8650     * @param keyCode The value in event.getKeyCode().
8651     * @param event Description of the key event.
8652     * @return If you handled the event, return true. If you want to allow the
8653     *         event to be handled by the next receiver, return false.
8654     */
8655    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8656        return false;
8657    }
8658
8659    /**
8660     * Check whether the called view is a text editor, in which case it
8661     * would make sense to automatically display a soft input window for
8662     * it.  Subclasses should override this if they implement
8663     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8664     * a call on that method would return a non-null InputConnection, and
8665     * they are really a first-class editor that the user would normally
8666     * start typing on when the go into a window containing your view.
8667     *
8668     * <p>The default implementation always returns false.  This does
8669     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8670     * will not be called or the user can not otherwise perform edits on your
8671     * view; it is just a hint to the system that this is not the primary
8672     * purpose of this view.
8673     *
8674     * @return Returns true if this view is a text editor, else false.
8675     */
8676    public boolean onCheckIsTextEditor() {
8677        return false;
8678    }
8679
8680    /**
8681     * Create a new InputConnection for an InputMethod to interact
8682     * with the view.  The default implementation returns null, since it doesn't
8683     * support input methods.  You can override this to implement such support.
8684     * This is only needed for views that take focus and text input.
8685     *
8686     * <p>When implementing this, you probably also want to implement
8687     * {@link #onCheckIsTextEditor()} to indicate you will return a
8688     * non-null InputConnection.</p>
8689     *
8690     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8691     * object correctly and in its entirety, so that the connected IME can rely
8692     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8693     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8694     * must be filled in with the correct cursor position for IMEs to work correctly
8695     * with your application.</p>
8696     *
8697     * @param outAttrs Fill in with attribute information about the connection.
8698     */
8699    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8700        return null;
8701    }
8702
8703    /**
8704     * Called by the {@link android.view.inputmethod.InputMethodManager}
8705     * when a view who is not the current
8706     * input connection target is trying to make a call on the manager.  The
8707     * default implementation returns false; you can override this to return
8708     * true for certain views if you are performing InputConnection proxying
8709     * to them.
8710     * @param view The View that is making the InputMethodManager call.
8711     * @return Return true to allow the call, false to reject.
8712     */
8713    public boolean checkInputConnectionProxy(View view) {
8714        return false;
8715    }
8716
8717    /**
8718     * Show the context menu for this view. It is not safe to hold on to the
8719     * menu after returning from this method.
8720     *
8721     * You should normally not overload this method. Overload
8722     * {@link #onCreateContextMenu(ContextMenu)} or define an
8723     * {@link OnCreateContextMenuListener} to add items to the context menu.
8724     *
8725     * @param menu The context menu to populate
8726     */
8727    public void createContextMenu(ContextMenu menu) {
8728        ContextMenuInfo menuInfo = getContextMenuInfo();
8729
8730        // Sets the current menu info so all items added to menu will have
8731        // my extra info set.
8732        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8733
8734        onCreateContextMenu(menu);
8735        ListenerInfo li = mListenerInfo;
8736        if (li != null && li.mOnCreateContextMenuListener != null) {
8737            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8738        }
8739
8740        // Clear the extra information so subsequent items that aren't mine don't
8741        // have my extra info.
8742        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8743
8744        if (mParent != null) {
8745            mParent.createContextMenu(menu);
8746        }
8747    }
8748
8749    /**
8750     * Views should implement this if they have extra information to associate
8751     * with the context menu. The return result is supplied as a parameter to
8752     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8753     * callback.
8754     *
8755     * @return Extra information about the item for which the context menu
8756     *         should be shown. This information will vary across different
8757     *         subclasses of View.
8758     */
8759    protected ContextMenuInfo getContextMenuInfo() {
8760        return null;
8761    }
8762
8763    /**
8764     * Views should implement this if the view itself is going to add items to
8765     * the context menu.
8766     *
8767     * @param menu the context menu to populate
8768     */
8769    protected void onCreateContextMenu(ContextMenu menu) {
8770    }
8771
8772    /**
8773     * Implement this method to handle trackball motion events.  The
8774     * <em>relative</em> movement of the trackball since the last event
8775     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8776     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8777     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8778     * they will often be fractional values, representing the more fine-grained
8779     * movement information available from a trackball).
8780     *
8781     * @param event The motion event.
8782     * @return True if the event was handled, false otherwise.
8783     */
8784    public boolean onTrackballEvent(MotionEvent event) {
8785        return false;
8786    }
8787
8788    /**
8789     * Implement this method to handle generic motion events.
8790     * <p>
8791     * Generic motion events describe joystick movements, mouse hovers, track pad
8792     * touches, scroll wheel movements and other input events.  The
8793     * {@link MotionEvent#getSource() source} of the motion event specifies
8794     * the class of input that was received.  Implementations of this method
8795     * must examine the bits in the source before processing the event.
8796     * The following code example shows how this is done.
8797     * </p><p>
8798     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8799     * are delivered to the view under the pointer.  All other generic motion events are
8800     * delivered to the focused view.
8801     * </p>
8802     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8803     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8804     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8805     *             // process the joystick movement...
8806     *             return true;
8807     *         }
8808     *     }
8809     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8810     *         switch (event.getAction()) {
8811     *             case MotionEvent.ACTION_HOVER_MOVE:
8812     *                 // process the mouse hover movement...
8813     *                 return true;
8814     *             case MotionEvent.ACTION_SCROLL:
8815     *                 // process the scroll wheel movement...
8816     *                 return true;
8817     *         }
8818     *     }
8819     *     return super.onGenericMotionEvent(event);
8820     * }</pre>
8821     *
8822     * @param event The generic motion event being processed.
8823     * @return True if the event was handled, false otherwise.
8824     */
8825    public boolean onGenericMotionEvent(MotionEvent event) {
8826        return false;
8827    }
8828
8829    /**
8830     * Implement this method to handle hover events.
8831     * <p>
8832     * This method is called whenever a pointer is hovering into, over, or out of the
8833     * bounds of a view and the view is not currently being touched.
8834     * Hover events are represented as pointer events with action
8835     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8836     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8837     * </p>
8838     * <ul>
8839     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8840     * when the pointer enters the bounds of the view.</li>
8841     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8842     * when the pointer has already entered the bounds of the view and has moved.</li>
8843     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8844     * when the pointer has exited the bounds of the view or when the pointer is
8845     * about to go down due to a button click, tap, or similar user action that
8846     * causes the view to be touched.</li>
8847     * </ul>
8848     * <p>
8849     * The view should implement this method to return true to indicate that it is
8850     * handling the hover event, such as by changing its drawable state.
8851     * </p><p>
8852     * The default implementation calls {@link #setHovered} to update the hovered state
8853     * of the view when a hover enter or hover exit event is received, if the view
8854     * is enabled and is clickable.  The default implementation also sends hover
8855     * accessibility events.
8856     * </p>
8857     *
8858     * @param event The motion event that describes the hover.
8859     * @return True if the view handled the hover event.
8860     *
8861     * @see #isHovered
8862     * @see #setHovered
8863     * @see #onHoverChanged
8864     */
8865    public boolean onHoverEvent(MotionEvent event) {
8866        // The root view may receive hover (or touch) events that are outside the bounds of
8867        // the window.  This code ensures that we only send accessibility events for
8868        // hovers that are actually within the bounds of the root view.
8869        final int action = event.getActionMasked();
8870        if (!mSendingHoverAccessibilityEvents) {
8871            if ((action == MotionEvent.ACTION_HOVER_ENTER
8872                    || action == MotionEvent.ACTION_HOVER_MOVE)
8873                    && !hasHoveredChild()
8874                    && pointInView(event.getX(), event.getY())) {
8875                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8876                mSendingHoverAccessibilityEvents = true;
8877            }
8878        } else {
8879            if (action == MotionEvent.ACTION_HOVER_EXIT
8880                    || (action == MotionEvent.ACTION_MOVE
8881                            && !pointInView(event.getX(), event.getY()))) {
8882                mSendingHoverAccessibilityEvents = false;
8883                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8884            }
8885        }
8886
8887        if (isHoverable()) {
8888            switch (action) {
8889                case MotionEvent.ACTION_HOVER_ENTER:
8890                    setHovered(true);
8891                    break;
8892                case MotionEvent.ACTION_HOVER_EXIT:
8893                    setHovered(false);
8894                    break;
8895            }
8896
8897            // Dispatch the event to onGenericMotionEvent before returning true.
8898            // This is to provide compatibility with existing applications that
8899            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8900            // break because of the new default handling for hoverable views
8901            // in onHoverEvent.
8902            // Note that onGenericMotionEvent will be called by default when
8903            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8904            dispatchGenericMotionEventInternal(event);
8905            // The event was already handled by calling setHovered(), so always
8906            // return true.
8907            return true;
8908        }
8909
8910        return false;
8911    }
8912
8913    /**
8914     * Returns true if the view should handle {@link #onHoverEvent}
8915     * by calling {@link #setHovered} to change its hovered state.
8916     *
8917     * @return True if the view is hoverable.
8918     */
8919    private boolean isHoverable() {
8920        final int viewFlags = mViewFlags;
8921        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8922            return false;
8923        }
8924
8925        return (viewFlags & CLICKABLE) == CLICKABLE
8926                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8927    }
8928
8929    /**
8930     * Returns true if the view is currently hovered.
8931     *
8932     * @return True if the view is currently hovered.
8933     *
8934     * @see #setHovered
8935     * @see #onHoverChanged
8936     */
8937    @ViewDebug.ExportedProperty
8938    public boolean isHovered() {
8939        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8940    }
8941
8942    /**
8943     * Sets whether the view is currently hovered.
8944     * <p>
8945     * Calling this method also changes the drawable state of the view.  This
8946     * enables the view to react to hover by using different drawable resources
8947     * to change its appearance.
8948     * </p><p>
8949     * The {@link #onHoverChanged} method is called when the hovered state changes.
8950     * </p>
8951     *
8952     * @param hovered True if the view is hovered.
8953     *
8954     * @see #isHovered
8955     * @see #onHoverChanged
8956     */
8957    public void setHovered(boolean hovered) {
8958        if (hovered) {
8959            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8960                mPrivateFlags |= PFLAG_HOVERED;
8961                refreshDrawableState();
8962                onHoverChanged(true);
8963            }
8964        } else {
8965            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8966                mPrivateFlags &= ~PFLAG_HOVERED;
8967                refreshDrawableState();
8968                onHoverChanged(false);
8969            }
8970        }
8971    }
8972
8973    /**
8974     * Implement this method to handle hover state changes.
8975     * <p>
8976     * This method is called whenever the hover state changes as a result of a
8977     * call to {@link #setHovered}.
8978     * </p>
8979     *
8980     * @param hovered The current hover state, as returned by {@link #isHovered}.
8981     *
8982     * @see #isHovered
8983     * @see #setHovered
8984     */
8985    public void onHoverChanged(boolean hovered) {
8986    }
8987
8988    /**
8989     * Implement this method to handle touch screen motion events.
8990     * <p>
8991     * If this method is used to detect click actions, it is recommended that
8992     * the actions be performed by implementing and calling
8993     * {@link #performClick()}. This will ensure consistent system behavior,
8994     * including:
8995     * <ul>
8996     * <li>obeying click sound preferences
8997     * <li>dispatching OnClickListener calls
8998     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
8999     * accessibility features are enabled
9000     * </ul>
9001     *
9002     * @param event The motion event.
9003     * @return True if the event was handled, false otherwise.
9004     */
9005    public boolean onTouchEvent(MotionEvent event) {
9006        final float x = event.getX();
9007        final float y = event.getY();
9008        final int viewFlags = mViewFlags;
9009
9010        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9011            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9012                setPressed(false);
9013            }
9014            // A disabled view that is clickable still consumes the touch
9015            // events, it just doesn't respond to them.
9016            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9017                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9018        }
9019
9020        if (mTouchDelegate != null) {
9021            if (mTouchDelegate.onTouchEvent(event)) {
9022                return true;
9023            }
9024        }
9025
9026        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9027                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9028            switch (event.getAction()) {
9029                case MotionEvent.ACTION_UP:
9030                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9031                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9032                        // take focus if we don't have it already and we should in
9033                        // touch mode.
9034                        boolean focusTaken = false;
9035                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9036                            focusTaken = requestFocus();
9037                        }
9038
9039                        if (prepressed) {
9040                            // The button is being released before we actually
9041                            // showed it as pressed.  Make it show the pressed
9042                            // state now (before scheduling the click) to ensure
9043                            // the user sees it.
9044                            setPressed(true, x, y);
9045                       }
9046
9047                        if (!mHasPerformedLongPress) {
9048                            // This is a tap, so remove the longpress check
9049                            removeLongPressCallback();
9050
9051                            // Only perform take click actions if we were in the pressed state
9052                            if (!focusTaken) {
9053                                // Use a Runnable and post this rather than calling
9054                                // performClick directly. This lets other visual state
9055                                // of the view update before click actions start.
9056                                if (mPerformClick == null) {
9057                                    mPerformClick = new PerformClick();
9058                                }
9059                                if (!post(mPerformClick)) {
9060                                    performClick();
9061                                }
9062                            }
9063                        }
9064
9065                        if (mUnsetPressedState == null) {
9066                            mUnsetPressedState = new UnsetPressedState();
9067                        }
9068
9069                        if (prepressed) {
9070                            postDelayed(mUnsetPressedState,
9071                                    ViewConfiguration.getPressedStateDuration());
9072                        } else if (!post(mUnsetPressedState)) {
9073                            // If the post failed, unpress right now
9074                            mUnsetPressedState.run();
9075                        }
9076
9077                        removeTapCallback();
9078                    }
9079                    break;
9080
9081                case MotionEvent.ACTION_DOWN:
9082                    mHasPerformedLongPress = false;
9083
9084                    if (performButtonActionOnTouchDown(event)) {
9085                        break;
9086                    }
9087
9088                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9089                    boolean isInScrollingContainer = isInScrollingContainer();
9090
9091                    // For views inside a scrolling container, delay the pressed feedback for
9092                    // a short period in case this is a scroll.
9093                    if (isInScrollingContainer) {
9094                        mPrivateFlags |= PFLAG_PREPRESSED;
9095                        if (mPendingCheckForTap == null) {
9096                            mPendingCheckForTap = new CheckForTap();
9097                        }
9098                        mPendingCheckForTap.x = event.getX();
9099                        mPendingCheckForTap.y = event.getY();
9100                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9101                    } else {
9102                        // Not inside a scrolling container, so show the feedback right away
9103                        setHotspot(x, y);
9104                        setPressed(true);
9105                        checkForLongClick(0);
9106                    }
9107                    break;
9108
9109                case MotionEvent.ACTION_CANCEL:
9110                    setPressed(false);
9111                    removeTapCallback();
9112                    removeLongPressCallback();
9113                    break;
9114
9115                case MotionEvent.ACTION_MOVE:
9116                    setHotspot(x, y);
9117
9118                    // Be lenient about moving outside of buttons
9119                    if (!pointInView(x, y, mTouchSlop)) {
9120                        // Outside button
9121                        removeTapCallback();
9122                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9123                            // Remove any future long press/tap checks
9124                            removeLongPressCallback();
9125
9126                            setPressed(false);
9127                        }
9128                    }
9129                    break;
9130            }
9131
9132            return true;
9133        }
9134
9135        return false;
9136    }
9137
9138    private void setHotspot(float x, float y) {
9139        if (mBackground != null) {
9140            mBackground.setHotspot(x, y);
9141        }
9142    }
9143
9144    /**
9145     * @hide
9146     */
9147    public boolean isInScrollingContainer() {
9148        ViewParent p = getParent();
9149        while (p != null && p instanceof ViewGroup) {
9150            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9151                return true;
9152            }
9153            p = p.getParent();
9154        }
9155        return false;
9156    }
9157
9158    /**
9159     * Remove the longpress detection timer.
9160     */
9161    private void removeLongPressCallback() {
9162        if (mPendingCheckForLongPress != null) {
9163          removeCallbacks(mPendingCheckForLongPress);
9164        }
9165    }
9166
9167    /**
9168     * Remove the pending click action
9169     */
9170    private void removePerformClickCallback() {
9171        if (mPerformClick != null) {
9172            removeCallbacks(mPerformClick);
9173        }
9174    }
9175
9176    /**
9177     * Remove the prepress detection timer.
9178     */
9179    private void removeUnsetPressCallback() {
9180        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9181            setPressed(false);
9182            removeCallbacks(mUnsetPressedState);
9183        }
9184    }
9185
9186    /**
9187     * Remove the tap detection timer.
9188     */
9189    private void removeTapCallback() {
9190        if (mPendingCheckForTap != null) {
9191            mPrivateFlags &= ~PFLAG_PREPRESSED;
9192            removeCallbacks(mPendingCheckForTap);
9193        }
9194    }
9195
9196    /**
9197     * Cancels a pending long press.  Your subclass can use this if you
9198     * want the context menu to come up if the user presses and holds
9199     * at the same place, but you don't want it to come up if they press
9200     * and then move around enough to cause scrolling.
9201     */
9202    public void cancelLongPress() {
9203        removeLongPressCallback();
9204
9205        /*
9206         * The prepressed state handled by the tap callback is a display
9207         * construct, but the tap callback will post a long press callback
9208         * less its own timeout. Remove it here.
9209         */
9210        removeTapCallback();
9211    }
9212
9213    /**
9214     * Remove the pending callback for sending a
9215     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9216     */
9217    private void removeSendViewScrolledAccessibilityEventCallback() {
9218        if (mSendViewScrolledAccessibilityEvent != null) {
9219            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9220            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9221        }
9222    }
9223
9224    /**
9225     * Sets the TouchDelegate for this View.
9226     */
9227    public void setTouchDelegate(TouchDelegate delegate) {
9228        mTouchDelegate = delegate;
9229    }
9230
9231    /**
9232     * Gets the TouchDelegate for this View.
9233     */
9234    public TouchDelegate getTouchDelegate() {
9235        return mTouchDelegate;
9236    }
9237
9238    /**
9239     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9240     *
9241     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9242     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9243     * available. This method should only be called for touch events.
9244     *
9245     * <p class="note">This api is not intended for most applications. Buffered dispatch
9246     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9247     * streams will not improve your input latency. Side effects include: increased latency,
9248     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9249     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9250     * you.</p>
9251     */
9252    public final void requestUnbufferedDispatch(MotionEvent event) {
9253        final int action = event.getAction();
9254        if (mAttachInfo == null
9255                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9256                || !event.isTouchEvent()) {
9257            return;
9258        }
9259        mAttachInfo.mUnbufferedDispatchRequested = true;
9260    }
9261
9262    /**
9263     * Set flags controlling behavior of this view.
9264     *
9265     * @param flags Constant indicating the value which should be set
9266     * @param mask Constant indicating the bit range that should be changed
9267     */
9268    void setFlags(int flags, int mask) {
9269        final boolean accessibilityEnabled =
9270                AccessibilityManager.getInstance(mContext).isEnabled();
9271        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9272
9273        int old = mViewFlags;
9274        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9275
9276        int changed = mViewFlags ^ old;
9277        if (changed == 0) {
9278            return;
9279        }
9280        int privateFlags = mPrivateFlags;
9281
9282        /* Check if the FOCUSABLE bit has changed */
9283        if (((changed & FOCUSABLE_MASK) != 0) &&
9284                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9285            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9286                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9287                /* Give up focus if we are no longer focusable */
9288                clearFocus();
9289            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9290                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9291                /*
9292                 * Tell the view system that we are now available to take focus
9293                 * if no one else already has it.
9294                 */
9295                if (mParent != null) mParent.focusableViewAvailable(this);
9296            }
9297        }
9298
9299        final int newVisibility = flags & VISIBILITY_MASK;
9300        if (newVisibility == VISIBLE) {
9301            if ((changed & VISIBILITY_MASK) != 0) {
9302                /*
9303                 * If this view is becoming visible, invalidate it in case it changed while
9304                 * it was not visible. Marking it drawn ensures that the invalidation will
9305                 * go through.
9306                 */
9307                mPrivateFlags |= PFLAG_DRAWN;
9308                invalidate(true);
9309
9310                needGlobalAttributesUpdate(true);
9311
9312                // a view becoming visible is worth notifying the parent
9313                // about in case nothing has focus.  even if this specific view
9314                // isn't focusable, it may contain something that is, so let
9315                // the root view try to give this focus if nothing else does.
9316                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9317                    mParent.focusableViewAvailable(this);
9318                }
9319            }
9320        }
9321
9322        /* Check if the GONE bit has changed */
9323        if ((changed & GONE) != 0) {
9324            needGlobalAttributesUpdate(false);
9325            requestLayout();
9326
9327            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9328                if (hasFocus()) clearFocus();
9329                clearAccessibilityFocus();
9330                destroyDrawingCache();
9331                if (mParent instanceof View) {
9332                    // GONE views noop invalidation, so invalidate the parent
9333                    ((View) mParent).invalidate(true);
9334                }
9335                // Mark the view drawn to ensure that it gets invalidated properly the next
9336                // time it is visible and gets invalidated
9337                mPrivateFlags |= PFLAG_DRAWN;
9338            }
9339            if (mAttachInfo != null) {
9340                mAttachInfo.mViewVisibilityChanged = true;
9341            }
9342        }
9343
9344        /* Check if the VISIBLE bit has changed */
9345        if ((changed & INVISIBLE) != 0) {
9346            needGlobalAttributesUpdate(false);
9347            /*
9348             * If this view is becoming invisible, set the DRAWN flag so that
9349             * the next invalidate() will not be skipped.
9350             */
9351            mPrivateFlags |= PFLAG_DRAWN;
9352
9353            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9354                // root view becoming invisible shouldn't clear focus and accessibility focus
9355                if (getRootView() != this) {
9356                    if (hasFocus()) clearFocus();
9357                    clearAccessibilityFocus();
9358                }
9359            }
9360            if (mAttachInfo != null) {
9361                mAttachInfo.mViewVisibilityChanged = true;
9362            }
9363        }
9364
9365        if ((changed & VISIBILITY_MASK) != 0) {
9366            // If the view is invisible, cleanup its display list to free up resources
9367            if (newVisibility != VISIBLE && mAttachInfo != null) {
9368                cleanupDraw();
9369            }
9370
9371            if (mParent instanceof ViewGroup) {
9372                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9373                        (changed & VISIBILITY_MASK), newVisibility);
9374                ((View) mParent).invalidate(true);
9375            } else if (mParent != null) {
9376                mParent.invalidateChild(this, null);
9377            }
9378            dispatchVisibilityChanged(this, newVisibility);
9379
9380            notifySubtreeAccessibilityStateChangedIfNeeded();
9381        }
9382
9383        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9384            destroyDrawingCache();
9385        }
9386
9387        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9388            destroyDrawingCache();
9389            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9390            invalidateParentCaches();
9391        }
9392
9393        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9394            destroyDrawingCache();
9395            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9396        }
9397
9398        if ((changed & DRAW_MASK) != 0) {
9399            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9400                if (mBackground != null) {
9401                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9402                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9403                } else {
9404                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9405                }
9406            } else {
9407                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9408            }
9409            requestLayout();
9410            invalidate(true);
9411        }
9412
9413        if ((changed & KEEP_SCREEN_ON) != 0) {
9414            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9415                mParent.recomputeViewAttributes(this);
9416            }
9417        }
9418
9419        if (accessibilityEnabled) {
9420            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9421                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9422                if (oldIncludeForAccessibility != includeForAccessibility()) {
9423                    notifySubtreeAccessibilityStateChangedIfNeeded();
9424                } else {
9425                    notifyViewAccessibilityStateChangedIfNeeded(
9426                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9427                }
9428            } else if ((changed & ENABLED_MASK) != 0) {
9429                notifyViewAccessibilityStateChangedIfNeeded(
9430                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9431            }
9432        }
9433    }
9434
9435    /**
9436     * Change the view's z order in the tree, so it's on top of other sibling
9437     * views. This ordering change may affect layout, if the parent container
9438     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9439     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9440     * method should be followed by calls to {@link #requestLayout()} and
9441     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9442     * with the new child ordering.
9443     *
9444     * @see ViewGroup#bringChildToFront(View)
9445     */
9446    public void bringToFront() {
9447        if (mParent != null) {
9448            mParent.bringChildToFront(this);
9449        }
9450    }
9451
9452    /**
9453     * This is called in response to an internal scroll in this view (i.e., the
9454     * view scrolled its own contents). This is typically as a result of
9455     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9456     * called.
9457     *
9458     * @param l Current horizontal scroll origin.
9459     * @param t Current vertical scroll origin.
9460     * @param oldl Previous horizontal scroll origin.
9461     * @param oldt Previous vertical scroll origin.
9462     */
9463    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9464        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9465            postSendViewScrolledAccessibilityEventCallback();
9466        }
9467
9468        mBackgroundSizeChanged = true;
9469
9470        final AttachInfo ai = mAttachInfo;
9471        if (ai != null) {
9472            ai.mViewScrollChanged = true;
9473        }
9474    }
9475
9476    /**
9477     * Interface definition for a callback to be invoked when the layout bounds of a view
9478     * changes due to layout processing.
9479     */
9480    public interface OnLayoutChangeListener {
9481        /**
9482         * Called when the layout bounds of a view changes due to layout processing.
9483         *
9484         * @param v The view whose bounds have changed.
9485         * @param left The new value of the view's left property.
9486         * @param top The new value of the view's top property.
9487         * @param right The new value of the view's right property.
9488         * @param bottom The new value of the view's bottom property.
9489         * @param oldLeft The previous value of the view's left property.
9490         * @param oldTop The previous value of the view's top property.
9491         * @param oldRight The previous value of the view's right property.
9492         * @param oldBottom The previous value of the view's bottom property.
9493         */
9494        void onLayoutChange(View v, int left, int top, int right, int bottom,
9495            int oldLeft, int oldTop, int oldRight, int oldBottom);
9496    }
9497
9498    /**
9499     * This is called during layout when the size of this view has changed. If
9500     * you were just added to the view hierarchy, you're called with the old
9501     * values of 0.
9502     *
9503     * @param w Current width of this view.
9504     * @param h Current height of this view.
9505     * @param oldw Old width of this view.
9506     * @param oldh Old height of this view.
9507     */
9508    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9509    }
9510
9511    /**
9512     * Called by draw to draw the child views. This may be overridden
9513     * by derived classes to gain control just before its children are drawn
9514     * (but after its own view has been drawn).
9515     * @param canvas the canvas on which to draw the view
9516     */
9517    protected void dispatchDraw(Canvas canvas) {
9518
9519    }
9520
9521    /**
9522     * Gets the parent of this view. Note that the parent is a
9523     * ViewParent and not necessarily a View.
9524     *
9525     * @return Parent of this view.
9526     */
9527    public final ViewParent getParent() {
9528        return mParent;
9529    }
9530
9531    /**
9532     * Set the horizontal scrolled position of your view. This will cause a call to
9533     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9534     * invalidated.
9535     * @param value the x position to scroll to
9536     */
9537    public void setScrollX(int value) {
9538        scrollTo(value, mScrollY);
9539    }
9540
9541    /**
9542     * Set the vertical scrolled position of your view. This will cause a call to
9543     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9544     * invalidated.
9545     * @param value the y position to scroll to
9546     */
9547    public void setScrollY(int value) {
9548        scrollTo(mScrollX, value);
9549    }
9550
9551    /**
9552     * Return the scrolled left position of this view. This is the left edge of
9553     * the displayed part of your view. You do not need to draw any pixels
9554     * farther left, since those are outside of the frame of your view on
9555     * screen.
9556     *
9557     * @return The left edge of the displayed part of your view, in pixels.
9558     */
9559    public final int getScrollX() {
9560        return mScrollX;
9561    }
9562
9563    /**
9564     * Return the scrolled top position of this view. This is the top edge of
9565     * the displayed part of your view. You do not need to draw any pixels above
9566     * it, since those are outside of the frame of your view on screen.
9567     *
9568     * @return The top edge of the displayed part of your view, in pixels.
9569     */
9570    public final int getScrollY() {
9571        return mScrollY;
9572    }
9573
9574    /**
9575     * Return the width of the your view.
9576     *
9577     * @return The width of your view, in pixels.
9578     */
9579    @ViewDebug.ExportedProperty(category = "layout")
9580    public final int getWidth() {
9581        return mRight - mLeft;
9582    }
9583
9584    /**
9585     * Return the height of your view.
9586     *
9587     * @return The height of your view, in pixels.
9588     */
9589    @ViewDebug.ExportedProperty(category = "layout")
9590    public final int getHeight() {
9591        return mBottom - mTop;
9592    }
9593
9594    /**
9595     * Return the visible drawing bounds of your view. Fills in the output
9596     * rectangle with the values from getScrollX(), getScrollY(),
9597     * getWidth(), and getHeight(). These bounds do not account for any
9598     * transformation properties currently set on the view, such as
9599     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9600     *
9601     * @param outRect The (scrolled) drawing bounds of the view.
9602     */
9603    public void getDrawingRect(Rect outRect) {
9604        outRect.left = mScrollX;
9605        outRect.top = mScrollY;
9606        outRect.right = mScrollX + (mRight - mLeft);
9607        outRect.bottom = mScrollY + (mBottom - mTop);
9608    }
9609
9610    /**
9611     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9612     * raw width component (that is the result is masked by
9613     * {@link #MEASURED_SIZE_MASK}).
9614     *
9615     * @return The raw measured width of this view.
9616     */
9617    public final int getMeasuredWidth() {
9618        return mMeasuredWidth & MEASURED_SIZE_MASK;
9619    }
9620
9621    /**
9622     * Return the full width measurement information for this view as computed
9623     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9624     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9625     * This should be used during measurement and layout calculations only. Use
9626     * {@link #getWidth()} to see how wide a view is after layout.
9627     *
9628     * @return The measured width of this view as a bit mask.
9629     */
9630    public final int getMeasuredWidthAndState() {
9631        return mMeasuredWidth;
9632    }
9633
9634    /**
9635     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9636     * raw width component (that is the result is masked by
9637     * {@link #MEASURED_SIZE_MASK}).
9638     *
9639     * @return The raw measured height of this view.
9640     */
9641    public final int getMeasuredHeight() {
9642        return mMeasuredHeight & MEASURED_SIZE_MASK;
9643    }
9644
9645    /**
9646     * Return the full height measurement information for this view as computed
9647     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9648     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9649     * This should be used during measurement and layout calculations only. Use
9650     * {@link #getHeight()} to see how wide a view is after layout.
9651     *
9652     * @return The measured width of this view as a bit mask.
9653     */
9654    public final int getMeasuredHeightAndState() {
9655        return mMeasuredHeight;
9656    }
9657
9658    /**
9659     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9660     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9661     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9662     * and the height component is at the shifted bits
9663     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9664     */
9665    public final int getMeasuredState() {
9666        return (mMeasuredWidth&MEASURED_STATE_MASK)
9667                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9668                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9669    }
9670
9671    /**
9672     * The transform matrix of this view, which is calculated based on the current
9673     * roation, scale, and pivot properties.
9674     *
9675     * @see #getRotation()
9676     * @see #getScaleX()
9677     * @see #getScaleY()
9678     * @see #getPivotX()
9679     * @see #getPivotY()
9680     * @return The current transform matrix for the view
9681     */
9682    public Matrix getMatrix() {
9683        ensureTransformationInfo();
9684        final Matrix matrix = mTransformationInfo.mMatrix;
9685        mRenderNode.getMatrix(matrix);
9686        return matrix;
9687    }
9688
9689    /**
9690     * Returns true if the transform matrix is the identity matrix.
9691     * Recomputes the matrix if necessary.
9692     *
9693     * @return True if the transform matrix is the identity matrix, false otherwise.
9694     */
9695    final boolean hasIdentityMatrix() {
9696        return mRenderNode.hasIdentityMatrix();
9697    }
9698
9699    void ensureTransformationInfo() {
9700        if (mTransformationInfo == null) {
9701            mTransformationInfo = new TransformationInfo();
9702        }
9703    }
9704
9705   /**
9706     * Utility method to retrieve the inverse of the current mMatrix property.
9707     * We cache the matrix to avoid recalculating it when transform properties
9708     * have not changed.
9709     *
9710     * @return The inverse of the current matrix of this view.
9711     */
9712    final Matrix getInverseMatrix() {
9713        ensureTransformationInfo();
9714        if (mTransformationInfo.mInverseMatrix == null) {
9715            mTransformationInfo.mInverseMatrix = new Matrix();
9716        }
9717        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9718        mRenderNode.getInverseMatrix(matrix);
9719        return matrix;
9720    }
9721
9722    /**
9723     * Gets the distance along the Z axis from the camera to this view.
9724     *
9725     * @see #setCameraDistance(float)
9726     *
9727     * @return The distance along the Z axis.
9728     */
9729    public float getCameraDistance() {
9730        final float dpi = mResources.getDisplayMetrics().densityDpi;
9731        return -(mRenderNode.getCameraDistance() * dpi);
9732    }
9733
9734    /**
9735     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9736     * views are drawn) from the camera to this view. The camera's distance
9737     * affects 3D transformations, for instance rotations around the X and Y
9738     * axis. If the rotationX or rotationY properties are changed and this view is
9739     * large (more than half the size of the screen), it is recommended to always
9740     * use a camera distance that's greater than the height (X axis rotation) or
9741     * the width (Y axis rotation) of this view.</p>
9742     *
9743     * <p>The distance of the camera from the view plane can have an affect on the
9744     * perspective distortion of the view when it is rotated around the x or y axis.
9745     * For example, a large distance will result in a large viewing angle, and there
9746     * will not be much perspective distortion of the view as it rotates. A short
9747     * distance may cause much more perspective distortion upon rotation, and can
9748     * also result in some drawing artifacts if the rotated view ends up partially
9749     * behind the camera (which is why the recommendation is to use a distance at
9750     * least as far as the size of the view, if the view is to be rotated.)</p>
9751     *
9752     * <p>The distance is expressed in "depth pixels." The default distance depends
9753     * on the screen density. For instance, on a medium density display, the
9754     * default distance is 1280. On a high density display, the default distance
9755     * is 1920.</p>
9756     *
9757     * <p>If you want to specify a distance that leads to visually consistent
9758     * results across various densities, use the following formula:</p>
9759     * <pre>
9760     * float scale = context.getResources().getDisplayMetrics().density;
9761     * view.setCameraDistance(distance * scale);
9762     * </pre>
9763     *
9764     * <p>The density scale factor of a high density display is 1.5,
9765     * and 1920 = 1280 * 1.5.</p>
9766     *
9767     * @param distance The distance in "depth pixels", if negative the opposite
9768     *        value is used
9769     *
9770     * @see #setRotationX(float)
9771     * @see #setRotationY(float)
9772     */
9773    public void setCameraDistance(float distance) {
9774        final float dpi = mResources.getDisplayMetrics().densityDpi;
9775
9776        invalidateViewProperty(true, false);
9777        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9778        invalidateViewProperty(false, false);
9779
9780        invalidateParentIfNeededAndWasQuickRejected();
9781    }
9782
9783    /**
9784     * The degrees that the view is rotated around the pivot point.
9785     *
9786     * @see #setRotation(float)
9787     * @see #getPivotX()
9788     * @see #getPivotY()
9789     *
9790     * @return The degrees of rotation.
9791     */
9792    @ViewDebug.ExportedProperty(category = "drawing")
9793    public float getRotation() {
9794        return mRenderNode.getRotation();
9795    }
9796
9797    /**
9798     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9799     * result in clockwise rotation.
9800     *
9801     * @param rotation The degrees of rotation.
9802     *
9803     * @see #getRotation()
9804     * @see #getPivotX()
9805     * @see #getPivotY()
9806     * @see #setRotationX(float)
9807     * @see #setRotationY(float)
9808     *
9809     * @attr ref android.R.styleable#View_rotation
9810     */
9811    public void setRotation(float rotation) {
9812        if (rotation != getRotation()) {
9813            // Double-invalidation is necessary to capture view's old and new areas
9814            invalidateViewProperty(true, false);
9815            mRenderNode.setRotation(rotation);
9816            invalidateViewProperty(false, true);
9817
9818            invalidateParentIfNeededAndWasQuickRejected();
9819            notifySubtreeAccessibilityStateChangedIfNeeded();
9820        }
9821    }
9822
9823    /**
9824     * The degrees that the view is rotated around the vertical axis through the pivot point.
9825     *
9826     * @see #getPivotX()
9827     * @see #getPivotY()
9828     * @see #setRotationY(float)
9829     *
9830     * @return The degrees of Y rotation.
9831     */
9832    @ViewDebug.ExportedProperty(category = "drawing")
9833    public float getRotationY() {
9834        return mRenderNode.getRotationY();
9835    }
9836
9837    /**
9838     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9839     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9840     * down the y axis.
9841     *
9842     * When rotating large views, it is recommended to adjust the camera distance
9843     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9844     *
9845     * @param rotationY The degrees of Y rotation.
9846     *
9847     * @see #getRotationY()
9848     * @see #getPivotX()
9849     * @see #getPivotY()
9850     * @see #setRotation(float)
9851     * @see #setRotationX(float)
9852     * @see #setCameraDistance(float)
9853     *
9854     * @attr ref android.R.styleable#View_rotationY
9855     */
9856    public void setRotationY(float rotationY) {
9857        if (rotationY != getRotationY()) {
9858            invalidateViewProperty(true, false);
9859            mRenderNode.setRotationY(rotationY);
9860            invalidateViewProperty(false, true);
9861
9862            invalidateParentIfNeededAndWasQuickRejected();
9863            notifySubtreeAccessibilityStateChangedIfNeeded();
9864        }
9865    }
9866
9867    /**
9868     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9869     *
9870     * @see #getPivotX()
9871     * @see #getPivotY()
9872     * @see #setRotationX(float)
9873     *
9874     * @return The degrees of X rotation.
9875     */
9876    @ViewDebug.ExportedProperty(category = "drawing")
9877    public float getRotationX() {
9878        return mRenderNode.getRotationX();
9879    }
9880
9881    /**
9882     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9883     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9884     * x axis.
9885     *
9886     * When rotating large views, it is recommended to adjust the camera distance
9887     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9888     *
9889     * @param rotationX The degrees of X rotation.
9890     *
9891     * @see #getRotationX()
9892     * @see #getPivotX()
9893     * @see #getPivotY()
9894     * @see #setRotation(float)
9895     * @see #setRotationY(float)
9896     * @see #setCameraDistance(float)
9897     *
9898     * @attr ref android.R.styleable#View_rotationX
9899     */
9900    public void setRotationX(float rotationX) {
9901        if (rotationX != getRotationX()) {
9902            invalidateViewProperty(true, false);
9903            mRenderNode.setRotationX(rotationX);
9904            invalidateViewProperty(false, true);
9905
9906            invalidateParentIfNeededAndWasQuickRejected();
9907            notifySubtreeAccessibilityStateChangedIfNeeded();
9908        }
9909    }
9910
9911    /**
9912     * The amount that the view is scaled in x around the pivot point, as a proportion of
9913     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9914     *
9915     * <p>By default, this is 1.0f.
9916     *
9917     * @see #getPivotX()
9918     * @see #getPivotY()
9919     * @return The scaling factor.
9920     */
9921    @ViewDebug.ExportedProperty(category = "drawing")
9922    public float getScaleX() {
9923        return mRenderNode.getScaleX();
9924    }
9925
9926    /**
9927     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9928     * the view's unscaled width. A value of 1 means that no scaling is applied.
9929     *
9930     * @param scaleX The scaling factor.
9931     * @see #getPivotX()
9932     * @see #getPivotY()
9933     *
9934     * @attr ref android.R.styleable#View_scaleX
9935     */
9936    public void setScaleX(float scaleX) {
9937        if (scaleX != getScaleX()) {
9938            invalidateViewProperty(true, false);
9939            mRenderNode.setScaleX(scaleX);
9940            invalidateViewProperty(false, true);
9941
9942            invalidateParentIfNeededAndWasQuickRejected();
9943            notifySubtreeAccessibilityStateChangedIfNeeded();
9944        }
9945    }
9946
9947    /**
9948     * The amount that the view is scaled in y around the pivot point, as a proportion of
9949     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9950     *
9951     * <p>By default, this is 1.0f.
9952     *
9953     * @see #getPivotX()
9954     * @see #getPivotY()
9955     * @return The scaling factor.
9956     */
9957    @ViewDebug.ExportedProperty(category = "drawing")
9958    public float getScaleY() {
9959        return mRenderNode.getScaleY();
9960    }
9961
9962    /**
9963     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9964     * the view's unscaled width. A value of 1 means that no scaling is applied.
9965     *
9966     * @param scaleY The scaling factor.
9967     * @see #getPivotX()
9968     * @see #getPivotY()
9969     *
9970     * @attr ref android.R.styleable#View_scaleY
9971     */
9972    public void setScaleY(float scaleY) {
9973        if (scaleY != getScaleY()) {
9974            invalidateViewProperty(true, false);
9975            mRenderNode.setScaleY(scaleY);
9976            invalidateViewProperty(false, true);
9977
9978            invalidateParentIfNeededAndWasQuickRejected();
9979            notifySubtreeAccessibilityStateChangedIfNeeded();
9980        }
9981    }
9982
9983    /**
9984     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9985     * and {@link #setScaleX(float) scaled}.
9986     *
9987     * @see #getRotation()
9988     * @see #getScaleX()
9989     * @see #getScaleY()
9990     * @see #getPivotY()
9991     * @return The x location of the pivot point.
9992     *
9993     * @attr ref android.R.styleable#View_transformPivotX
9994     */
9995    @ViewDebug.ExportedProperty(category = "drawing")
9996    public float getPivotX() {
9997        return mRenderNode.getPivotX();
9998    }
9999
10000    /**
10001     * Sets the x location of the point around which the view is
10002     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10003     * By default, the pivot point is centered on the object.
10004     * Setting this property disables this behavior and causes the view to use only the
10005     * explicitly set pivotX and pivotY values.
10006     *
10007     * @param pivotX The x location of the pivot point.
10008     * @see #getRotation()
10009     * @see #getScaleX()
10010     * @see #getScaleY()
10011     * @see #getPivotY()
10012     *
10013     * @attr ref android.R.styleable#View_transformPivotX
10014     */
10015    public void setPivotX(float pivotX) {
10016        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10017            invalidateViewProperty(true, false);
10018            mRenderNode.setPivotX(pivotX);
10019            invalidateViewProperty(false, true);
10020
10021            invalidateParentIfNeededAndWasQuickRejected();
10022        }
10023    }
10024
10025    /**
10026     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10027     * and {@link #setScaleY(float) scaled}.
10028     *
10029     * @see #getRotation()
10030     * @see #getScaleX()
10031     * @see #getScaleY()
10032     * @see #getPivotY()
10033     * @return The y location of the pivot point.
10034     *
10035     * @attr ref android.R.styleable#View_transformPivotY
10036     */
10037    @ViewDebug.ExportedProperty(category = "drawing")
10038    public float getPivotY() {
10039        return mRenderNode.getPivotY();
10040    }
10041
10042    /**
10043     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10044     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10045     * Setting this property disables this behavior and causes the view to use only the
10046     * explicitly set pivotX and pivotY values.
10047     *
10048     * @param pivotY The y location of the pivot point.
10049     * @see #getRotation()
10050     * @see #getScaleX()
10051     * @see #getScaleY()
10052     * @see #getPivotY()
10053     *
10054     * @attr ref android.R.styleable#View_transformPivotY
10055     */
10056    public void setPivotY(float pivotY) {
10057        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10058            invalidateViewProperty(true, false);
10059            mRenderNode.setPivotY(pivotY);
10060            invalidateViewProperty(false, true);
10061
10062            invalidateParentIfNeededAndWasQuickRejected();
10063        }
10064    }
10065
10066    /**
10067     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10068     * completely transparent and 1 means the view is completely opaque.
10069     *
10070     * <p>By default this is 1.0f.
10071     * @return The opacity of the view.
10072     */
10073    @ViewDebug.ExportedProperty(category = "drawing")
10074    public float getAlpha() {
10075        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10076    }
10077
10078    /**
10079     * Returns whether this View has content which overlaps.
10080     *
10081     * <p>This function, intended to be overridden by specific View types, is an optimization when
10082     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10083     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10084     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10085     * directly. An example of overlapping rendering is a TextView with a background image, such as
10086     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10087     * ImageView with only the foreground image. The default implementation returns true; subclasses
10088     * should override if they have cases which can be optimized.</p>
10089     *
10090     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10091     * necessitates that a View return true if it uses the methods internally without passing the
10092     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10093     *
10094     * @return true if the content in this view might overlap, false otherwise.
10095     */
10096    public boolean hasOverlappingRendering() {
10097        return true;
10098    }
10099
10100    /**
10101     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10102     * completely transparent and 1 means the view is completely opaque.</p>
10103     *
10104     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10105     * performance implications, especially for large views. It is best to use the alpha property
10106     * sparingly and transiently, as in the case of fading animations.</p>
10107     *
10108     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10109     * strongly recommended for performance reasons to either override
10110     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10111     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10112     *
10113     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10114     * responsible for applying the opacity itself.</p>
10115     *
10116     * <p>Note that if the view is backed by a
10117     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10118     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10119     * 1.0 will supercede the alpha of the layer paint.</p>
10120     *
10121     * @param alpha The opacity of the view.
10122     *
10123     * @see #hasOverlappingRendering()
10124     * @see #setLayerType(int, android.graphics.Paint)
10125     *
10126     * @attr ref android.R.styleable#View_alpha
10127     */
10128    public void setAlpha(float alpha) {
10129        ensureTransformationInfo();
10130        if (mTransformationInfo.mAlpha != alpha) {
10131            mTransformationInfo.mAlpha = alpha;
10132            if (onSetAlpha((int) (alpha * 255))) {
10133                mPrivateFlags |= PFLAG_ALPHA_SET;
10134                // subclass is handling alpha - don't optimize rendering cache invalidation
10135                invalidateParentCaches();
10136                invalidate(true);
10137            } else {
10138                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10139                invalidateViewProperty(true, false);
10140                mRenderNode.setAlpha(getFinalAlpha());
10141                notifyViewAccessibilityStateChangedIfNeeded(
10142                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10143            }
10144        }
10145    }
10146
10147    /**
10148     * Faster version of setAlpha() which performs the same steps except there are
10149     * no calls to invalidate(). The caller of this function should perform proper invalidation
10150     * on the parent and this object. The return value indicates whether the subclass handles
10151     * alpha (the return value for onSetAlpha()).
10152     *
10153     * @param alpha The new value for the alpha property
10154     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10155     *         the new value for the alpha property is different from the old value
10156     */
10157    boolean setAlphaNoInvalidation(float alpha) {
10158        ensureTransformationInfo();
10159        if (mTransformationInfo.mAlpha != alpha) {
10160            mTransformationInfo.mAlpha = alpha;
10161            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10162            if (subclassHandlesAlpha) {
10163                mPrivateFlags |= PFLAG_ALPHA_SET;
10164                return true;
10165            } else {
10166                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10167                mRenderNode.setAlpha(getFinalAlpha());
10168            }
10169        }
10170        return false;
10171    }
10172
10173    /**
10174     * This property is hidden and intended only for use by the Fade transition, which
10175     * animates it to produce a visual translucency that does not side-effect (or get
10176     * affected by) the real alpha property. This value is composited with the other
10177     * alpha value (and the AlphaAnimation value, when that is present) to produce
10178     * a final visual translucency result, which is what is passed into the DisplayList.
10179     *
10180     * @hide
10181     */
10182    public void setTransitionAlpha(float alpha) {
10183        ensureTransformationInfo();
10184        if (mTransformationInfo.mTransitionAlpha != alpha) {
10185            mTransformationInfo.mTransitionAlpha = alpha;
10186            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10187            invalidateViewProperty(true, false);
10188            mRenderNode.setAlpha(getFinalAlpha());
10189        }
10190    }
10191
10192    /**
10193     * Calculates the visual alpha of this view, which is a combination of the actual
10194     * alpha value and the transitionAlpha value (if set).
10195     */
10196    private float getFinalAlpha() {
10197        if (mTransformationInfo != null) {
10198            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10199        }
10200        return 1;
10201    }
10202
10203    /**
10204     * This property is hidden and intended only for use by the Fade transition, which
10205     * animates it to produce a visual translucency that does not side-effect (or get
10206     * affected by) the real alpha property. This value is composited with the other
10207     * alpha value (and the AlphaAnimation value, when that is present) to produce
10208     * a final visual translucency result, which is what is passed into the DisplayList.
10209     *
10210     * @hide
10211     */
10212    public float getTransitionAlpha() {
10213        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10214    }
10215
10216    /**
10217     * Top position of this view relative to its parent.
10218     *
10219     * @return The top of this view, in pixels.
10220     */
10221    @ViewDebug.CapturedViewProperty
10222    public final int getTop() {
10223        return mTop;
10224    }
10225
10226    /**
10227     * Sets the top position of this view relative to its parent. This method is meant to be called
10228     * by the layout system and should not generally be called otherwise, because the property
10229     * may be changed at any time by the layout.
10230     *
10231     * @param top The top of this view, in pixels.
10232     */
10233    public final void setTop(int top) {
10234        if (top != mTop) {
10235            final boolean matrixIsIdentity = hasIdentityMatrix();
10236            if (matrixIsIdentity) {
10237                if (mAttachInfo != null) {
10238                    int minTop;
10239                    int yLoc;
10240                    if (top < mTop) {
10241                        minTop = top;
10242                        yLoc = top - mTop;
10243                    } else {
10244                        minTop = mTop;
10245                        yLoc = 0;
10246                    }
10247                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10248                }
10249            } else {
10250                // Double-invalidation is necessary to capture view's old and new areas
10251                invalidate(true);
10252            }
10253
10254            int width = mRight - mLeft;
10255            int oldHeight = mBottom - mTop;
10256
10257            mTop = top;
10258            mRenderNode.setTop(mTop);
10259
10260            sizeChange(width, mBottom - mTop, width, oldHeight);
10261
10262            if (!matrixIsIdentity) {
10263                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10264                invalidate(true);
10265            }
10266            mBackgroundSizeChanged = true;
10267            invalidateParentIfNeeded();
10268            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10269                // View was rejected last time it was drawn by its parent; this may have changed
10270                invalidateParentIfNeeded();
10271            }
10272        }
10273    }
10274
10275    /**
10276     * Bottom position of this view relative to its parent.
10277     *
10278     * @return The bottom of this view, in pixels.
10279     */
10280    @ViewDebug.CapturedViewProperty
10281    public final int getBottom() {
10282        return mBottom;
10283    }
10284
10285    /**
10286     * True if this view has changed since the last time being drawn.
10287     *
10288     * @return The dirty state of this view.
10289     */
10290    public boolean isDirty() {
10291        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10292    }
10293
10294    /**
10295     * Sets the bottom position of this view relative to its parent. This method is meant to be
10296     * called by the layout system and should not generally be called otherwise, because the
10297     * property may be changed at any time by the layout.
10298     *
10299     * @param bottom The bottom of this view, in pixels.
10300     */
10301    public final void setBottom(int bottom) {
10302        if (bottom != mBottom) {
10303            final boolean matrixIsIdentity = hasIdentityMatrix();
10304            if (matrixIsIdentity) {
10305                if (mAttachInfo != null) {
10306                    int maxBottom;
10307                    if (bottom < mBottom) {
10308                        maxBottom = mBottom;
10309                    } else {
10310                        maxBottom = bottom;
10311                    }
10312                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10313                }
10314            } else {
10315                // Double-invalidation is necessary to capture view's old and new areas
10316                invalidate(true);
10317            }
10318
10319            int width = mRight - mLeft;
10320            int oldHeight = mBottom - mTop;
10321
10322            mBottom = bottom;
10323            mRenderNode.setBottom(mBottom);
10324
10325            sizeChange(width, mBottom - mTop, width, oldHeight);
10326
10327            if (!matrixIsIdentity) {
10328                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10329                invalidate(true);
10330            }
10331            mBackgroundSizeChanged = true;
10332            invalidateParentIfNeeded();
10333            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10334                // View was rejected last time it was drawn by its parent; this may have changed
10335                invalidateParentIfNeeded();
10336            }
10337        }
10338    }
10339
10340    /**
10341     * Left position of this view relative to its parent.
10342     *
10343     * @return The left edge of this view, in pixels.
10344     */
10345    @ViewDebug.CapturedViewProperty
10346    public final int getLeft() {
10347        return mLeft;
10348    }
10349
10350    /**
10351     * Sets the left position of this view relative to its parent. This method is meant to be called
10352     * by the layout system and should not generally be called otherwise, because the property
10353     * may be changed at any time by the layout.
10354     *
10355     * @param left The left of this view, in pixels.
10356     */
10357    public final void setLeft(int left) {
10358        if (left != mLeft) {
10359            final boolean matrixIsIdentity = hasIdentityMatrix();
10360            if (matrixIsIdentity) {
10361                if (mAttachInfo != null) {
10362                    int minLeft;
10363                    int xLoc;
10364                    if (left < mLeft) {
10365                        minLeft = left;
10366                        xLoc = left - mLeft;
10367                    } else {
10368                        minLeft = mLeft;
10369                        xLoc = 0;
10370                    }
10371                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10372                }
10373            } else {
10374                // Double-invalidation is necessary to capture view's old and new areas
10375                invalidate(true);
10376            }
10377
10378            int oldWidth = mRight - mLeft;
10379            int height = mBottom - mTop;
10380
10381            mLeft = left;
10382            mRenderNode.setLeft(left);
10383
10384            sizeChange(mRight - mLeft, height, oldWidth, height);
10385
10386            if (!matrixIsIdentity) {
10387                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10388                invalidate(true);
10389            }
10390            mBackgroundSizeChanged = true;
10391            invalidateParentIfNeeded();
10392            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10393                // View was rejected last time it was drawn by its parent; this may have changed
10394                invalidateParentIfNeeded();
10395            }
10396        }
10397    }
10398
10399    /**
10400     * Right position of this view relative to its parent.
10401     *
10402     * @return The right edge of this view, in pixels.
10403     */
10404    @ViewDebug.CapturedViewProperty
10405    public final int getRight() {
10406        return mRight;
10407    }
10408
10409    /**
10410     * Sets the right position of this view relative to its parent. This method is meant to be called
10411     * by the layout system and should not generally be called otherwise, because the property
10412     * may be changed at any time by the layout.
10413     *
10414     * @param right The right of this view, in pixels.
10415     */
10416    public final void setRight(int right) {
10417        if (right != mRight) {
10418            final boolean matrixIsIdentity = hasIdentityMatrix();
10419            if (matrixIsIdentity) {
10420                if (mAttachInfo != null) {
10421                    int maxRight;
10422                    if (right < mRight) {
10423                        maxRight = mRight;
10424                    } else {
10425                        maxRight = right;
10426                    }
10427                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10428                }
10429            } else {
10430                // Double-invalidation is necessary to capture view's old and new areas
10431                invalidate(true);
10432            }
10433
10434            int oldWidth = mRight - mLeft;
10435            int height = mBottom - mTop;
10436
10437            mRight = right;
10438            mRenderNode.setRight(mRight);
10439
10440            sizeChange(mRight - mLeft, height, oldWidth, height);
10441
10442            if (!matrixIsIdentity) {
10443                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10444                invalidate(true);
10445            }
10446            mBackgroundSizeChanged = true;
10447            invalidateParentIfNeeded();
10448            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10449                // View was rejected last time it was drawn by its parent; this may have changed
10450                invalidateParentIfNeeded();
10451            }
10452        }
10453    }
10454
10455    /**
10456     * The visual x position of this view, in pixels. This is equivalent to the
10457     * {@link #setTranslationX(float) translationX} property plus the current
10458     * {@link #getLeft() left} property.
10459     *
10460     * @return The visual x position of this view, in pixels.
10461     */
10462    @ViewDebug.ExportedProperty(category = "drawing")
10463    public float getX() {
10464        return mLeft + getTranslationX();
10465    }
10466
10467    /**
10468     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10469     * {@link #setTranslationX(float) translationX} property to be the difference between
10470     * the x value passed in and the current {@link #getLeft() left} property.
10471     *
10472     * @param x The visual x position of this view, in pixels.
10473     */
10474    public void setX(float x) {
10475        setTranslationX(x - mLeft);
10476    }
10477
10478    /**
10479     * The visual y position of this view, in pixels. This is equivalent to the
10480     * {@link #setTranslationY(float) translationY} property plus the current
10481     * {@link #getTop() top} property.
10482     *
10483     * @return The visual y position of this view, in pixels.
10484     */
10485    @ViewDebug.ExportedProperty(category = "drawing")
10486    public float getY() {
10487        return mTop + getTranslationY();
10488    }
10489
10490    /**
10491     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10492     * {@link #setTranslationY(float) translationY} property to be the difference between
10493     * the y value passed in and the current {@link #getTop() top} property.
10494     *
10495     * @param y The visual y position of this view, in pixels.
10496     */
10497    public void setY(float y) {
10498        setTranslationY(y - mTop);
10499    }
10500
10501    /**
10502     * The visual z position of this view, in pixels. This is equivalent to the
10503     * {@link #setTranslationZ(float) translationZ} property plus the current
10504     * {@link #getElevation() elevation} property.
10505     *
10506     * @return The visual z position of this view, in pixels.
10507     */
10508    @ViewDebug.ExportedProperty(category = "drawing")
10509    public float getZ() {
10510        return getElevation() + getTranslationZ();
10511    }
10512
10513    /**
10514     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10515     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10516     * the x value passed in and the current {@link #getElevation() elevation} property.
10517     *
10518     * @param z The visual z position of this view, in pixels.
10519     */
10520    public void setZ(float z) {
10521        setTranslationZ(z - getElevation());
10522    }
10523
10524    @ViewDebug.ExportedProperty(category = "drawing")
10525    public float getElevation() {
10526        return mRenderNode.getElevation();
10527    }
10528
10529    /**
10530     * Sets the base depth location of this view.
10531     *
10532     * @attr ref android.R.styleable#View_elevation
10533     */
10534    public void setElevation(float elevation) {
10535        if (elevation != getElevation()) {
10536            invalidateViewProperty(true, false);
10537            mRenderNode.setElevation(elevation);
10538            invalidateViewProperty(false, true);
10539
10540            invalidateParentIfNeededAndWasQuickRejected();
10541        }
10542    }
10543
10544    /**
10545     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10546     * This position is post-layout, in addition to wherever the object's
10547     * layout placed it.
10548     *
10549     * @return The horizontal position of this view relative to its left position, in pixels.
10550     */
10551    @ViewDebug.ExportedProperty(category = "drawing")
10552    public float getTranslationX() {
10553        return mRenderNode.getTranslationX();
10554    }
10555
10556    /**
10557     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10558     * This effectively positions the object post-layout, in addition to wherever the object's
10559     * layout placed it.
10560     *
10561     * @param translationX The horizontal position of this view relative to its left position,
10562     * in pixels.
10563     *
10564     * @attr ref android.R.styleable#View_translationX
10565     */
10566    public void setTranslationX(float translationX) {
10567        if (translationX != getTranslationX()) {
10568            invalidateViewProperty(true, false);
10569            mRenderNode.setTranslationX(translationX);
10570            invalidateViewProperty(false, true);
10571
10572            invalidateParentIfNeededAndWasQuickRejected();
10573            notifySubtreeAccessibilityStateChangedIfNeeded();
10574        }
10575    }
10576
10577    /**
10578     * The vertical location of this view relative to its {@link #getTop() top} position.
10579     * This position is post-layout, in addition to wherever the object's
10580     * layout placed it.
10581     *
10582     * @return The vertical position of this view relative to its top position,
10583     * in pixels.
10584     */
10585    @ViewDebug.ExportedProperty(category = "drawing")
10586    public float getTranslationY() {
10587        return mRenderNode.getTranslationY();
10588    }
10589
10590    /**
10591     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10592     * This effectively positions the object post-layout, in addition to wherever the object's
10593     * layout placed it.
10594     *
10595     * @param translationY The vertical position of this view relative to its top position,
10596     * in pixels.
10597     *
10598     * @attr ref android.R.styleable#View_translationY
10599     */
10600    public void setTranslationY(float translationY) {
10601        if (translationY != getTranslationY()) {
10602            invalidateViewProperty(true, false);
10603            mRenderNode.setTranslationY(translationY);
10604            invalidateViewProperty(false, true);
10605
10606            invalidateParentIfNeededAndWasQuickRejected();
10607        }
10608    }
10609
10610    /**
10611     * The depth location of this view relative to its {@link #getElevation() elevation}.
10612     *
10613     * @return The depth of this view relative to its elevation.
10614     */
10615    @ViewDebug.ExportedProperty(category = "drawing")
10616    public float getTranslationZ() {
10617        return mRenderNode.getTranslationZ();
10618    }
10619
10620    /**
10621     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10622     *
10623     * @attr ref android.R.styleable#View_translationZ
10624     */
10625    public void setTranslationZ(float translationZ) {
10626        if (translationZ != getTranslationZ()) {
10627            invalidateViewProperty(true, false);
10628            mRenderNode.setTranslationZ(translationZ);
10629            invalidateViewProperty(false, true);
10630
10631            invalidateParentIfNeededAndWasQuickRejected();
10632        }
10633    }
10634
10635    /**
10636     * Returns a ValueAnimator which can animate a clipping circle.
10637     * <p>
10638     * The View will be clipped to the animating circle.
10639     * <p>
10640     * Any shadow cast by the View will respect the circular clip from this animator.
10641     *
10642     * @param centerX The x coordinate of the center of the animating circle.
10643     * @param centerY The y coordinate of the center of the animating circle.
10644     * @param startRadius The starting radius of the animating circle.
10645     * @param endRadius The ending radius of the animating circle.
10646     */
10647    public final ValueAnimator createRevealAnimator(int centerX,  int centerY,
10648            float startRadius, float endRadius) {
10649        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10650                startRadius, endRadius, false);
10651    }
10652
10653    /**
10654     * Returns a ValueAnimator which can animate a clearing circle.
10655     * <p>
10656     * The View is prevented from drawing within the circle, so the content
10657     * behind the View shows through.
10658     *
10659     * @param centerX The x coordinate of the center of the animating circle.
10660     * @param centerY The y coordinate of the center of the animating circle.
10661     * @param startRadius The starting radius of the animating circle.
10662     * @param endRadius The ending radius of the animating circle.
10663     *
10664     * @hide
10665     */
10666    public final ValueAnimator createClearCircleAnimator(int centerX,  int centerY,
10667            float startRadius, float endRadius) {
10668        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10669                startRadius, endRadius, true);
10670    }
10671
10672    /**
10673     * Returns the current StateListAnimator if exists.
10674     *
10675     * @return StateListAnimator or null if it does not exists
10676     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10677     */
10678    public StateListAnimator getStateListAnimator() {
10679        return mStateListAnimator;
10680    }
10681
10682    /**
10683     * Attaches the provided StateListAnimator to this View.
10684     * <p>
10685     * Any previously attached StateListAnimator will be detached.
10686     *
10687     * @param stateListAnimator The StateListAnimator to update the view
10688     * @see {@link android.animation.StateListAnimator}
10689     */
10690    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10691        if (mStateListAnimator == stateListAnimator) {
10692            return;
10693        }
10694        if (mStateListAnimator != null) {
10695            mStateListAnimator.setTarget(null);
10696        }
10697        mStateListAnimator = stateListAnimator;
10698        if (stateListAnimator != null) {
10699            stateListAnimator.setTarget(this);
10700            if (isAttachedToWindow()) {
10701                stateListAnimator.setState(getDrawableState());
10702            }
10703        }
10704    }
10705
10706    /**
10707     * Sets the {@link Outline} of the view, which defines the shape of the shadow it
10708     * casts, and enables outline clipping.
10709     * <p>
10710     * By default, a View queries its Outline from its background drawable, via
10711     * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows
10712     * this behavior to be overridden.
10713     * <p>
10714     * If the outline is {@link Outline#isEmpty()} or is <code>null</code>,
10715     * shadows will not be cast.
10716     * <p>
10717     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10718     *
10719     * @param outline The new outline of the view.
10720     *
10721     * @see #setClipToOutline(boolean)
10722     * @see #getClipToOutline()
10723     */
10724    public void setOutline(@Nullable Outline outline) {
10725        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10726
10727        if (outline == null || outline.isEmpty()) {
10728            if (mOutline != null) {
10729                mOutline.setEmpty();
10730            }
10731        } else {
10732            // always copy the path since caller may reuse
10733            if (mOutline == null) {
10734                mOutline = new Outline();
10735            }
10736            mOutline.set(outline);
10737        }
10738        mRenderNode.setOutline(mOutline);
10739    }
10740
10741    /**
10742     * Returns whether the Outline should be used to clip the contents of the View.
10743     * <p>
10744     * Note that this flag will only be respected if the View's Outline returns true from
10745     * {@link Outline#canClip()}.
10746     *
10747     * @see #setOutline(Outline)
10748     * @see #setClipToOutline(boolean)
10749     */
10750    public final boolean getClipToOutline() {
10751        return mRenderNode.getClipToOutline();
10752    }
10753
10754    /**
10755     * Sets whether the View's Outline should be used to clip the contents of the View.
10756     * <p>
10757     * Note that this flag will only be respected if the View's Outline returns true from
10758     * {@link Outline#canClip()}.
10759     *
10760     * @see #setOutline(Outline)
10761     * @see #getClipToOutline()
10762     */
10763    public void setClipToOutline(boolean clipToOutline) {
10764        damageInParent();
10765        if (getClipToOutline() != clipToOutline) {
10766            mRenderNode.setClipToOutline(clipToOutline);
10767        }
10768    }
10769
10770    private void queryOutlineFromBackgroundIfUndefined() {
10771        if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) {
10772            // Outline not currently defined, query from background
10773            if (mOutline == null) {
10774                mOutline = new Outline();
10775            } else {
10776                //invalidate outline, to ensure background calculates it
10777                mOutline.setEmpty();
10778            }
10779            if (mBackground.getOutline(mOutline)) {
10780                if (mOutline.isEmpty()) {
10781                    throw new IllegalStateException("Background drawable failed to build outline");
10782                }
10783                mRenderNode.setOutline(mOutline);
10784            } else {
10785                mRenderNode.setOutline(null);
10786            }
10787            notifySubtreeAccessibilityStateChangedIfNeeded();
10788        }
10789    }
10790
10791    /**
10792     * Private API to be used for reveal animation
10793     *
10794     * @hide
10795     */
10796    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10797            float x, float y, float radius) {
10798        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10799        // TODO: Handle this invalidate in a better way, or purely in native.
10800        invalidate();
10801    }
10802
10803    /**
10804     * Hit rectangle in parent's coordinates
10805     *
10806     * @param outRect The hit rectangle of the view.
10807     */
10808    public void getHitRect(Rect outRect) {
10809        if (hasIdentityMatrix() || mAttachInfo == null) {
10810            outRect.set(mLeft, mTop, mRight, mBottom);
10811        } else {
10812            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10813            tmpRect.set(0, 0, getWidth(), getHeight());
10814            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10815            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10816                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10817        }
10818    }
10819
10820    /**
10821     * Determines whether the given point, in local coordinates is inside the view.
10822     */
10823    /*package*/ final boolean pointInView(float localX, float localY) {
10824        return localX >= 0 && localX < (mRight - mLeft)
10825                && localY >= 0 && localY < (mBottom - mTop);
10826    }
10827
10828    /**
10829     * Utility method to determine whether the given point, in local coordinates,
10830     * is inside the view, where the area of the view is expanded by the slop factor.
10831     * This method is called while processing touch-move events to determine if the event
10832     * is still within the view.
10833     *
10834     * @hide
10835     */
10836    public boolean pointInView(float localX, float localY, float slop) {
10837        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10838                localY < ((mBottom - mTop) + slop);
10839    }
10840
10841    /**
10842     * When a view has focus and the user navigates away from it, the next view is searched for
10843     * starting from the rectangle filled in by this method.
10844     *
10845     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10846     * of the view.  However, if your view maintains some idea of internal selection,
10847     * such as a cursor, or a selected row or column, you should override this method and
10848     * fill in a more specific rectangle.
10849     *
10850     * @param r The rectangle to fill in, in this view's coordinates.
10851     */
10852    public void getFocusedRect(Rect r) {
10853        getDrawingRect(r);
10854    }
10855
10856    /**
10857     * If some part of this view is not clipped by any of its parents, then
10858     * return that area in r in global (root) coordinates. To convert r to local
10859     * coordinates (without taking possible View rotations into account), offset
10860     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10861     * If the view is completely clipped or translated out, return false.
10862     *
10863     * @param r If true is returned, r holds the global coordinates of the
10864     *        visible portion of this view.
10865     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10866     *        between this view and its root. globalOffet may be null.
10867     * @return true if r is non-empty (i.e. part of the view is visible at the
10868     *         root level.
10869     */
10870    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10871        int width = mRight - mLeft;
10872        int height = mBottom - mTop;
10873        if (width > 0 && height > 0) {
10874            r.set(0, 0, width, height);
10875            if (globalOffset != null) {
10876                globalOffset.set(-mScrollX, -mScrollY);
10877            }
10878            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10879        }
10880        return false;
10881    }
10882
10883    public final boolean getGlobalVisibleRect(Rect r) {
10884        return getGlobalVisibleRect(r, null);
10885    }
10886
10887    public final boolean getLocalVisibleRect(Rect r) {
10888        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10889        if (getGlobalVisibleRect(r, offset)) {
10890            r.offset(-offset.x, -offset.y); // make r local
10891            return true;
10892        }
10893        return false;
10894    }
10895
10896    /**
10897     * Offset this view's vertical location by the specified number of pixels.
10898     *
10899     * @param offset the number of pixels to offset the view by
10900     */
10901    public void offsetTopAndBottom(int offset) {
10902        if (offset != 0) {
10903            final boolean matrixIsIdentity = hasIdentityMatrix();
10904            if (matrixIsIdentity) {
10905                if (isHardwareAccelerated()) {
10906                    invalidateViewProperty(false, false);
10907                } else {
10908                    final ViewParent p = mParent;
10909                    if (p != null && mAttachInfo != null) {
10910                        final Rect r = mAttachInfo.mTmpInvalRect;
10911                        int minTop;
10912                        int maxBottom;
10913                        int yLoc;
10914                        if (offset < 0) {
10915                            minTop = mTop + offset;
10916                            maxBottom = mBottom;
10917                            yLoc = offset;
10918                        } else {
10919                            minTop = mTop;
10920                            maxBottom = mBottom + offset;
10921                            yLoc = 0;
10922                        }
10923                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10924                        p.invalidateChild(this, r);
10925                    }
10926                }
10927            } else {
10928                invalidateViewProperty(false, false);
10929            }
10930
10931            mTop += offset;
10932            mBottom += offset;
10933            mRenderNode.offsetTopAndBottom(offset);
10934            if (isHardwareAccelerated()) {
10935                invalidateViewProperty(false, false);
10936            } else {
10937                if (!matrixIsIdentity) {
10938                    invalidateViewProperty(false, true);
10939                }
10940                invalidateParentIfNeeded();
10941            }
10942            notifySubtreeAccessibilityStateChangedIfNeeded();
10943        }
10944    }
10945
10946    /**
10947     * Offset this view's horizontal location by the specified amount of pixels.
10948     *
10949     * @param offset the number of pixels to offset the view by
10950     */
10951    public void offsetLeftAndRight(int offset) {
10952        if (offset != 0) {
10953            final boolean matrixIsIdentity = hasIdentityMatrix();
10954            if (matrixIsIdentity) {
10955                if (isHardwareAccelerated()) {
10956                    invalidateViewProperty(false, false);
10957                } else {
10958                    final ViewParent p = mParent;
10959                    if (p != null && mAttachInfo != null) {
10960                        final Rect r = mAttachInfo.mTmpInvalRect;
10961                        int minLeft;
10962                        int maxRight;
10963                        if (offset < 0) {
10964                            minLeft = mLeft + offset;
10965                            maxRight = mRight;
10966                        } else {
10967                            minLeft = mLeft;
10968                            maxRight = mRight + offset;
10969                        }
10970                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10971                        p.invalidateChild(this, r);
10972                    }
10973                }
10974            } else {
10975                invalidateViewProperty(false, false);
10976            }
10977
10978            mLeft += offset;
10979            mRight += offset;
10980            mRenderNode.offsetLeftAndRight(offset);
10981            if (isHardwareAccelerated()) {
10982                invalidateViewProperty(false, false);
10983            } else {
10984                if (!matrixIsIdentity) {
10985                    invalidateViewProperty(false, true);
10986                }
10987                invalidateParentIfNeeded();
10988            }
10989            notifySubtreeAccessibilityStateChangedIfNeeded();
10990        }
10991    }
10992
10993    /**
10994     * Get the LayoutParams associated with this view. All views should have
10995     * layout parameters. These supply parameters to the <i>parent</i> of this
10996     * view specifying how it should be arranged. There are many subclasses of
10997     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10998     * of ViewGroup that are responsible for arranging their children.
10999     *
11000     * This method may return null if this View is not attached to a parent
11001     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11002     * was not invoked successfully. When a View is attached to a parent
11003     * ViewGroup, this method must not return null.
11004     *
11005     * @return The LayoutParams associated with this view, or null if no
11006     *         parameters have been set yet
11007     */
11008    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11009    public ViewGroup.LayoutParams getLayoutParams() {
11010        return mLayoutParams;
11011    }
11012
11013    /**
11014     * Set the layout parameters associated with this view. These supply
11015     * parameters to the <i>parent</i> of this view specifying how it should be
11016     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11017     * correspond to the different subclasses of ViewGroup that are responsible
11018     * for arranging their children.
11019     *
11020     * @param params The layout parameters for this view, cannot be null
11021     */
11022    public void setLayoutParams(ViewGroup.LayoutParams params) {
11023        if (params == null) {
11024            throw new NullPointerException("Layout parameters cannot be null");
11025        }
11026        mLayoutParams = params;
11027        resolveLayoutParams();
11028        if (mParent instanceof ViewGroup) {
11029            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11030        }
11031        requestLayout();
11032    }
11033
11034    /**
11035     * Resolve the layout parameters depending on the resolved layout direction
11036     *
11037     * @hide
11038     */
11039    public void resolveLayoutParams() {
11040        if (mLayoutParams != null) {
11041            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11042        }
11043    }
11044
11045    /**
11046     * Set the scrolled position of your view. This will cause a call to
11047     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11048     * invalidated.
11049     * @param x the x position to scroll to
11050     * @param y the y position to scroll to
11051     */
11052    public void scrollTo(int x, int y) {
11053        if (mScrollX != x || mScrollY != y) {
11054            int oldX = mScrollX;
11055            int oldY = mScrollY;
11056            mScrollX = x;
11057            mScrollY = y;
11058            invalidateParentCaches();
11059            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11060            if (!awakenScrollBars()) {
11061                postInvalidateOnAnimation();
11062            }
11063        }
11064    }
11065
11066    /**
11067     * Move the scrolled position of your view. This will cause a call to
11068     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11069     * invalidated.
11070     * @param x the amount of pixels to scroll by horizontally
11071     * @param y the amount of pixels to scroll by vertically
11072     */
11073    public void scrollBy(int x, int y) {
11074        scrollTo(mScrollX + x, mScrollY + y);
11075    }
11076
11077    /**
11078     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11079     * animation to fade the scrollbars out after a default delay. If a subclass
11080     * provides animated scrolling, the start delay should equal the duration
11081     * of the scrolling animation.</p>
11082     *
11083     * <p>The animation starts only if at least one of the scrollbars is
11084     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11085     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11086     * this method returns true, and false otherwise. If the animation is
11087     * started, this method calls {@link #invalidate()}; in that case the
11088     * caller should not call {@link #invalidate()}.</p>
11089     *
11090     * <p>This method should be invoked every time a subclass directly updates
11091     * the scroll parameters.</p>
11092     *
11093     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11094     * and {@link #scrollTo(int, int)}.</p>
11095     *
11096     * @return true if the animation is played, false otherwise
11097     *
11098     * @see #awakenScrollBars(int)
11099     * @see #scrollBy(int, int)
11100     * @see #scrollTo(int, int)
11101     * @see #isHorizontalScrollBarEnabled()
11102     * @see #isVerticalScrollBarEnabled()
11103     * @see #setHorizontalScrollBarEnabled(boolean)
11104     * @see #setVerticalScrollBarEnabled(boolean)
11105     */
11106    protected boolean awakenScrollBars() {
11107        return mScrollCache != null &&
11108                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11109    }
11110
11111    /**
11112     * Trigger the scrollbars to draw.
11113     * This method differs from awakenScrollBars() only in its default duration.
11114     * initialAwakenScrollBars() will show the scroll bars for longer than
11115     * usual to give the user more of a chance to notice them.
11116     *
11117     * @return true if the animation is played, false otherwise.
11118     */
11119    private boolean initialAwakenScrollBars() {
11120        return mScrollCache != null &&
11121                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11122    }
11123
11124    /**
11125     * <p>
11126     * Trigger the scrollbars to draw. When invoked this method starts an
11127     * animation to fade the scrollbars out after a fixed delay. If a subclass
11128     * provides animated scrolling, the start delay should equal the duration of
11129     * the scrolling animation.
11130     * </p>
11131     *
11132     * <p>
11133     * The animation starts only if at least one of the scrollbars is enabled,
11134     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11135     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11136     * this method returns true, and false otherwise. If the animation is
11137     * started, this method calls {@link #invalidate()}; in that case the caller
11138     * should not call {@link #invalidate()}.
11139     * </p>
11140     *
11141     * <p>
11142     * This method should be invoked everytime a subclass directly updates the
11143     * scroll parameters.
11144     * </p>
11145     *
11146     * @param startDelay the delay, in milliseconds, after which the animation
11147     *        should start; when the delay is 0, the animation starts
11148     *        immediately
11149     * @return true if the animation is played, false otherwise
11150     *
11151     * @see #scrollBy(int, int)
11152     * @see #scrollTo(int, int)
11153     * @see #isHorizontalScrollBarEnabled()
11154     * @see #isVerticalScrollBarEnabled()
11155     * @see #setHorizontalScrollBarEnabled(boolean)
11156     * @see #setVerticalScrollBarEnabled(boolean)
11157     */
11158    protected boolean awakenScrollBars(int startDelay) {
11159        return awakenScrollBars(startDelay, true);
11160    }
11161
11162    /**
11163     * <p>
11164     * Trigger the scrollbars to draw. When invoked this method starts an
11165     * animation to fade the scrollbars out after a fixed delay. If a subclass
11166     * provides animated scrolling, the start delay should equal the duration of
11167     * the scrolling animation.
11168     * </p>
11169     *
11170     * <p>
11171     * The animation starts only if at least one of the scrollbars is enabled,
11172     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11173     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11174     * this method returns true, and false otherwise. If the animation is
11175     * started, this method calls {@link #invalidate()} if the invalidate parameter
11176     * is set to true; in that case the caller
11177     * should not call {@link #invalidate()}.
11178     * </p>
11179     *
11180     * <p>
11181     * This method should be invoked everytime a subclass directly updates the
11182     * scroll parameters.
11183     * </p>
11184     *
11185     * @param startDelay the delay, in milliseconds, after which the animation
11186     *        should start; when the delay is 0, the animation starts
11187     *        immediately
11188     *
11189     * @param invalidate Wheter this method should call invalidate
11190     *
11191     * @return true if the animation is played, false otherwise
11192     *
11193     * @see #scrollBy(int, int)
11194     * @see #scrollTo(int, int)
11195     * @see #isHorizontalScrollBarEnabled()
11196     * @see #isVerticalScrollBarEnabled()
11197     * @see #setHorizontalScrollBarEnabled(boolean)
11198     * @see #setVerticalScrollBarEnabled(boolean)
11199     */
11200    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11201        final ScrollabilityCache scrollCache = mScrollCache;
11202
11203        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11204            return false;
11205        }
11206
11207        if (scrollCache.scrollBar == null) {
11208            scrollCache.scrollBar = new ScrollBarDrawable();
11209        }
11210
11211        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11212
11213            if (invalidate) {
11214                // Invalidate to show the scrollbars
11215                postInvalidateOnAnimation();
11216            }
11217
11218            if (scrollCache.state == ScrollabilityCache.OFF) {
11219                // FIXME: this is copied from WindowManagerService.
11220                // We should get this value from the system when it
11221                // is possible to do so.
11222                final int KEY_REPEAT_FIRST_DELAY = 750;
11223                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11224            }
11225
11226            // Tell mScrollCache when we should start fading. This may
11227            // extend the fade start time if one was already scheduled
11228            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11229            scrollCache.fadeStartTime = fadeStartTime;
11230            scrollCache.state = ScrollabilityCache.ON;
11231
11232            // Schedule our fader to run, unscheduling any old ones first
11233            if (mAttachInfo != null) {
11234                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11235                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11236            }
11237
11238            return true;
11239        }
11240
11241        return false;
11242    }
11243
11244    /**
11245     * Do not invalidate views which are not visible and which are not running an animation. They
11246     * will not get drawn and they should not set dirty flags as if they will be drawn
11247     */
11248    private boolean skipInvalidate() {
11249        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11250                (!(mParent instanceof ViewGroup) ||
11251                        !((ViewGroup) mParent).isViewTransitioning(this));
11252    }
11253
11254    /**
11255     * Mark the area defined by dirty as needing to be drawn. If the view is
11256     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11257     * point in the future.
11258     * <p>
11259     * This must be called from a UI thread. To call from a non-UI thread, call
11260     * {@link #postInvalidate()}.
11261     * <p>
11262     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11263     * {@code dirty}.
11264     *
11265     * @param dirty the rectangle representing the bounds of the dirty region
11266     */
11267    public void invalidate(Rect dirty) {
11268        final int scrollX = mScrollX;
11269        final int scrollY = mScrollY;
11270        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11271                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11272    }
11273
11274    /**
11275     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11276     * coordinates of the dirty rect are relative to the view. If the view is
11277     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11278     * point in the future.
11279     * <p>
11280     * This must be called from a UI thread. To call from a non-UI thread, call
11281     * {@link #postInvalidate()}.
11282     *
11283     * @param l the left position of the dirty region
11284     * @param t the top position of the dirty region
11285     * @param r the right position of the dirty region
11286     * @param b the bottom position of the dirty region
11287     */
11288    public void invalidate(int l, int t, int r, int b) {
11289        final int scrollX = mScrollX;
11290        final int scrollY = mScrollY;
11291        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11292    }
11293
11294    /**
11295     * Invalidate the whole view. If the view is visible,
11296     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11297     * the future.
11298     * <p>
11299     * This must be called from a UI thread. To call from a non-UI thread, call
11300     * {@link #postInvalidate()}.
11301     */
11302    public void invalidate() {
11303        invalidate(true);
11304    }
11305
11306    /**
11307     * This is where the invalidate() work actually happens. A full invalidate()
11308     * causes the drawing cache to be invalidated, but this function can be
11309     * called with invalidateCache set to false to skip that invalidation step
11310     * for cases that do not need it (for example, a component that remains at
11311     * the same dimensions with the same content).
11312     *
11313     * @param invalidateCache Whether the drawing cache for this view should be
11314     *            invalidated as well. This is usually true for a full
11315     *            invalidate, but may be set to false if the View's contents or
11316     *            dimensions have not changed.
11317     */
11318    void invalidate(boolean invalidateCache) {
11319        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11320    }
11321
11322    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11323            boolean fullInvalidate) {
11324        if (skipInvalidate()) {
11325            return;
11326        }
11327
11328        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11329                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11330                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11331                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11332            if (fullInvalidate) {
11333                mLastIsOpaque = isOpaque();
11334                mPrivateFlags &= ~PFLAG_DRAWN;
11335            }
11336
11337            mPrivateFlags |= PFLAG_DIRTY;
11338
11339            if (invalidateCache) {
11340                mPrivateFlags |= PFLAG_INVALIDATED;
11341                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11342            }
11343
11344            // Propagate the damage rectangle to the parent view.
11345            final AttachInfo ai = mAttachInfo;
11346            final ViewParent p = mParent;
11347            if (p != null && ai != null && l < r && t < b) {
11348                final Rect damage = ai.mTmpInvalRect;
11349                damage.set(l, t, r, b);
11350                p.invalidateChild(this, damage);
11351            }
11352
11353            // Damage the entire projection receiver, if necessary.
11354            if (mBackground != null && mBackground.isProjected()) {
11355                final View receiver = getProjectionReceiver();
11356                if (receiver != null) {
11357                    receiver.damageInParent();
11358                }
11359            }
11360
11361            // Damage the entire IsolatedZVolume recieving this view's shadow.
11362            if (isHardwareAccelerated() && getZ() != 0) {
11363                damageShadowReceiver();
11364            }
11365        }
11366    }
11367
11368    /**
11369     * @return this view's projection receiver, or {@code null} if none exists
11370     */
11371    private View getProjectionReceiver() {
11372        ViewParent p = getParent();
11373        while (p != null && p instanceof View) {
11374            final View v = (View) p;
11375            if (v.isProjectionReceiver()) {
11376                return v;
11377            }
11378            p = p.getParent();
11379        }
11380
11381        return null;
11382    }
11383
11384    /**
11385     * @return whether the view is a projection receiver
11386     */
11387    private boolean isProjectionReceiver() {
11388        return mBackground != null;
11389    }
11390
11391    /**
11392     * Damage area of the screen that can be covered by this View's shadow.
11393     *
11394     * This method will guarantee that any changes to shadows cast by a View
11395     * are damaged on the screen for future redraw.
11396     */
11397    private void damageShadowReceiver() {
11398        final AttachInfo ai = mAttachInfo;
11399        if (ai != null) {
11400            ViewParent p = getParent();
11401            if (p != null && p instanceof ViewGroup) {
11402                final ViewGroup vg = (ViewGroup) p;
11403                vg.damageInParent();
11404            }
11405        }
11406    }
11407
11408    /**
11409     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11410     * set any flags or handle all of the cases handled by the default invalidation methods.
11411     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11412     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11413     * walk up the hierarchy, transforming the dirty rect as necessary.
11414     *
11415     * The method also handles normal invalidation logic if display list properties are not
11416     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11417     * backup approach, to handle these cases used in the various property-setting methods.
11418     *
11419     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11420     * are not being used in this view
11421     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11422     * list properties are not being used in this view
11423     */
11424    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11425        if (!isHardwareAccelerated()
11426                || !mRenderNode.isValid()
11427                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11428            if (invalidateParent) {
11429                invalidateParentCaches();
11430            }
11431            if (forceRedraw) {
11432                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11433            }
11434            invalidate(false);
11435        } else {
11436            damageInParent();
11437        }
11438        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11439            damageShadowReceiver();
11440        }
11441    }
11442
11443    /**
11444     * Tells the parent view to damage this view's bounds.
11445     *
11446     * @hide
11447     */
11448    protected void damageInParent() {
11449        final AttachInfo ai = mAttachInfo;
11450        final ViewParent p = mParent;
11451        if (p != null && ai != null) {
11452            final Rect r = ai.mTmpInvalRect;
11453            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11454            if (mParent instanceof ViewGroup) {
11455                ((ViewGroup) mParent).damageChild(this, r);
11456            } else {
11457                mParent.invalidateChild(this, r);
11458            }
11459        }
11460    }
11461
11462    /**
11463     * Utility method to transform a given Rect by the current matrix of this view.
11464     */
11465    void transformRect(final Rect rect) {
11466        if (!getMatrix().isIdentity()) {
11467            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11468            boundingRect.set(rect);
11469            getMatrix().mapRect(boundingRect);
11470            rect.set((int) Math.floor(boundingRect.left),
11471                    (int) Math.floor(boundingRect.top),
11472                    (int) Math.ceil(boundingRect.right),
11473                    (int) Math.ceil(boundingRect.bottom));
11474        }
11475    }
11476
11477    /**
11478     * Used to indicate that the parent of this view should clear its caches. This functionality
11479     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11480     * which is necessary when various parent-managed properties of the view change, such as
11481     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11482     * clears the parent caches and does not causes an invalidate event.
11483     *
11484     * @hide
11485     */
11486    protected void invalidateParentCaches() {
11487        if (mParent instanceof View) {
11488            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11489        }
11490    }
11491
11492    /**
11493     * Used to indicate that the parent of this view should be invalidated. This functionality
11494     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11495     * which is necessary when various parent-managed properties of the view change, such as
11496     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11497     * an invalidation event to the parent.
11498     *
11499     * @hide
11500     */
11501    protected void invalidateParentIfNeeded() {
11502        if (isHardwareAccelerated() && mParent instanceof View) {
11503            ((View) mParent).invalidate(true);
11504        }
11505    }
11506
11507    /**
11508     * @hide
11509     */
11510    protected void invalidateParentIfNeededAndWasQuickRejected() {
11511        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11512            // View was rejected last time it was drawn by its parent; this may have changed
11513            invalidateParentIfNeeded();
11514        }
11515    }
11516
11517    /**
11518     * Indicates whether this View is opaque. An opaque View guarantees that it will
11519     * draw all the pixels overlapping its bounds using a fully opaque color.
11520     *
11521     * Subclasses of View should override this method whenever possible to indicate
11522     * whether an instance is opaque. Opaque Views are treated in a special way by
11523     * the View hierarchy, possibly allowing it to perform optimizations during
11524     * invalidate/draw passes.
11525     *
11526     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11527     */
11528    @ViewDebug.ExportedProperty(category = "drawing")
11529    public boolean isOpaque() {
11530        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11531                getFinalAlpha() >= 1.0f;
11532    }
11533
11534    /**
11535     * @hide
11536     */
11537    protected void computeOpaqueFlags() {
11538        // Opaque if:
11539        //   - Has a background
11540        //   - Background is opaque
11541        //   - Doesn't have scrollbars or scrollbars overlay
11542
11543        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11544            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11545        } else {
11546            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11547        }
11548
11549        final int flags = mViewFlags;
11550        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11551                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11552                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11553            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11554        } else {
11555            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11556        }
11557    }
11558
11559    /**
11560     * @hide
11561     */
11562    protected boolean hasOpaqueScrollbars() {
11563        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11564    }
11565
11566    /**
11567     * @return A handler associated with the thread running the View. This
11568     * handler can be used to pump events in the UI events queue.
11569     */
11570    public Handler getHandler() {
11571        final AttachInfo attachInfo = mAttachInfo;
11572        if (attachInfo != null) {
11573            return attachInfo.mHandler;
11574        }
11575        return null;
11576    }
11577
11578    /**
11579     * Gets the view root associated with the View.
11580     * @return The view root, or null if none.
11581     * @hide
11582     */
11583    public ViewRootImpl getViewRootImpl() {
11584        if (mAttachInfo != null) {
11585            return mAttachInfo.mViewRootImpl;
11586        }
11587        return null;
11588    }
11589
11590    /**
11591     * @hide
11592     */
11593    public HardwareRenderer getHardwareRenderer() {
11594        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11595    }
11596
11597    /**
11598     * <p>Causes the Runnable to be added to the message queue.
11599     * The runnable will be run on the user interface thread.</p>
11600     *
11601     * @param action The Runnable that will be executed.
11602     *
11603     * @return Returns true if the Runnable was successfully placed in to the
11604     *         message queue.  Returns false on failure, usually because the
11605     *         looper processing the message queue is exiting.
11606     *
11607     * @see #postDelayed
11608     * @see #removeCallbacks
11609     */
11610    public boolean post(Runnable action) {
11611        final AttachInfo attachInfo = mAttachInfo;
11612        if (attachInfo != null) {
11613            return attachInfo.mHandler.post(action);
11614        }
11615        // Assume that post will succeed later
11616        ViewRootImpl.getRunQueue().post(action);
11617        return true;
11618    }
11619
11620    /**
11621     * <p>Causes the Runnable to be added to the message queue, to be run
11622     * after the specified amount of time elapses.
11623     * The runnable will be run on the user interface thread.</p>
11624     *
11625     * @param action The Runnable that will be executed.
11626     * @param delayMillis The delay (in milliseconds) until the Runnable
11627     *        will be executed.
11628     *
11629     * @return true if the Runnable was successfully placed in to the
11630     *         message queue.  Returns false on failure, usually because the
11631     *         looper processing the message queue is exiting.  Note that a
11632     *         result of true does not mean the Runnable will be processed --
11633     *         if the looper is quit before the delivery time of the message
11634     *         occurs then the message will be dropped.
11635     *
11636     * @see #post
11637     * @see #removeCallbacks
11638     */
11639    public boolean postDelayed(Runnable action, long delayMillis) {
11640        final AttachInfo attachInfo = mAttachInfo;
11641        if (attachInfo != null) {
11642            return attachInfo.mHandler.postDelayed(action, delayMillis);
11643        }
11644        // Assume that post will succeed later
11645        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11646        return true;
11647    }
11648
11649    /**
11650     * <p>Causes the Runnable to execute on the next animation time step.
11651     * The runnable will be run on the user interface thread.</p>
11652     *
11653     * @param action The Runnable that will be executed.
11654     *
11655     * @see #postOnAnimationDelayed
11656     * @see #removeCallbacks
11657     */
11658    public void postOnAnimation(Runnable action) {
11659        final AttachInfo attachInfo = mAttachInfo;
11660        if (attachInfo != null) {
11661            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11662                    Choreographer.CALLBACK_ANIMATION, action, null);
11663        } else {
11664            // Assume that post will succeed later
11665            ViewRootImpl.getRunQueue().post(action);
11666        }
11667    }
11668
11669    /**
11670     * <p>Causes the Runnable to execute on the next animation time step,
11671     * after the specified amount of time elapses.
11672     * The runnable will be run on the user interface thread.</p>
11673     *
11674     * @param action The Runnable that will be executed.
11675     * @param delayMillis The delay (in milliseconds) until the Runnable
11676     *        will be executed.
11677     *
11678     * @see #postOnAnimation
11679     * @see #removeCallbacks
11680     */
11681    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11682        final AttachInfo attachInfo = mAttachInfo;
11683        if (attachInfo != null) {
11684            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11685                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11686        } else {
11687            // Assume that post will succeed later
11688            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11689        }
11690    }
11691
11692    /**
11693     * <p>Removes the specified Runnable from the message queue.</p>
11694     *
11695     * @param action The Runnable to remove from the message handling queue
11696     *
11697     * @return true if this view could ask the Handler to remove the Runnable,
11698     *         false otherwise. When the returned value is true, the Runnable
11699     *         may or may not have been actually removed from the message queue
11700     *         (for instance, if the Runnable was not in the queue already.)
11701     *
11702     * @see #post
11703     * @see #postDelayed
11704     * @see #postOnAnimation
11705     * @see #postOnAnimationDelayed
11706     */
11707    public boolean removeCallbacks(Runnable action) {
11708        if (action != null) {
11709            final AttachInfo attachInfo = mAttachInfo;
11710            if (attachInfo != null) {
11711                attachInfo.mHandler.removeCallbacks(action);
11712                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11713                        Choreographer.CALLBACK_ANIMATION, action, null);
11714            }
11715            // Assume that post will succeed later
11716            ViewRootImpl.getRunQueue().removeCallbacks(action);
11717        }
11718        return true;
11719    }
11720
11721    /**
11722     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11723     * Use this to invalidate the View from a non-UI thread.</p>
11724     *
11725     * <p>This method can be invoked from outside of the UI thread
11726     * only when this View is attached to a window.</p>
11727     *
11728     * @see #invalidate()
11729     * @see #postInvalidateDelayed(long)
11730     */
11731    public void postInvalidate() {
11732        postInvalidateDelayed(0);
11733    }
11734
11735    /**
11736     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11737     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11738     *
11739     * <p>This method can be invoked from outside of the UI thread
11740     * only when this View is attached to a window.</p>
11741     *
11742     * @param left The left coordinate of the rectangle to invalidate.
11743     * @param top The top coordinate of the rectangle to invalidate.
11744     * @param right The right coordinate of the rectangle to invalidate.
11745     * @param bottom The bottom coordinate of the rectangle to invalidate.
11746     *
11747     * @see #invalidate(int, int, int, int)
11748     * @see #invalidate(Rect)
11749     * @see #postInvalidateDelayed(long, int, int, int, int)
11750     */
11751    public void postInvalidate(int left, int top, int right, int bottom) {
11752        postInvalidateDelayed(0, left, top, right, bottom);
11753    }
11754
11755    /**
11756     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11757     * loop. Waits for the specified amount of time.</p>
11758     *
11759     * <p>This method can be invoked from outside of the UI thread
11760     * only when this View is attached to a window.</p>
11761     *
11762     * @param delayMilliseconds the duration in milliseconds to delay the
11763     *         invalidation by
11764     *
11765     * @see #invalidate()
11766     * @see #postInvalidate()
11767     */
11768    public void postInvalidateDelayed(long delayMilliseconds) {
11769        // We try only with the AttachInfo because there's no point in invalidating
11770        // if we are not attached to our window
11771        final AttachInfo attachInfo = mAttachInfo;
11772        if (attachInfo != null) {
11773            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11774        }
11775    }
11776
11777    /**
11778     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11779     * through the event loop. Waits for the specified amount of time.</p>
11780     *
11781     * <p>This method can be invoked from outside of the UI thread
11782     * only when this View is attached to a window.</p>
11783     *
11784     * @param delayMilliseconds the duration in milliseconds to delay the
11785     *         invalidation by
11786     * @param left The left coordinate of the rectangle to invalidate.
11787     * @param top The top coordinate of the rectangle to invalidate.
11788     * @param right The right coordinate of the rectangle to invalidate.
11789     * @param bottom The bottom coordinate of the rectangle to invalidate.
11790     *
11791     * @see #invalidate(int, int, int, int)
11792     * @see #invalidate(Rect)
11793     * @see #postInvalidate(int, int, int, int)
11794     */
11795    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11796            int right, int bottom) {
11797
11798        // We try only with the AttachInfo because there's no point in invalidating
11799        // if we are not attached to our window
11800        final AttachInfo attachInfo = mAttachInfo;
11801        if (attachInfo != null) {
11802            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11803            info.target = this;
11804            info.left = left;
11805            info.top = top;
11806            info.right = right;
11807            info.bottom = bottom;
11808
11809            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11810        }
11811    }
11812
11813    /**
11814     * <p>Cause an invalidate to happen on the next animation time step, typically the
11815     * next display frame.</p>
11816     *
11817     * <p>This method can be invoked from outside of the UI thread
11818     * only when this View is attached to a window.</p>
11819     *
11820     * @see #invalidate()
11821     */
11822    public void postInvalidateOnAnimation() {
11823        // We try only with the AttachInfo because there's no point in invalidating
11824        // if we are not attached to our window
11825        final AttachInfo attachInfo = mAttachInfo;
11826        if (attachInfo != null) {
11827            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11828        }
11829    }
11830
11831    /**
11832     * <p>Cause an invalidate of the specified area to happen on the next animation
11833     * time step, typically the next display frame.</p>
11834     *
11835     * <p>This method can be invoked from outside of the UI thread
11836     * only when this View is attached to a window.</p>
11837     *
11838     * @param left The left coordinate of the rectangle to invalidate.
11839     * @param top The top coordinate of the rectangle to invalidate.
11840     * @param right The right coordinate of the rectangle to invalidate.
11841     * @param bottom The bottom coordinate of the rectangle to invalidate.
11842     *
11843     * @see #invalidate(int, int, int, int)
11844     * @see #invalidate(Rect)
11845     */
11846    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11847        // We try only with the AttachInfo because there's no point in invalidating
11848        // if we are not attached to our window
11849        final AttachInfo attachInfo = mAttachInfo;
11850        if (attachInfo != null) {
11851            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11852            info.target = this;
11853            info.left = left;
11854            info.top = top;
11855            info.right = right;
11856            info.bottom = bottom;
11857
11858            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11859        }
11860    }
11861
11862    /**
11863     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11864     * This event is sent at most once every
11865     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11866     */
11867    private void postSendViewScrolledAccessibilityEventCallback() {
11868        if (mSendViewScrolledAccessibilityEvent == null) {
11869            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11870        }
11871        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11872            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11873            postDelayed(mSendViewScrolledAccessibilityEvent,
11874                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11875        }
11876    }
11877
11878    /**
11879     * Called by a parent to request that a child update its values for mScrollX
11880     * and mScrollY if necessary. This will typically be done if the child is
11881     * animating a scroll using a {@link android.widget.Scroller Scroller}
11882     * object.
11883     */
11884    public void computeScroll() {
11885    }
11886
11887    /**
11888     * <p>Indicate whether the horizontal edges are faded when the view is
11889     * scrolled horizontally.</p>
11890     *
11891     * @return true if the horizontal edges should are faded on scroll, false
11892     *         otherwise
11893     *
11894     * @see #setHorizontalFadingEdgeEnabled(boolean)
11895     *
11896     * @attr ref android.R.styleable#View_requiresFadingEdge
11897     */
11898    public boolean isHorizontalFadingEdgeEnabled() {
11899        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11900    }
11901
11902    /**
11903     * <p>Define whether the horizontal edges should be faded when this view
11904     * is scrolled horizontally.</p>
11905     *
11906     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11907     *                                    be faded when the view is scrolled
11908     *                                    horizontally
11909     *
11910     * @see #isHorizontalFadingEdgeEnabled()
11911     *
11912     * @attr ref android.R.styleable#View_requiresFadingEdge
11913     */
11914    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11915        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11916            if (horizontalFadingEdgeEnabled) {
11917                initScrollCache();
11918            }
11919
11920            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11921        }
11922    }
11923
11924    /**
11925     * <p>Indicate whether the vertical edges are faded when the view is
11926     * scrolled horizontally.</p>
11927     *
11928     * @return true if the vertical edges should are faded on scroll, false
11929     *         otherwise
11930     *
11931     * @see #setVerticalFadingEdgeEnabled(boolean)
11932     *
11933     * @attr ref android.R.styleable#View_requiresFadingEdge
11934     */
11935    public boolean isVerticalFadingEdgeEnabled() {
11936        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11937    }
11938
11939    /**
11940     * <p>Define whether the vertical edges should be faded when this view
11941     * is scrolled vertically.</p>
11942     *
11943     * @param verticalFadingEdgeEnabled true if the vertical edges should
11944     *                                  be faded when the view is scrolled
11945     *                                  vertically
11946     *
11947     * @see #isVerticalFadingEdgeEnabled()
11948     *
11949     * @attr ref android.R.styleable#View_requiresFadingEdge
11950     */
11951    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11952        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11953            if (verticalFadingEdgeEnabled) {
11954                initScrollCache();
11955            }
11956
11957            mViewFlags ^= FADING_EDGE_VERTICAL;
11958        }
11959    }
11960
11961    /**
11962     * Returns the strength, or intensity, of the top faded edge. The strength is
11963     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11964     * returns 0.0 or 1.0 but no value in between.
11965     *
11966     * Subclasses should override this method to provide a smoother fade transition
11967     * when scrolling occurs.
11968     *
11969     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11970     */
11971    protected float getTopFadingEdgeStrength() {
11972        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11973    }
11974
11975    /**
11976     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11977     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11978     * returns 0.0 or 1.0 but no value in between.
11979     *
11980     * Subclasses should override this method to provide a smoother fade transition
11981     * when scrolling occurs.
11982     *
11983     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11984     */
11985    protected float getBottomFadingEdgeStrength() {
11986        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11987                computeVerticalScrollRange() ? 1.0f : 0.0f;
11988    }
11989
11990    /**
11991     * Returns the strength, or intensity, of the left faded edge. The strength is
11992     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11993     * returns 0.0 or 1.0 but no value in between.
11994     *
11995     * Subclasses should override this method to provide a smoother fade transition
11996     * when scrolling occurs.
11997     *
11998     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11999     */
12000    protected float getLeftFadingEdgeStrength() {
12001        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12002    }
12003
12004    /**
12005     * Returns the strength, or intensity, of the right faded edge. The strength is
12006     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12007     * returns 0.0 or 1.0 but no value in between.
12008     *
12009     * Subclasses should override this method to provide a smoother fade transition
12010     * when scrolling occurs.
12011     *
12012     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12013     */
12014    protected float getRightFadingEdgeStrength() {
12015        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12016                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12017    }
12018
12019    /**
12020     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12021     * scrollbar is not drawn by default.</p>
12022     *
12023     * @return true if the horizontal scrollbar should be painted, false
12024     *         otherwise
12025     *
12026     * @see #setHorizontalScrollBarEnabled(boolean)
12027     */
12028    public boolean isHorizontalScrollBarEnabled() {
12029        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12030    }
12031
12032    /**
12033     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12034     * scrollbar is not drawn by default.</p>
12035     *
12036     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12037     *                                   be painted
12038     *
12039     * @see #isHorizontalScrollBarEnabled()
12040     */
12041    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12042        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12043            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12044            computeOpaqueFlags();
12045            resolvePadding();
12046        }
12047    }
12048
12049    /**
12050     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12051     * scrollbar is not drawn by default.</p>
12052     *
12053     * @return true if the vertical scrollbar should be painted, false
12054     *         otherwise
12055     *
12056     * @see #setVerticalScrollBarEnabled(boolean)
12057     */
12058    public boolean isVerticalScrollBarEnabled() {
12059        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12060    }
12061
12062    /**
12063     * <p>Define whether the vertical scrollbar should be drawn or not. The
12064     * scrollbar is not drawn by default.</p>
12065     *
12066     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12067     *                                 be painted
12068     *
12069     * @see #isVerticalScrollBarEnabled()
12070     */
12071    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12072        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12073            mViewFlags ^= SCROLLBARS_VERTICAL;
12074            computeOpaqueFlags();
12075            resolvePadding();
12076        }
12077    }
12078
12079    /**
12080     * @hide
12081     */
12082    protected void recomputePadding() {
12083        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12084    }
12085
12086    /**
12087     * Define whether scrollbars will fade when the view is not scrolling.
12088     *
12089     * @param fadeScrollbars wheter to enable fading
12090     *
12091     * @attr ref android.R.styleable#View_fadeScrollbars
12092     */
12093    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12094        initScrollCache();
12095        final ScrollabilityCache scrollabilityCache = mScrollCache;
12096        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12097        if (fadeScrollbars) {
12098            scrollabilityCache.state = ScrollabilityCache.OFF;
12099        } else {
12100            scrollabilityCache.state = ScrollabilityCache.ON;
12101        }
12102    }
12103
12104    /**
12105     *
12106     * Returns true if scrollbars will fade when this view is not scrolling
12107     *
12108     * @return true if scrollbar fading is enabled
12109     *
12110     * @attr ref android.R.styleable#View_fadeScrollbars
12111     */
12112    public boolean isScrollbarFadingEnabled() {
12113        return mScrollCache != null && mScrollCache.fadeScrollBars;
12114    }
12115
12116    /**
12117     *
12118     * Returns the delay before scrollbars fade.
12119     *
12120     * @return the delay before scrollbars fade
12121     *
12122     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12123     */
12124    public int getScrollBarDefaultDelayBeforeFade() {
12125        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12126                mScrollCache.scrollBarDefaultDelayBeforeFade;
12127    }
12128
12129    /**
12130     * Define the delay before scrollbars fade.
12131     *
12132     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12133     *
12134     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12135     */
12136    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12137        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12138    }
12139
12140    /**
12141     *
12142     * Returns the scrollbar fade duration.
12143     *
12144     * @return the scrollbar fade duration
12145     *
12146     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12147     */
12148    public int getScrollBarFadeDuration() {
12149        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12150                mScrollCache.scrollBarFadeDuration;
12151    }
12152
12153    /**
12154     * Define the scrollbar fade duration.
12155     *
12156     * @param scrollBarFadeDuration - the scrollbar fade duration
12157     *
12158     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12159     */
12160    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12161        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12162    }
12163
12164    /**
12165     *
12166     * Returns the scrollbar size.
12167     *
12168     * @return the scrollbar size
12169     *
12170     * @attr ref android.R.styleable#View_scrollbarSize
12171     */
12172    public int getScrollBarSize() {
12173        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12174                mScrollCache.scrollBarSize;
12175    }
12176
12177    /**
12178     * Define the scrollbar size.
12179     *
12180     * @param scrollBarSize - the scrollbar size
12181     *
12182     * @attr ref android.R.styleable#View_scrollbarSize
12183     */
12184    public void setScrollBarSize(int scrollBarSize) {
12185        getScrollCache().scrollBarSize = scrollBarSize;
12186    }
12187
12188    /**
12189     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12190     * inset. When inset, they add to the padding of the view. And the scrollbars
12191     * can be drawn inside the padding area or on the edge of the view. For example,
12192     * if a view has a background drawable and you want to draw the scrollbars
12193     * inside the padding specified by the drawable, you can use
12194     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12195     * appear at the edge of the view, ignoring the padding, then you can use
12196     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12197     * @param style the style of the scrollbars. Should be one of
12198     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12199     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12200     * @see #SCROLLBARS_INSIDE_OVERLAY
12201     * @see #SCROLLBARS_INSIDE_INSET
12202     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12203     * @see #SCROLLBARS_OUTSIDE_INSET
12204     *
12205     * @attr ref android.R.styleable#View_scrollbarStyle
12206     */
12207    public void setScrollBarStyle(@ScrollBarStyle int style) {
12208        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12209            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12210            computeOpaqueFlags();
12211            resolvePadding();
12212        }
12213    }
12214
12215    /**
12216     * <p>Returns the current scrollbar style.</p>
12217     * @return the current scrollbar style
12218     * @see #SCROLLBARS_INSIDE_OVERLAY
12219     * @see #SCROLLBARS_INSIDE_INSET
12220     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12221     * @see #SCROLLBARS_OUTSIDE_INSET
12222     *
12223     * @attr ref android.R.styleable#View_scrollbarStyle
12224     */
12225    @ViewDebug.ExportedProperty(mapping = {
12226            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12227            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12228            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12229            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12230    })
12231    @ScrollBarStyle
12232    public int getScrollBarStyle() {
12233        return mViewFlags & SCROLLBARS_STYLE_MASK;
12234    }
12235
12236    /**
12237     * <p>Compute the horizontal range that the horizontal scrollbar
12238     * represents.</p>
12239     *
12240     * <p>The range is expressed in arbitrary units that must be the same as the
12241     * units used by {@link #computeHorizontalScrollExtent()} and
12242     * {@link #computeHorizontalScrollOffset()}.</p>
12243     *
12244     * <p>The default range is the drawing width of this view.</p>
12245     *
12246     * @return the total horizontal range represented by the horizontal
12247     *         scrollbar
12248     *
12249     * @see #computeHorizontalScrollExtent()
12250     * @see #computeHorizontalScrollOffset()
12251     * @see android.widget.ScrollBarDrawable
12252     */
12253    protected int computeHorizontalScrollRange() {
12254        return getWidth();
12255    }
12256
12257    /**
12258     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12259     * within the horizontal range. This value is used to compute the position
12260     * of the thumb within the scrollbar's track.</p>
12261     *
12262     * <p>The range is expressed in arbitrary units that must be the same as the
12263     * units used by {@link #computeHorizontalScrollRange()} and
12264     * {@link #computeHorizontalScrollExtent()}.</p>
12265     *
12266     * <p>The default offset is the scroll offset of this view.</p>
12267     *
12268     * @return the horizontal offset of the scrollbar's thumb
12269     *
12270     * @see #computeHorizontalScrollRange()
12271     * @see #computeHorizontalScrollExtent()
12272     * @see android.widget.ScrollBarDrawable
12273     */
12274    protected int computeHorizontalScrollOffset() {
12275        return mScrollX;
12276    }
12277
12278    /**
12279     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12280     * within the horizontal range. This value is used to compute the length
12281     * of the thumb within the scrollbar's track.</p>
12282     *
12283     * <p>The range is expressed in arbitrary units that must be the same as the
12284     * units used by {@link #computeHorizontalScrollRange()} and
12285     * {@link #computeHorizontalScrollOffset()}.</p>
12286     *
12287     * <p>The default extent is the drawing width of this view.</p>
12288     *
12289     * @return the horizontal extent of the scrollbar's thumb
12290     *
12291     * @see #computeHorizontalScrollRange()
12292     * @see #computeHorizontalScrollOffset()
12293     * @see android.widget.ScrollBarDrawable
12294     */
12295    protected int computeHorizontalScrollExtent() {
12296        return getWidth();
12297    }
12298
12299    /**
12300     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12301     *
12302     * <p>The range is expressed in arbitrary units that must be the same as the
12303     * units used by {@link #computeVerticalScrollExtent()} and
12304     * {@link #computeVerticalScrollOffset()}.</p>
12305     *
12306     * @return the total vertical range represented by the vertical scrollbar
12307     *
12308     * <p>The default range is the drawing height of this view.</p>
12309     *
12310     * @see #computeVerticalScrollExtent()
12311     * @see #computeVerticalScrollOffset()
12312     * @see android.widget.ScrollBarDrawable
12313     */
12314    protected int computeVerticalScrollRange() {
12315        return getHeight();
12316    }
12317
12318    /**
12319     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12320     * within the horizontal range. This value is used to compute the position
12321     * of the thumb within the scrollbar's track.</p>
12322     *
12323     * <p>The range is expressed in arbitrary units that must be the same as the
12324     * units used by {@link #computeVerticalScrollRange()} and
12325     * {@link #computeVerticalScrollExtent()}.</p>
12326     *
12327     * <p>The default offset is the scroll offset of this view.</p>
12328     *
12329     * @return the vertical offset of the scrollbar's thumb
12330     *
12331     * @see #computeVerticalScrollRange()
12332     * @see #computeVerticalScrollExtent()
12333     * @see android.widget.ScrollBarDrawable
12334     */
12335    protected int computeVerticalScrollOffset() {
12336        return mScrollY;
12337    }
12338
12339    /**
12340     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12341     * within the vertical range. This value is used to compute the length
12342     * of the thumb within the scrollbar's track.</p>
12343     *
12344     * <p>The range is expressed in arbitrary units that must be the same as the
12345     * units used by {@link #computeVerticalScrollRange()} and
12346     * {@link #computeVerticalScrollOffset()}.</p>
12347     *
12348     * <p>The default extent is the drawing height of this view.</p>
12349     *
12350     * @return the vertical extent of the scrollbar's thumb
12351     *
12352     * @see #computeVerticalScrollRange()
12353     * @see #computeVerticalScrollOffset()
12354     * @see android.widget.ScrollBarDrawable
12355     */
12356    protected int computeVerticalScrollExtent() {
12357        return getHeight();
12358    }
12359
12360    /**
12361     * Check if this view can be scrolled horizontally in a certain direction.
12362     *
12363     * @param direction Negative to check scrolling left, positive to check scrolling right.
12364     * @return true if this view can be scrolled in the specified direction, false otherwise.
12365     */
12366    public boolean canScrollHorizontally(int direction) {
12367        final int offset = computeHorizontalScrollOffset();
12368        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12369        if (range == 0) return false;
12370        if (direction < 0) {
12371            return offset > 0;
12372        } else {
12373            return offset < range - 1;
12374        }
12375    }
12376
12377    /**
12378     * Check if this view can be scrolled vertically in a certain direction.
12379     *
12380     * @param direction Negative to check scrolling up, positive to check scrolling down.
12381     * @return true if this view can be scrolled in the specified direction, false otherwise.
12382     */
12383    public boolean canScrollVertically(int direction) {
12384        final int offset = computeVerticalScrollOffset();
12385        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12386        if (range == 0) return false;
12387        if (direction < 0) {
12388            return offset > 0;
12389        } else {
12390            return offset < range - 1;
12391        }
12392    }
12393
12394    /**
12395     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12396     * scrollbars are painted only if they have been awakened first.</p>
12397     *
12398     * @param canvas the canvas on which to draw the scrollbars
12399     *
12400     * @see #awakenScrollBars(int)
12401     */
12402    protected final void onDrawScrollBars(Canvas canvas) {
12403        // scrollbars are drawn only when the animation is running
12404        final ScrollabilityCache cache = mScrollCache;
12405        if (cache != null) {
12406
12407            int state = cache.state;
12408
12409            if (state == ScrollabilityCache.OFF) {
12410                return;
12411            }
12412
12413            boolean invalidate = false;
12414
12415            if (state == ScrollabilityCache.FADING) {
12416                // We're fading -- get our fade interpolation
12417                if (cache.interpolatorValues == null) {
12418                    cache.interpolatorValues = new float[1];
12419                }
12420
12421                float[] values = cache.interpolatorValues;
12422
12423                // Stops the animation if we're done
12424                if (cache.scrollBarInterpolator.timeToValues(values) ==
12425                        Interpolator.Result.FREEZE_END) {
12426                    cache.state = ScrollabilityCache.OFF;
12427                } else {
12428                    cache.scrollBar.setAlpha(Math.round(values[0]));
12429                }
12430
12431                // This will make the scroll bars inval themselves after
12432                // drawing. We only want this when we're fading so that
12433                // we prevent excessive redraws
12434                invalidate = true;
12435            } else {
12436                // We're just on -- but we may have been fading before so
12437                // reset alpha
12438                cache.scrollBar.setAlpha(255);
12439            }
12440
12441
12442            final int viewFlags = mViewFlags;
12443
12444            final boolean drawHorizontalScrollBar =
12445                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12446            final boolean drawVerticalScrollBar =
12447                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12448                && !isVerticalScrollBarHidden();
12449
12450            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12451                final int width = mRight - mLeft;
12452                final int height = mBottom - mTop;
12453
12454                final ScrollBarDrawable scrollBar = cache.scrollBar;
12455
12456                final int scrollX = mScrollX;
12457                final int scrollY = mScrollY;
12458                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12459
12460                int left;
12461                int top;
12462                int right;
12463                int bottom;
12464
12465                if (drawHorizontalScrollBar) {
12466                    int size = scrollBar.getSize(false);
12467                    if (size <= 0) {
12468                        size = cache.scrollBarSize;
12469                    }
12470
12471                    scrollBar.setParameters(computeHorizontalScrollRange(),
12472                                            computeHorizontalScrollOffset(),
12473                                            computeHorizontalScrollExtent(), false);
12474                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12475                            getVerticalScrollbarWidth() : 0;
12476                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12477                    left = scrollX + (mPaddingLeft & inside);
12478                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12479                    bottom = top + size;
12480                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12481                    if (invalidate) {
12482                        invalidate(left, top, right, bottom);
12483                    }
12484                }
12485
12486                if (drawVerticalScrollBar) {
12487                    int size = scrollBar.getSize(true);
12488                    if (size <= 0) {
12489                        size = cache.scrollBarSize;
12490                    }
12491
12492                    scrollBar.setParameters(computeVerticalScrollRange(),
12493                                            computeVerticalScrollOffset(),
12494                                            computeVerticalScrollExtent(), true);
12495                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12496                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12497                        verticalScrollbarPosition = isLayoutRtl() ?
12498                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12499                    }
12500                    switch (verticalScrollbarPosition) {
12501                        default:
12502                        case SCROLLBAR_POSITION_RIGHT:
12503                            left = scrollX + width - size - (mUserPaddingRight & inside);
12504                            break;
12505                        case SCROLLBAR_POSITION_LEFT:
12506                            left = scrollX + (mUserPaddingLeft & inside);
12507                            break;
12508                    }
12509                    top = scrollY + (mPaddingTop & inside);
12510                    right = left + size;
12511                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12512                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12513                    if (invalidate) {
12514                        invalidate(left, top, right, bottom);
12515                    }
12516                }
12517            }
12518        }
12519    }
12520
12521    /**
12522     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12523     * FastScroller is visible.
12524     * @return whether to temporarily hide the vertical scrollbar
12525     * @hide
12526     */
12527    protected boolean isVerticalScrollBarHidden() {
12528        return false;
12529    }
12530
12531    /**
12532     * <p>Draw the horizontal scrollbar if
12533     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12534     *
12535     * @param canvas the canvas on which to draw the scrollbar
12536     * @param scrollBar the scrollbar's drawable
12537     *
12538     * @see #isHorizontalScrollBarEnabled()
12539     * @see #computeHorizontalScrollRange()
12540     * @see #computeHorizontalScrollExtent()
12541     * @see #computeHorizontalScrollOffset()
12542     * @see android.widget.ScrollBarDrawable
12543     * @hide
12544     */
12545    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12546            int l, int t, int r, int b) {
12547        scrollBar.setBounds(l, t, r, b);
12548        scrollBar.draw(canvas);
12549    }
12550
12551    /**
12552     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12553     * returns true.</p>
12554     *
12555     * @param canvas the canvas on which to draw the scrollbar
12556     * @param scrollBar the scrollbar's drawable
12557     *
12558     * @see #isVerticalScrollBarEnabled()
12559     * @see #computeVerticalScrollRange()
12560     * @see #computeVerticalScrollExtent()
12561     * @see #computeVerticalScrollOffset()
12562     * @see android.widget.ScrollBarDrawable
12563     * @hide
12564     */
12565    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12566            int l, int t, int r, int b) {
12567        scrollBar.setBounds(l, t, r, b);
12568        scrollBar.draw(canvas);
12569    }
12570
12571    /**
12572     * Implement this to do your drawing.
12573     *
12574     * @param canvas the canvas on which the background will be drawn
12575     */
12576    protected void onDraw(Canvas canvas) {
12577    }
12578
12579    /*
12580     * Caller is responsible for calling requestLayout if necessary.
12581     * (This allows addViewInLayout to not request a new layout.)
12582     */
12583    void assignParent(ViewParent parent) {
12584        if (mParent == null) {
12585            mParent = parent;
12586        } else if (parent == null) {
12587            mParent = null;
12588        } else {
12589            throw new RuntimeException("view " + this + " being added, but"
12590                    + " it already has a parent");
12591        }
12592    }
12593
12594    /**
12595     * This is called when the view is attached to a window.  At this point it
12596     * has a Surface and will start drawing.  Note that this function is
12597     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12598     * however it may be called any time before the first onDraw -- including
12599     * before or after {@link #onMeasure(int, int)}.
12600     *
12601     * @see #onDetachedFromWindow()
12602     */
12603    protected void onAttachedToWindow() {
12604        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12605            mParent.requestTransparentRegion(this);
12606        }
12607
12608        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12609            initialAwakenScrollBars();
12610            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12611        }
12612
12613        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12614
12615        jumpDrawablesToCurrentState();
12616
12617        resetSubtreeAccessibilityStateChanged();
12618
12619        if (isFocused()) {
12620            InputMethodManager imm = InputMethodManager.peekInstance();
12621            imm.focusIn(this);
12622        }
12623    }
12624
12625    /**
12626     * Resolve all RTL related properties.
12627     *
12628     * @return true if resolution of RTL properties has been done
12629     *
12630     * @hide
12631     */
12632    public boolean resolveRtlPropertiesIfNeeded() {
12633        if (!needRtlPropertiesResolution()) return false;
12634
12635        // Order is important here: LayoutDirection MUST be resolved first
12636        if (!isLayoutDirectionResolved()) {
12637            resolveLayoutDirection();
12638            resolveLayoutParams();
12639        }
12640        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12641        if (!isTextDirectionResolved()) {
12642            resolveTextDirection();
12643        }
12644        if (!isTextAlignmentResolved()) {
12645            resolveTextAlignment();
12646        }
12647        // Should resolve Drawables before Padding because we need the layout direction of the
12648        // Drawable to correctly resolve Padding.
12649        if (!isDrawablesResolved()) {
12650            resolveDrawables();
12651        }
12652        if (!isPaddingResolved()) {
12653            resolvePadding();
12654        }
12655        onRtlPropertiesChanged(getLayoutDirection());
12656        return true;
12657    }
12658
12659    /**
12660     * Reset resolution of all RTL related properties.
12661     *
12662     * @hide
12663     */
12664    public void resetRtlProperties() {
12665        resetResolvedLayoutDirection();
12666        resetResolvedTextDirection();
12667        resetResolvedTextAlignment();
12668        resetResolvedPadding();
12669        resetResolvedDrawables();
12670    }
12671
12672    /**
12673     * @see #onScreenStateChanged(int)
12674     */
12675    void dispatchScreenStateChanged(int screenState) {
12676        onScreenStateChanged(screenState);
12677    }
12678
12679    /**
12680     * This method is called whenever the state of the screen this view is
12681     * attached to changes. A state change will usually occurs when the screen
12682     * turns on or off (whether it happens automatically or the user does it
12683     * manually.)
12684     *
12685     * @param screenState The new state of the screen. Can be either
12686     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12687     */
12688    public void onScreenStateChanged(int screenState) {
12689    }
12690
12691    /**
12692     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12693     */
12694    private boolean hasRtlSupport() {
12695        return mContext.getApplicationInfo().hasRtlSupport();
12696    }
12697
12698    /**
12699     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12700     * RTL not supported)
12701     */
12702    private boolean isRtlCompatibilityMode() {
12703        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12704        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12705    }
12706
12707    /**
12708     * @return true if RTL properties need resolution.
12709     *
12710     */
12711    private boolean needRtlPropertiesResolution() {
12712        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12713    }
12714
12715    /**
12716     * Called when any RTL property (layout direction or text direction or text alignment) has
12717     * been changed.
12718     *
12719     * Subclasses need to override this method to take care of cached information that depends on the
12720     * resolved layout direction, or to inform child views that inherit their layout direction.
12721     *
12722     * The default implementation does nothing.
12723     *
12724     * @param layoutDirection the direction of the layout
12725     *
12726     * @see #LAYOUT_DIRECTION_LTR
12727     * @see #LAYOUT_DIRECTION_RTL
12728     */
12729    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12730    }
12731
12732    /**
12733     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12734     * that the parent directionality can and will be resolved before its children.
12735     *
12736     * @return true if resolution has been done, false otherwise.
12737     *
12738     * @hide
12739     */
12740    public boolean resolveLayoutDirection() {
12741        // Clear any previous layout direction resolution
12742        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12743
12744        if (hasRtlSupport()) {
12745            // Set resolved depending on layout direction
12746            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12747                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12748                case LAYOUT_DIRECTION_INHERIT:
12749                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12750                    // later to get the correct resolved value
12751                    if (!canResolveLayoutDirection()) return false;
12752
12753                    // Parent has not yet resolved, LTR is still the default
12754                    try {
12755                        if (!mParent.isLayoutDirectionResolved()) return false;
12756
12757                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12758                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12759                        }
12760                    } catch (AbstractMethodError e) {
12761                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12762                                " does not fully implement ViewParent", e);
12763                    }
12764                    break;
12765                case LAYOUT_DIRECTION_RTL:
12766                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12767                    break;
12768                case LAYOUT_DIRECTION_LOCALE:
12769                    if((LAYOUT_DIRECTION_RTL ==
12770                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12771                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12772                    }
12773                    break;
12774                default:
12775                    // Nothing to do, LTR by default
12776            }
12777        }
12778
12779        // Set to resolved
12780        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12781        return true;
12782    }
12783
12784    /**
12785     * Check if layout direction resolution can be done.
12786     *
12787     * @return true if layout direction resolution can be done otherwise return false.
12788     */
12789    public boolean canResolveLayoutDirection() {
12790        switch (getRawLayoutDirection()) {
12791            case LAYOUT_DIRECTION_INHERIT:
12792                if (mParent != null) {
12793                    try {
12794                        return mParent.canResolveLayoutDirection();
12795                    } catch (AbstractMethodError e) {
12796                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12797                                " does not fully implement ViewParent", e);
12798                    }
12799                }
12800                return false;
12801
12802            default:
12803                return true;
12804        }
12805    }
12806
12807    /**
12808     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12809     * {@link #onMeasure(int, int)}.
12810     *
12811     * @hide
12812     */
12813    public void resetResolvedLayoutDirection() {
12814        // Reset the current resolved bits
12815        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12816    }
12817
12818    /**
12819     * @return true if the layout direction is inherited.
12820     *
12821     * @hide
12822     */
12823    public boolean isLayoutDirectionInherited() {
12824        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12825    }
12826
12827    /**
12828     * @return true if layout direction has been resolved.
12829     */
12830    public boolean isLayoutDirectionResolved() {
12831        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12832    }
12833
12834    /**
12835     * Return if padding has been resolved
12836     *
12837     * @hide
12838     */
12839    boolean isPaddingResolved() {
12840        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12841    }
12842
12843    /**
12844     * Resolves padding depending on layout direction, if applicable, and
12845     * recomputes internal padding values to adjust for scroll bars.
12846     *
12847     * @hide
12848     */
12849    public void resolvePadding() {
12850        final int resolvedLayoutDirection = getLayoutDirection();
12851
12852        if (!isRtlCompatibilityMode()) {
12853            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12854            // If start / end padding are defined, they will be resolved (hence overriding) to
12855            // left / right or right / left depending on the resolved layout direction.
12856            // If start / end padding are not defined, use the left / right ones.
12857            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12858                Rect padding = sThreadLocal.get();
12859                if (padding == null) {
12860                    padding = new Rect();
12861                    sThreadLocal.set(padding);
12862                }
12863                mBackground.getPadding(padding);
12864                if (!mLeftPaddingDefined) {
12865                    mUserPaddingLeftInitial = padding.left;
12866                }
12867                if (!mRightPaddingDefined) {
12868                    mUserPaddingRightInitial = padding.right;
12869                }
12870            }
12871            switch (resolvedLayoutDirection) {
12872                case LAYOUT_DIRECTION_RTL:
12873                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12874                        mUserPaddingRight = mUserPaddingStart;
12875                    } else {
12876                        mUserPaddingRight = mUserPaddingRightInitial;
12877                    }
12878                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12879                        mUserPaddingLeft = mUserPaddingEnd;
12880                    } else {
12881                        mUserPaddingLeft = mUserPaddingLeftInitial;
12882                    }
12883                    break;
12884                case LAYOUT_DIRECTION_LTR:
12885                default:
12886                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12887                        mUserPaddingLeft = mUserPaddingStart;
12888                    } else {
12889                        mUserPaddingLeft = mUserPaddingLeftInitial;
12890                    }
12891                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12892                        mUserPaddingRight = mUserPaddingEnd;
12893                    } else {
12894                        mUserPaddingRight = mUserPaddingRightInitial;
12895                    }
12896            }
12897
12898            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12899        }
12900
12901        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12902        onRtlPropertiesChanged(resolvedLayoutDirection);
12903
12904        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12905    }
12906
12907    /**
12908     * Reset the resolved layout direction.
12909     *
12910     * @hide
12911     */
12912    public void resetResolvedPadding() {
12913        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12914    }
12915
12916    /**
12917     * This is called when the view is detached from a window.  At this point it
12918     * no longer has a surface for drawing.
12919     *
12920     * @see #onAttachedToWindow()
12921     */
12922    protected void onDetachedFromWindow() {
12923    }
12924
12925    /**
12926     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12927     * after onDetachedFromWindow().
12928     *
12929     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12930     * The super method should be called at the end of the overriden method to ensure
12931     * subclasses are destroyed first
12932     *
12933     * @hide
12934     */
12935    protected void onDetachedFromWindowInternal() {
12936        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12937        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12938
12939        removeUnsetPressCallback();
12940        removeLongPressCallback();
12941        removePerformClickCallback();
12942        removeSendViewScrolledAccessibilityEventCallback();
12943        stopNestedScroll();
12944
12945        destroyDrawingCache();
12946        destroyLayer(false);
12947
12948        cleanupDraw();
12949        mCurrentAnimation = null;
12950    }
12951
12952    private void cleanupDraw() {
12953        resetDisplayList();
12954        if (mAttachInfo != null) {
12955            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12956        }
12957    }
12958
12959    /**
12960     * This method ensures the hardware renderer is in a valid state
12961     * before executing the specified action.
12962     *
12963     * This method will attempt to set a valid state even if the window
12964     * the renderer is attached to was destroyed.
12965     *
12966     * This method is not guaranteed to work. If the hardware renderer
12967     * does not exist or cannot be put in a valid state, this method
12968     * will not executed the specified action.
12969     *
12970     * The specified action is executed synchronously.
12971     *
12972     * @param action The action to execute after the renderer is in a valid state
12973     *
12974     * @return True if the specified Runnable was executed, false otherwise
12975     *
12976     * @hide
12977     */
12978    public boolean executeHardwareAction(Runnable action) {
12979        //noinspection SimplifiableIfStatement
12980        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12981            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12982        }
12983        return false;
12984    }
12985
12986    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12987    }
12988
12989    /**
12990     * @return The number of times this view has been attached to a window
12991     */
12992    protected int getWindowAttachCount() {
12993        return mWindowAttachCount;
12994    }
12995
12996    /**
12997     * Retrieve a unique token identifying the window this view is attached to.
12998     * @return Return the window's token for use in
12999     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13000     */
13001    public IBinder getWindowToken() {
13002        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13003    }
13004
13005    /**
13006     * Retrieve the {@link WindowId} for the window this view is
13007     * currently attached to.
13008     */
13009    public WindowId getWindowId() {
13010        if (mAttachInfo == null) {
13011            return null;
13012        }
13013        if (mAttachInfo.mWindowId == null) {
13014            try {
13015                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13016                        mAttachInfo.mWindowToken);
13017                mAttachInfo.mWindowId = new WindowId(
13018                        mAttachInfo.mIWindowId);
13019            } catch (RemoteException e) {
13020            }
13021        }
13022        return mAttachInfo.mWindowId;
13023    }
13024
13025    /**
13026     * Retrieve a unique token identifying the top-level "real" window of
13027     * the window that this view is attached to.  That is, this is like
13028     * {@link #getWindowToken}, except if the window this view in is a panel
13029     * window (attached to another containing window), then the token of
13030     * the containing window is returned instead.
13031     *
13032     * @return Returns the associated window token, either
13033     * {@link #getWindowToken()} or the containing window's token.
13034     */
13035    public IBinder getApplicationWindowToken() {
13036        AttachInfo ai = mAttachInfo;
13037        if (ai != null) {
13038            IBinder appWindowToken = ai.mPanelParentWindowToken;
13039            if (appWindowToken == null) {
13040                appWindowToken = ai.mWindowToken;
13041            }
13042            return appWindowToken;
13043        }
13044        return null;
13045    }
13046
13047    /**
13048     * Gets the logical display to which the view's window has been attached.
13049     *
13050     * @return The logical display, or null if the view is not currently attached to a window.
13051     */
13052    public Display getDisplay() {
13053        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13054    }
13055
13056    /**
13057     * Retrieve private session object this view hierarchy is using to
13058     * communicate with the window manager.
13059     * @return the session object to communicate with the window manager
13060     */
13061    /*package*/ IWindowSession getWindowSession() {
13062        return mAttachInfo != null ? mAttachInfo.mSession : null;
13063    }
13064
13065    /**
13066     * @param info the {@link android.view.View.AttachInfo} to associated with
13067     *        this view
13068     */
13069    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13070        //System.out.println("Attached! " + this);
13071        mAttachInfo = info;
13072        if (mOverlay != null) {
13073            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13074        }
13075        mWindowAttachCount++;
13076        // We will need to evaluate the drawable state at least once.
13077        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13078        if (mFloatingTreeObserver != null) {
13079            info.mTreeObserver.merge(mFloatingTreeObserver);
13080            mFloatingTreeObserver = null;
13081        }
13082        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13083            mAttachInfo.mScrollContainers.add(this);
13084            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13085        }
13086        performCollectViewAttributes(mAttachInfo, visibility);
13087        onAttachedToWindow();
13088
13089        ListenerInfo li = mListenerInfo;
13090        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13091                li != null ? li.mOnAttachStateChangeListeners : null;
13092        if (listeners != null && listeners.size() > 0) {
13093            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13094            // perform the dispatching. The iterator is a safe guard against listeners that
13095            // could mutate the list by calling the various add/remove methods. This prevents
13096            // the array from being modified while we iterate it.
13097            for (OnAttachStateChangeListener listener : listeners) {
13098                listener.onViewAttachedToWindow(this);
13099            }
13100        }
13101
13102        int vis = info.mWindowVisibility;
13103        if (vis != GONE) {
13104            onWindowVisibilityChanged(vis);
13105        }
13106        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13107            // If nobody has evaluated the drawable state yet, then do it now.
13108            refreshDrawableState();
13109        }
13110        needGlobalAttributesUpdate(false);
13111    }
13112
13113    void dispatchDetachedFromWindow() {
13114        AttachInfo info = mAttachInfo;
13115        if (info != null) {
13116            int vis = info.mWindowVisibility;
13117            if (vis != GONE) {
13118                onWindowVisibilityChanged(GONE);
13119            }
13120        }
13121
13122        onDetachedFromWindow();
13123        onDetachedFromWindowInternal();
13124
13125        ListenerInfo li = mListenerInfo;
13126        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13127                li != null ? li.mOnAttachStateChangeListeners : null;
13128        if (listeners != null && listeners.size() > 0) {
13129            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13130            // perform the dispatching. The iterator is a safe guard against listeners that
13131            // could mutate the list by calling the various add/remove methods. This prevents
13132            // the array from being modified while we iterate it.
13133            for (OnAttachStateChangeListener listener : listeners) {
13134                listener.onViewDetachedFromWindow(this);
13135            }
13136        }
13137
13138        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13139            mAttachInfo.mScrollContainers.remove(this);
13140            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13141        }
13142
13143        mAttachInfo = null;
13144        if (mOverlay != null) {
13145            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13146        }
13147    }
13148
13149    /**
13150     * Cancel any deferred high-level input events that were previously posted to the event queue.
13151     *
13152     * <p>Many views post high-level events such as click handlers to the event queue
13153     * to run deferred in order to preserve a desired user experience - clearing visible
13154     * pressed states before executing, etc. This method will abort any events of this nature
13155     * that are currently in flight.</p>
13156     *
13157     * <p>Custom views that generate their own high-level deferred input events should override
13158     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13159     *
13160     * <p>This will also cancel pending input events for any child views.</p>
13161     *
13162     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13163     * This will not impact newer events posted after this call that may occur as a result of
13164     * lower-level input events still waiting in the queue. If you are trying to prevent
13165     * double-submitted  events for the duration of some sort of asynchronous transaction
13166     * you should also take other steps to protect against unexpected double inputs e.g. calling
13167     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13168     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13169     */
13170    public final void cancelPendingInputEvents() {
13171        dispatchCancelPendingInputEvents();
13172    }
13173
13174    /**
13175     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13176     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13177     */
13178    void dispatchCancelPendingInputEvents() {
13179        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13180        onCancelPendingInputEvents();
13181        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13182            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13183                    " did not call through to super.onCancelPendingInputEvents()");
13184        }
13185    }
13186
13187    /**
13188     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13189     * a parent view.
13190     *
13191     * <p>This method is responsible for removing any pending high-level input events that were
13192     * posted to the event queue to run later. Custom view classes that post their own deferred
13193     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13194     * {@link android.os.Handler} should override this method, call
13195     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13196     * </p>
13197     */
13198    public void onCancelPendingInputEvents() {
13199        removePerformClickCallback();
13200        cancelLongPress();
13201        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13202    }
13203
13204    /**
13205     * Store this view hierarchy's frozen state into the given container.
13206     *
13207     * @param container The SparseArray in which to save the view's state.
13208     *
13209     * @see #restoreHierarchyState(android.util.SparseArray)
13210     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13211     * @see #onSaveInstanceState()
13212     */
13213    public void saveHierarchyState(SparseArray<Parcelable> container) {
13214        dispatchSaveInstanceState(container);
13215    }
13216
13217    /**
13218     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13219     * this view and its children. May be overridden to modify how freezing happens to a
13220     * view's children; for example, some views may want to not store state for their children.
13221     *
13222     * @param container The SparseArray in which to save the view's state.
13223     *
13224     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13225     * @see #saveHierarchyState(android.util.SparseArray)
13226     * @see #onSaveInstanceState()
13227     */
13228    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13229        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13230            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13231            Parcelable state = onSaveInstanceState();
13232            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13233                throw new IllegalStateException(
13234                        "Derived class did not call super.onSaveInstanceState()");
13235            }
13236            if (state != null) {
13237                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13238                // + ": " + state);
13239                container.put(mID, state);
13240            }
13241        }
13242    }
13243
13244    /**
13245     * Hook allowing a view to generate a representation of its internal state
13246     * that can later be used to create a new instance with that same state.
13247     * This state should only contain information that is not persistent or can
13248     * not be reconstructed later. For example, you will never store your
13249     * current position on screen because that will be computed again when a
13250     * new instance of the view is placed in its view hierarchy.
13251     * <p>
13252     * Some examples of things you may store here: the current cursor position
13253     * in a text view (but usually not the text itself since that is stored in a
13254     * content provider or other persistent storage), the currently selected
13255     * item in a list view.
13256     *
13257     * @return Returns a Parcelable object containing the view's current dynamic
13258     *         state, or null if there is nothing interesting to save. The
13259     *         default implementation returns null.
13260     * @see #onRestoreInstanceState(android.os.Parcelable)
13261     * @see #saveHierarchyState(android.util.SparseArray)
13262     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13263     * @see #setSaveEnabled(boolean)
13264     */
13265    protected Parcelable onSaveInstanceState() {
13266        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13267        return BaseSavedState.EMPTY_STATE;
13268    }
13269
13270    /**
13271     * Restore this view hierarchy's frozen state from the given container.
13272     *
13273     * @param container The SparseArray which holds previously frozen states.
13274     *
13275     * @see #saveHierarchyState(android.util.SparseArray)
13276     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13277     * @see #onRestoreInstanceState(android.os.Parcelable)
13278     */
13279    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13280        dispatchRestoreInstanceState(container);
13281    }
13282
13283    /**
13284     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13285     * state for this view and its children. May be overridden to modify how restoring
13286     * happens to a view's children; for example, some views may want to not store state
13287     * for their children.
13288     *
13289     * @param container The SparseArray which holds previously saved state.
13290     *
13291     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13292     * @see #restoreHierarchyState(android.util.SparseArray)
13293     * @see #onRestoreInstanceState(android.os.Parcelable)
13294     */
13295    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13296        if (mID != NO_ID) {
13297            Parcelable state = container.get(mID);
13298            if (state != null) {
13299                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13300                // + ": " + state);
13301                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13302                onRestoreInstanceState(state);
13303                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13304                    throw new IllegalStateException(
13305                            "Derived class did not call super.onRestoreInstanceState()");
13306                }
13307            }
13308        }
13309    }
13310
13311    /**
13312     * Hook allowing a view to re-apply a representation of its internal state that had previously
13313     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13314     * null state.
13315     *
13316     * @param state The frozen state that had previously been returned by
13317     *        {@link #onSaveInstanceState}.
13318     *
13319     * @see #onSaveInstanceState()
13320     * @see #restoreHierarchyState(android.util.SparseArray)
13321     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13322     */
13323    protected void onRestoreInstanceState(Parcelable state) {
13324        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13325        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13326            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13327                    + "received " + state.getClass().toString() + " instead. This usually happens "
13328                    + "when two views of different type have the same id in the same hierarchy. "
13329                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13330                    + "other views do not use the same id.");
13331        }
13332    }
13333
13334    /**
13335     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13336     *
13337     * @return the drawing start time in milliseconds
13338     */
13339    public long getDrawingTime() {
13340        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13341    }
13342
13343    /**
13344     * <p>Enables or disables the duplication of the parent's state into this view. When
13345     * duplication is enabled, this view gets its drawable state from its parent rather
13346     * than from its own internal properties.</p>
13347     *
13348     * <p>Note: in the current implementation, setting this property to true after the
13349     * view was added to a ViewGroup might have no effect at all. This property should
13350     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13351     *
13352     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13353     * property is enabled, an exception will be thrown.</p>
13354     *
13355     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13356     * parent, these states should not be affected by this method.</p>
13357     *
13358     * @param enabled True to enable duplication of the parent's drawable state, false
13359     *                to disable it.
13360     *
13361     * @see #getDrawableState()
13362     * @see #isDuplicateParentStateEnabled()
13363     */
13364    public void setDuplicateParentStateEnabled(boolean enabled) {
13365        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13366    }
13367
13368    /**
13369     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13370     *
13371     * @return True if this view's drawable state is duplicated from the parent,
13372     *         false otherwise
13373     *
13374     * @see #getDrawableState()
13375     * @see #setDuplicateParentStateEnabled(boolean)
13376     */
13377    public boolean isDuplicateParentStateEnabled() {
13378        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13379    }
13380
13381    /**
13382     * <p>Specifies the type of layer backing this view. The layer can be
13383     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13384     * {@link #LAYER_TYPE_HARDWARE}.</p>
13385     *
13386     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13387     * instance that controls how the layer is composed on screen. The following
13388     * properties of the paint are taken into account when composing the layer:</p>
13389     * <ul>
13390     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13391     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13392     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13393     * </ul>
13394     *
13395     * <p>If this view has an alpha value set to < 1.0 by calling
13396     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13397     * by this view's alpha value.</p>
13398     *
13399     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13400     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13401     * for more information on when and how to use layers.</p>
13402     *
13403     * @param layerType The type of layer to use with this view, must be one of
13404     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13405     *        {@link #LAYER_TYPE_HARDWARE}
13406     * @param paint The paint used to compose the layer. This argument is optional
13407     *        and can be null. It is ignored when the layer type is
13408     *        {@link #LAYER_TYPE_NONE}
13409     *
13410     * @see #getLayerType()
13411     * @see #LAYER_TYPE_NONE
13412     * @see #LAYER_TYPE_SOFTWARE
13413     * @see #LAYER_TYPE_HARDWARE
13414     * @see #setAlpha(float)
13415     *
13416     * @attr ref android.R.styleable#View_layerType
13417     */
13418    public void setLayerType(int layerType, Paint paint) {
13419        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13420            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13421                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13422        }
13423
13424        if (layerType == mLayerType) {
13425            setLayerPaint(paint);
13426            return;
13427        }
13428
13429        // Destroy any previous software drawing cache if needed
13430        switch (mLayerType) {
13431            case LAYER_TYPE_HARDWARE:
13432                destroyLayer(false);
13433                // fall through - non-accelerated views may use software layer mechanism instead
13434            case LAYER_TYPE_SOFTWARE:
13435                destroyDrawingCache();
13436                break;
13437            default:
13438                break;
13439        }
13440
13441        mLayerType = layerType;
13442        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13443        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13444        mLocalDirtyRect = layerDisabled ? null : new Rect();
13445
13446        invalidateParentCaches();
13447        invalidate(true);
13448    }
13449
13450    /**
13451     * Updates the {@link Paint} object used with the current layer (used only if the current
13452     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13453     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13454     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13455     * ensure that the view gets redrawn immediately.
13456     *
13457     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13458     * instance that controls how the layer is composed on screen. The following
13459     * properties of the paint are taken into account when composing the layer:</p>
13460     * <ul>
13461     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13462     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13463     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13464     * </ul>
13465     *
13466     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13467     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13468     *
13469     * @param paint The paint used to compose the layer. This argument is optional
13470     *        and can be null. It is ignored when the layer type is
13471     *        {@link #LAYER_TYPE_NONE}
13472     *
13473     * @see #setLayerType(int, android.graphics.Paint)
13474     */
13475    public void setLayerPaint(Paint paint) {
13476        int layerType = getLayerType();
13477        if (layerType != LAYER_TYPE_NONE) {
13478            mLayerPaint = paint == null ? new Paint() : paint;
13479            if (layerType == LAYER_TYPE_HARDWARE) {
13480                HardwareLayer layer = getHardwareLayer();
13481                if (layer != null) {
13482                    layer.setLayerPaint(mLayerPaint);
13483                }
13484                invalidateViewProperty(false, false);
13485            } else {
13486                invalidate();
13487            }
13488        }
13489    }
13490
13491    /**
13492     * Indicates whether this view has a static layer. A view with layer type
13493     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13494     * dynamic.
13495     */
13496    boolean hasStaticLayer() {
13497        return true;
13498    }
13499
13500    /**
13501     * Indicates what type of layer is currently associated with this view. By default
13502     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13503     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13504     * for more information on the different types of layers.
13505     *
13506     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13507     *         {@link #LAYER_TYPE_HARDWARE}
13508     *
13509     * @see #setLayerType(int, android.graphics.Paint)
13510     * @see #buildLayer()
13511     * @see #LAYER_TYPE_NONE
13512     * @see #LAYER_TYPE_SOFTWARE
13513     * @see #LAYER_TYPE_HARDWARE
13514     */
13515    public int getLayerType() {
13516        return mLayerType;
13517    }
13518
13519    /**
13520     * Forces this view's layer to be created and this view to be rendered
13521     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13522     * invoking this method will have no effect.
13523     *
13524     * This method can for instance be used to render a view into its layer before
13525     * starting an animation. If this view is complex, rendering into the layer
13526     * before starting the animation will avoid skipping frames.
13527     *
13528     * @throws IllegalStateException If this view is not attached to a window
13529     *
13530     * @see #setLayerType(int, android.graphics.Paint)
13531     */
13532    public void buildLayer() {
13533        if (mLayerType == LAYER_TYPE_NONE) return;
13534
13535        final AttachInfo attachInfo = mAttachInfo;
13536        if (attachInfo == null) {
13537            throw new IllegalStateException("This view must be attached to a window first");
13538        }
13539
13540        switch (mLayerType) {
13541            case LAYER_TYPE_HARDWARE:
13542                getHardwareLayer();
13543                // TODO: We need a better way to handle this case
13544                // If views have registered pre-draw listeners they need
13545                // to be notified before we build the layer. Those listeners
13546                // may however rely on other events to happen first so we
13547                // cannot just invoke them here until they don't cancel the
13548                // current frame
13549                if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13550                    attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13551                }
13552                break;
13553            case LAYER_TYPE_SOFTWARE:
13554                buildDrawingCache(true);
13555                break;
13556        }
13557    }
13558
13559    /**
13560     * <p>Returns a hardware layer that can be used to draw this view again
13561     * without executing its draw method.</p>
13562     *
13563     * @return A HardwareLayer ready to render, or null if an error occurred.
13564     */
13565    HardwareLayer getHardwareLayer() {
13566        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13567                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13568            return null;
13569        }
13570
13571        final int width = mRight - mLeft;
13572        final int height = mBottom - mTop;
13573
13574        if (width == 0 || height == 0) {
13575            return null;
13576        }
13577
13578        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13579            if (mHardwareLayer == null) {
13580                mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
13581                        width, height);
13582                mLocalDirtyRect.set(0, 0, width, height);
13583            } else if (mHardwareLayer.isValid()) {
13584                // This should not be necessary but applications that change
13585                // the parameters of their background drawable without calling
13586                // this.setBackground(Drawable) can leave the view in a bad state
13587                // (for instance isOpaque() returns true, but the background is
13588                // not opaque.)
13589                computeOpaqueFlags();
13590
13591                if (mHardwareLayer.prepare(width, height, isOpaque())) {
13592                    mLocalDirtyRect.set(0, 0, width, height);
13593                }
13594            }
13595
13596            // The layer is not valid if the underlying GPU resources cannot be allocated
13597            mHardwareLayer.flushChanges();
13598            if (!mHardwareLayer.isValid()) {
13599                return null;
13600            }
13601
13602            mHardwareLayer.setLayerPaint(mLayerPaint);
13603            RenderNode displayList = mHardwareLayer.startRecording();
13604            updateDisplayListIfDirty(displayList, true);
13605            mHardwareLayer.endRecording(mLocalDirtyRect);
13606            mLocalDirtyRect.setEmpty();
13607        }
13608
13609        return mHardwareLayer;
13610    }
13611
13612    /**
13613     * Destroys this View's hardware layer if possible.
13614     *
13615     * @return True if the layer was destroyed, false otherwise.
13616     *
13617     * @see #setLayerType(int, android.graphics.Paint)
13618     * @see #LAYER_TYPE_HARDWARE
13619     */
13620    boolean destroyLayer(boolean valid) {
13621        if (mHardwareLayer != null) {
13622            mHardwareLayer.destroy();
13623            mHardwareLayer = null;
13624
13625            invalidate(true);
13626            invalidateParentCaches();
13627            return true;
13628        }
13629        return false;
13630    }
13631
13632    /**
13633     * Destroys all hardware rendering resources. This method is invoked
13634     * when the system needs to reclaim resources. Upon execution of this
13635     * method, you should free any OpenGL resources created by the view.
13636     *
13637     * Note: you <strong>must</strong> call
13638     * <code>super.destroyHardwareResources()</code> when overriding
13639     * this method.
13640     *
13641     * @hide
13642     */
13643    protected void destroyHardwareResources() {
13644        resetDisplayList();
13645        destroyLayer(true);
13646    }
13647
13648    /**
13649     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13650     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13651     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13652     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13653     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13654     * null.</p>
13655     *
13656     * <p>Enabling the drawing cache is similar to
13657     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13658     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13659     * drawing cache has no effect on rendering because the system uses a different mechanism
13660     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13661     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13662     * for information on how to enable software and hardware layers.</p>
13663     *
13664     * <p>This API can be used to manually generate
13665     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13666     * {@link #getDrawingCache()}.</p>
13667     *
13668     * @param enabled true to enable the drawing cache, false otherwise
13669     *
13670     * @see #isDrawingCacheEnabled()
13671     * @see #getDrawingCache()
13672     * @see #buildDrawingCache()
13673     * @see #setLayerType(int, android.graphics.Paint)
13674     */
13675    public void setDrawingCacheEnabled(boolean enabled) {
13676        mCachingFailed = false;
13677        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13678    }
13679
13680    /**
13681     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13682     *
13683     * @return true if the drawing cache is enabled
13684     *
13685     * @see #setDrawingCacheEnabled(boolean)
13686     * @see #getDrawingCache()
13687     */
13688    @ViewDebug.ExportedProperty(category = "drawing")
13689    public boolean isDrawingCacheEnabled() {
13690        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13691    }
13692
13693    /**
13694     * Debugging utility which recursively outputs the dirty state of a view and its
13695     * descendants.
13696     *
13697     * @hide
13698     */
13699    @SuppressWarnings({"UnusedDeclaration"})
13700    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13701        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13702                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13703                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13704                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13705        if (clear) {
13706            mPrivateFlags &= clearMask;
13707        }
13708        if (this instanceof ViewGroup) {
13709            ViewGroup parent = (ViewGroup) this;
13710            final int count = parent.getChildCount();
13711            for (int i = 0; i < count; i++) {
13712                final View child = parent.getChildAt(i);
13713                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13714            }
13715        }
13716    }
13717
13718    /**
13719     * This method is used by ViewGroup to cause its children to restore or recreate their
13720     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13721     * to recreate its own display list, which would happen if it went through the normal
13722     * draw/dispatchDraw mechanisms.
13723     *
13724     * @hide
13725     */
13726    protected void dispatchGetDisplayList() {}
13727
13728    /**
13729     * A view that is not attached or hardware accelerated cannot create a display list.
13730     * This method checks these conditions and returns the appropriate result.
13731     *
13732     * @return true if view has the ability to create a display list, false otherwise.
13733     *
13734     * @hide
13735     */
13736    public boolean canHaveDisplayList() {
13737        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13738    }
13739
13740    /**
13741     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13742     * Otherwise, the same display list will be returned (after having been rendered into
13743     * along the way, depending on the invalidation state of the view).
13744     *
13745     * @param renderNode The previous version of this displayList, could be null.
13746     * @param isLayer Whether the requester of the display list is a layer. If so,
13747     * the view will avoid creating a layer inside the resulting display list.
13748     * @return A new or reused DisplayList object.
13749     */
13750    private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) {
13751        if (renderNode == null) {
13752            throw new IllegalArgumentException("RenderNode must not be null");
13753        }
13754        if (!canHaveDisplayList()) {
13755            // can't populate RenderNode, don't try
13756            return;
13757        }
13758
13759        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13760                || !renderNode.isValid()
13761                || (!isLayer && mRecreateDisplayList)) {
13762            // Don't need to recreate the display list, just need to tell our
13763            // children to restore/recreate theirs
13764            if (renderNode.isValid()
13765                    && !isLayer
13766                    && !mRecreateDisplayList) {
13767                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13768                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13769                dispatchGetDisplayList();
13770
13771                return; // no work needed
13772            }
13773
13774            if (!isLayer) {
13775                // If we got here, we're recreating it. Mark it as such to ensure that
13776                // we copy in child display lists into ours in drawChild()
13777                mRecreateDisplayList = true;
13778            }
13779
13780            boolean caching = false;
13781            int width = mRight - mLeft;
13782            int height = mBottom - mTop;
13783            int layerType = getLayerType();
13784
13785            final HardwareCanvas canvas = renderNode.start(width, height);
13786
13787            try {
13788                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13789                    if (layerType == LAYER_TYPE_HARDWARE) {
13790                        final HardwareLayer layer = getHardwareLayer();
13791                        if (layer != null && layer.isValid()) {
13792                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13793                        } else {
13794                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13795                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13796                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13797                        }
13798                        caching = true;
13799                    } else {
13800                        buildDrawingCache(true);
13801                        Bitmap cache = getDrawingCache(true);
13802                        if (cache != null) {
13803                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13804                            caching = true;
13805                        }
13806                    }
13807                } else {
13808
13809                    computeScroll();
13810
13811                    canvas.translate(-mScrollX, -mScrollY);
13812                    if (!isLayer) {
13813                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13814                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13815                    }
13816
13817                    // Fast path for layouts with no backgrounds
13818                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13819                        dispatchDraw(canvas);
13820                        if (mOverlay != null && !mOverlay.isEmpty()) {
13821                            mOverlay.getOverlayView().draw(canvas);
13822                        }
13823                    } else {
13824                        draw(canvas);
13825                    }
13826                }
13827            } finally {
13828                renderNode.end(canvas);
13829                renderNode.setCaching(caching);
13830                if (isLayer) {
13831                    renderNode.setLeftTopRightBottom(0, 0, width, height);
13832                } else {
13833                    setDisplayListProperties(renderNode);
13834                }
13835            }
13836        } else if (!isLayer) {
13837            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13838            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13839        }
13840    }
13841
13842    /**
13843     * Returns a RenderNode with View draw content recorded, which can be
13844     * used to draw this view again without executing its draw method.
13845     *
13846     * @return A RenderNode ready to replay, or null if caching is not enabled.
13847     *
13848     * @hide
13849     */
13850    public RenderNode getDisplayList() {
13851        updateDisplayListIfDirty(mRenderNode, false);
13852        return mRenderNode;
13853    }
13854
13855    private void resetDisplayList() {
13856        if (mRenderNode.isValid()) {
13857            mRenderNode.destroyDisplayListData();
13858        }
13859
13860        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
13861            mBackgroundDisplayList.destroyDisplayListData();
13862        }
13863    }
13864
13865    /**
13866     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13867     *
13868     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13869     *
13870     * @see #getDrawingCache(boolean)
13871     */
13872    public Bitmap getDrawingCache() {
13873        return getDrawingCache(false);
13874    }
13875
13876    /**
13877     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13878     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13879     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13880     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13881     * request the drawing cache by calling this method and draw it on screen if the
13882     * returned bitmap is not null.</p>
13883     *
13884     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13885     * this method will create a bitmap of the same size as this view. Because this bitmap
13886     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13887     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13888     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13889     * size than the view. This implies that your application must be able to handle this
13890     * size.</p>
13891     *
13892     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13893     *        the current density of the screen when the application is in compatibility
13894     *        mode.
13895     *
13896     * @return A bitmap representing this view or null if cache is disabled.
13897     *
13898     * @see #setDrawingCacheEnabled(boolean)
13899     * @see #isDrawingCacheEnabled()
13900     * @see #buildDrawingCache(boolean)
13901     * @see #destroyDrawingCache()
13902     */
13903    public Bitmap getDrawingCache(boolean autoScale) {
13904        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13905            return null;
13906        }
13907        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13908            buildDrawingCache(autoScale);
13909        }
13910        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13911    }
13912
13913    /**
13914     * <p>Frees the resources used by the drawing cache. If you call
13915     * {@link #buildDrawingCache()} manually without calling
13916     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13917     * should cleanup the cache with this method afterwards.</p>
13918     *
13919     * @see #setDrawingCacheEnabled(boolean)
13920     * @see #buildDrawingCache()
13921     * @see #getDrawingCache()
13922     */
13923    public void destroyDrawingCache() {
13924        if (mDrawingCache != null) {
13925            mDrawingCache.recycle();
13926            mDrawingCache = null;
13927        }
13928        if (mUnscaledDrawingCache != null) {
13929            mUnscaledDrawingCache.recycle();
13930            mUnscaledDrawingCache = null;
13931        }
13932    }
13933
13934    /**
13935     * Setting a solid background color for the drawing cache's bitmaps will improve
13936     * performance and memory usage. Note, though that this should only be used if this
13937     * view will always be drawn on top of a solid color.
13938     *
13939     * @param color The background color to use for the drawing cache's bitmap
13940     *
13941     * @see #setDrawingCacheEnabled(boolean)
13942     * @see #buildDrawingCache()
13943     * @see #getDrawingCache()
13944     */
13945    public void setDrawingCacheBackgroundColor(int color) {
13946        if (color != mDrawingCacheBackgroundColor) {
13947            mDrawingCacheBackgroundColor = color;
13948            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13949        }
13950    }
13951
13952    /**
13953     * @see #setDrawingCacheBackgroundColor(int)
13954     *
13955     * @return The background color to used for the drawing cache's bitmap
13956     */
13957    public int getDrawingCacheBackgroundColor() {
13958        return mDrawingCacheBackgroundColor;
13959    }
13960
13961    /**
13962     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13963     *
13964     * @see #buildDrawingCache(boolean)
13965     */
13966    public void buildDrawingCache() {
13967        buildDrawingCache(false);
13968    }
13969
13970    /**
13971     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13972     *
13973     * <p>If you call {@link #buildDrawingCache()} manually without calling
13974     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13975     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13976     *
13977     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13978     * this method will create a bitmap of the same size as this view. Because this bitmap
13979     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13980     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13981     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13982     * size than the view. This implies that your application must be able to handle this
13983     * size.</p>
13984     *
13985     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13986     * you do not need the drawing cache bitmap, calling this method will increase memory
13987     * usage and cause the view to be rendered in software once, thus negatively impacting
13988     * performance.</p>
13989     *
13990     * @see #getDrawingCache()
13991     * @see #destroyDrawingCache()
13992     */
13993    public void buildDrawingCache(boolean autoScale) {
13994        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13995                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13996            mCachingFailed = false;
13997
13998            int width = mRight - mLeft;
13999            int height = mBottom - mTop;
14000
14001            final AttachInfo attachInfo = mAttachInfo;
14002            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14003
14004            if (autoScale && scalingRequired) {
14005                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14006                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14007            }
14008
14009            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14010            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14011            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14012
14013            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14014            final long drawingCacheSize =
14015                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14016            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14017                if (width > 0 && height > 0) {
14018                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14019                            + projectedBitmapSize + " bytes, only "
14020                            + drawingCacheSize + " available");
14021                }
14022                destroyDrawingCache();
14023                mCachingFailed = true;
14024                return;
14025            }
14026
14027            boolean clear = true;
14028            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14029
14030            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14031                Bitmap.Config quality;
14032                if (!opaque) {
14033                    // Never pick ARGB_4444 because it looks awful
14034                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14035                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14036                        case DRAWING_CACHE_QUALITY_AUTO:
14037                        case DRAWING_CACHE_QUALITY_LOW:
14038                        case DRAWING_CACHE_QUALITY_HIGH:
14039                        default:
14040                            quality = Bitmap.Config.ARGB_8888;
14041                            break;
14042                    }
14043                } else {
14044                    // Optimization for translucent windows
14045                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14046                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14047                }
14048
14049                // Try to cleanup memory
14050                if (bitmap != null) bitmap.recycle();
14051
14052                try {
14053                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14054                            width, height, quality);
14055                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14056                    if (autoScale) {
14057                        mDrawingCache = bitmap;
14058                    } else {
14059                        mUnscaledDrawingCache = bitmap;
14060                    }
14061                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14062                } catch (OutOfMemoryError e) {
14063                    // If there is not enough memory to create the bitmap cache, just
14064                    // ignore the issue as bitmap caches are not required to draw the
14065                    // view hierarchy
14066                    if (autoScale) {
14067                        mDrawingCache = null;
14068                    } else {
14069                        mUnscaledDrawingCache = null;
14070                    }
14071                    mCachingFailed = true;
14072                    return;
14073                }
14074
14075                clear = drawingCacheBackgroundColor != 0;
14076            }
14077
14078            Canvas canvas;
14079            if (attachInfo != null) {
14080                canvas = attachInfo.mCanvas;
14081                if (canvas == null) {
14082                    canvas = new Canvas();
14083                }
14084                canvas.setBitmap(bitmap);
14085                // Temporarily clobber the cached Canvas in case one of our children
14086                // is also using a drawing cache. Without this, the children would
14087                // steal the canvas by attaching their own bitmap to it and bad, bad
14088                // thing would happen (invisible views, corrupted drawings, etc.)
14089                attachInfo.mCanvas = null;
14090            } else {
14091                // This case should hopefully never or seldom happen
14092                canvas = new Canvas(bitmap);
14093            }
14094
14095            if (clear) {
14096                bitmap.eraseColor(drawingCacheBackgroundColor);
14097            }
14098
14099            computeScroll();
14100            final int restoreCount = canvas.save();
14101
14102            if (autoScale && scalingRequired) {
14103                final float scale = attachInfo.mApplicationScale;
14104                canvas.scale(scale, scale);
14105            }
14106
14107            canvas.translate(-mScrollX, -mScrollY);
14108
14109            mPrivateFlags |= PFLAG_DRAWN;
14110            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14111                    mLayerType != LAYER_TYPE_NONE) {
14112                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14113            }
14114
14115            // Fast path for layouts with no backgrounds
14116            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14117                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14118                dispatchDraw(canvas);
14119                if (mOverlay != null && !mOverlay.isEmpty()) {
14120                    mOverlay.getOverlayView().draw(canvas);
14121                }
14122            } else {
14123                draw(canvas);
14124            }
14125
14126            canvas.restoreToCount(restoreCount);
14127            canvas.setBitmap(null);
14128
14129            if (attachInfo != null) {
14130                // Restore the cached Canvas for our siblings
14131                attachInfo.mCanvas = canvas;
14132            }
14133        }
14134    }
14135
14136    /**
14137     * Create a snapshot of the view into a bitmap.  We should probably make
14138     * some form of this public, but should think about the API.
14139     */
14140    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14141        int width = mRight - mLeft;
14142        int height = mBottom - mTop;
14143
14144        final AttachInfo attachInfo = mAttachInfo;
14145        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14146        width = (int) ((width * scale) + 0.5f);
14147        height = (int) ((height * scale) + 0.5f);
14148
14149        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14150                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14151        if (bitmap == null) {
14152            throw new OutOfMemoryError();
14153        }
14154
14155        Resources resources = getResources();
14156        if (resources != null) {
14157            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14158        }
14159
14160        Canvas canvas;
14161        if (attachInfo != null) {
14162            canvas = attachInfo.mCanvas;
14163            if (canvas == null) {
14164                canvas = new Canvas();
14165            }
14166            canvas.setBitmap(bitmap);
14167            // Temporarily clobber the cached Canvas in case one of our children
14168            // is also using a drawing cache. Without this, the children would
14169            // steal the canvas by attaching their own bitmap to it and bad, bad
14170            // things would happen (invisible views, corrupted drawings, etc.)
14171            attachInfo.mCanvas = null;
14172        } else {
14173            // This case should hopefully never or seldom happen
14174            canvas = new Canvas(bitmap);
14175        }
14176
14177        if ((backgroundColor & 0xff000000) != 0) {
14178            bitmap.eraseColor(backgroundColor);
14179        }
14180
14181        computeScroll();
14182        final int restoreCount = canvas.save();
14183        canvas.scale(scale, scale);
14184        canvas.translate(-mScrollX, -mScrollY);
14185
14186        // Temporarily remove the dirty mask
14187        int flags = mPrivateFlags;
14188        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14189
14190        // Fast path for layouts with no backgrounds
14191        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14192            dispatchDraw(canvas);
14193            if (mOverlay != null && !mOverlay.isEmpty()) {
14194                mOverlay.getOverlayView().draw(canvas);
14195            }
14196        } else {
14197            draw(canvas);
14198        }
14199
14200        mPrivateFlags = flags;
14201
14202        canvas.restoreToCount(restoreCount);
14203        canvas.setBitmap(null);
14204
14205        if (attachInfo != null) {
14206            // Restore the cached Canvas for our siblings
14207            attachInfo.mCanvas = canvas;
14208        }
14209
14210        return bitmap;
14211    }
14212
14213    /**
14214     * Indicates whether this View is currently in edit mode. A View is usually
14215     * in edit mode when displayed within a developer tool. For instance, if
14216     * this View is being drawn by a visual user interface builder, this method
14217     * should return true.
14218     *
14219     * Subclasses should check the return value of this method to provide
14220     * different behaviors if their normal behavior might interfere with the
14221     * host environment. For instance: the class spawns a thread in its
14222     * constructor, the drawing code relies on device-specific features, etc.
14223     *
14224     * This method is usually checked in the drawing code of custom widgets.
14225     *
14226     * @return True if this View is in edit mode, false otherwise.
14227     */
14228    public boolean isInEditMode() {
14229        return false;
14230    }
14231
14232    /**
14233     * If the View draws content inside its padding and enables fading edges,
14234     * it needs to support padding offsets. Padding offsets are added to the
14235     * fading edges to extend the length of the fade so that it covers pixels
14236     * drawn inside the padding.
14237     *
14238     * Subclasses of this class should override this method if they need
14239     * to draw content inside the padding.
14240     *
14241     * @return True if padding offset must be applied, false otherwise.
14242     *
14243     * @see #getLeftPaddingOffset()
14244     * @see #getRightPaddingOffset()
14245     * @see #getTopPaddingOffset()
14246     * @see #getBottomPaddingOffset()
14247     *
14248     * @since CURRENT
14249     */
14250    protected boolean isPaddingOffsetRequired() {
14251        return false;
14252    }
14253
14254    /**
14255     * Amount by which to extend the left fading region. Called only when
14256     * {@link #isPaddingOffsetRequired()} returns true.
14257     *
14258     * @return The left padding offset in pixels.
14259     *
14260     * @see #isPaddingOffsetRequired()
14261     *
14262     * @since CURRENT
14263     */
14264    protected int getLeftPaddingOffset() {
14265        return 0;
14266    }
14267
14268    /**
14269     * Amount by which to extend the right fading region. Called only when
14270     * {@link #isPaddingOffsetRequired()} returns true.
14271     *
14272     * @return The right padding offset in pixels.
14273     *
14274     * @see #isPaddingOffsetRequired()
14275     *
14276     * @since CURRENT
14277     */
14278    protected int getRightPaddingOffset() {
14279        return 0;
14280    }
14281
14282    /**
14283     * Amount by which to extend the top fading region. Called only when
14284     * {@link #isPaddingOffsetRequired()} returns true.
14285     *
14286     * @return The top padding offset in pixels.
14287     *
14288     * @see #isPaddingOffsetRequired()
14289     *
14290     * @since CURRENT
14291     */
14292    protected int getTopPaddingOffset() {
14293        return 0;
14294    }
14295
14296    /**
14297     * Amount by which to extend the bottom fading region. Called only when
14298     * {@link #isPaddingOffsetRequired()} returns true.
14299     *
14300     * @return The bottom padding offset in pixels.
14301     *
14302     * @see #isPaddingOffsetRequired()
14303     *
14304     * @since CURRENT
14305     */
14306    protected int getBottomPaddingOffset() {
14307        return 0;
14308    }
14309
14310    /**
14311     * @hide
14312     * @param offsetRequired
14313     */
14314    protected int getFadeTop(boolean offsetRequired) {
14315        int top = mPaddingTop;
14316        if (offsetRequired) top += getTopPaddingOffset();
14317        return top;
14318    }
14319
14320    /**
14321     * @hide
14322     * @param offsetRequired
14323     */
14324    protected int getFadeHeight(boolean offsetRequired) {
14325        int padding = mPaddingTop;
14326        if (offsetRequired) padding += getTopPaddingOffset();
14327        return mBottom - mTop - mPaddingBottom - padding;
14328    }
14329
14330    /**
14331     * <p>Indicates whether this view is attached to a hardware accelerated
14332     * window or not.</p>
14333     *
14334     * <p>Even if this method returns true, it does not mean that every call
14335     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14336     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14337     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14338     * window is hardware accelerated,
14339     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14340     * return false, and this method will return true.</p>
14341     *
14342     * @return True if the view is attached to a window and the window is
14343     *         hardware accelerated; false in any other case.
14344     */
14345    public boolean isHardwareAccelerated() {
14346        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14347    }
14348
14349    /**
14350     * Sets a rectangular area on this view to which the view will be clipped
14351     * when it is drawn. Setting the value to null will remove the clip bounds
14352     * and the view will draw normally, using its full bounds.
14353     *
14354     * @param clipBounds The rectangular area, in the local coordinates of
14355     * this view, to which future drawing operations will be clipped.
14356     */
14357    public void setClipBounds(Rect clipBounds) {
14358        if (clipBounds != null) {
14359            if (clipBounds.equals(mClipBounds)) {
14360                return;
14361            }
14362            if (mClipBounds == null) {
14363                invalidate();
14364                mClipBounds = new Rect(clipBounds);
14365            } else {
14366                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14367                        Math.min(mClipBounds.top, clipBounds.top),
14368                        Math.max(mClipBounds.right, clipBounds.right),
14369                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14370                mClipBounds.set(clipBounds);
14371            }
14372        } else {
14373            if (mClipBounds != null) {
14374                invalidate();
14375                mClipBounds = null;
14376            }
14377        }
14378    }
14379
14380    /**
14381     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14382     *
14383     * @return A copy of the current clip bounds if clip bounds are set,
14384     * otherwise null.
14385     */
14386    public Rect getClipBounds() {
14387        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14388    }
14389
14390    /**
14391     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14392     * case of an active Animation being run on the view.
14393     */
14394    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14395            Animation a, boolean scalingRequired) {
14396        Transformation invalidationTransform;
14397        final int flags = parent.mGroupFlags;
14398        final boolean initialized = a.isInitialized();
14399        if (!initialized) {
14400            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14401            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14402            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14403            onAnimationStart();
14404        }
14405
14406        final Transformation t = parent.getChildTransformation();
14407        boolean more = a.getTransformation(drawingTime, t, 1f);
14408        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14409            if (parent.mInvalidationTransformation == null) {
14410                parent.mInvalidationTransformation = new Transformation();
14411            }
14412            invalidationTransform = parent.mInvalidationTransformation;
14413            a.getTransformation(drawingTime, invalidationTransform, 1f);
14414        } else {
14415            invalidationTransform = t;
14416        }
14417
14418        if (more) {
14419            if (!a.willChangeBounds()) {
14420                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14421                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14422                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14423                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14424                    // The child need to draw an animation, potentially offscreen, so
14425                    // make sure we do not cancel invalidate requests
14426                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14427                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14428                }
14429            } else {
14430                if (parent.mInvalidateRegion == null) {
14431                    parent.mInvalidateRegion = new RectF();
14432                }
14433                final RectF region = parent.mInvalidateRegion;
14434                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14435                        invalidationTransform);
14436
14437                // The child need to draw an animation, potentially offscreen, so
14438                // make sure we do not cancel invalidate requests
14439                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14440
14441                final int left = mLeft + (int) region.left;
14442                final int top = mTop + (int) region.top;
14443                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14444                        top + (int) (region.height() + .5f));
14445            }
14446        }
14447        return more;
14448    }
14449
14450    /**
14451     * This method is called by getDisplayList() when a display list is recorded for a View.
14452     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14453     */
14454    void setDisplayListProperties(RenderNode renderNode) {
14455        if (renderNode != null) {
14456            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14457            if (mParent instanceof ViewGroup) {
14458                renderNode.setClipToBounds(
14459                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14460            }
14461            float alpha = 1;
14462            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14463                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14464                ViewGroup parentVG = (ViewGroup) mParent;
14465                final Transformation t = parentVG.getChildTransformation();
14466                if (parentVG.getChildStaticTransformation(this, t)) {
14467                    final int transformType = t.getTransformationType();
14468                    if (transformType != Transformation.TYPE_IDENTITY) {
14469                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14470                            alpha = t.getAlpha();
14471                        }
14472                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14473                            renderNode.setStaticMatrix(t.getMatrix());
14474                        }
14475                    }
14476                }
14477            }
14478            if (mTransformationInfo != null) {
14479                alpha *= getFinalAlpha();
14480                if (alpha < 1) {
14481                    final int multipliedAlpha = (int) (255 * alpha);
14482                    if (onSetAlpha(multipliedAlpha)) {
14483                        alpha = 1;
14484                    }
14485                }
14486                renderNode.setAlpha(alpha);
14487            } else if (alpha < 1) {
14488                renderNode.setAlpha(alpha);
14489            }
14490        }
14491    }
14492
14493    /**
14494     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14495     * This draw() method is an implementation detail and is not intended to be overridden or
14496     * to be called from anywhere else other than ViewGroup.drawChild().
14497     */
14498    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14499        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14500        boolean more = false;
14501        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14502        final int flags = parent.mGroupFlags;
14503
14504        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14505            parent.getChildTransformation().clear();
14506            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14507        }
14508
14509        Transformation transformToApply = null;
14510        boolean concatMatrix = false;
14511
14512        boolean scalingRequired = false;
14513        boolean caching;
14514        int layerType = getLayerType();
14515
14516        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14517        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14518                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14519            caching = true;
14520            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14521            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14522        } else {
14523            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14524        }
14525
14526        final Animation a = getAnimation();
14527        if (a != null) {
14528            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14529            concatMatrix = a.willChangeTransformationMatrix();
14530            if (concatMatrix) {
14531                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14532            }
14533            transformToApply = parent.getChildTransformation();
14534        } else {
14535            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14536                // No longer animating: clear out old animation matrix
14537                mRenderNode.setAnimationMatrix(null);
14538                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14539            }
14540            if (!useDisplayListProperties &&
14541                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14542                final Transformation t = parent.getChildTransformation();
14543                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14544                if (hasTransform) {
14545                    final int transformType = t.getTransformationType();
14546                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14547                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14548                }
14549            }
14550        }
14551
14552        concatMatrix |= !childHasIdentityMatrix;
14553
14554        // Sets the flag as early as possible to allow draw() implementations
14555        // to call invalidate() successfully when doing animations
14556        mPrivateFlags |= PFLAG_DRAWN;
14557
14558        if (!concatMatrix &&
14559                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14560                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14561                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14562                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14563            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14564            return more;
14565        }
14566        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14567
14568        if (hardwareAccelerated) {
14569            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14570            // retain the flag's value temporarily in the mRecreateDisplayList flag
14571            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14572            mPrivateFlags &= ~PFLAG_INVALIDATED;
14573        }
14574
14575        RenderNode displayList = null;
14576        Bitmap cache = null;
14577        boolean hasDisplayList = false;
14578        if (caching) {
14579            if (!hardwareAccelerated) {
14580                if (layerType != LAYER_TYPE_NONE) {
14581                    layerType = LAYER_TYPE_SOFTWARE;
14582                    buildDrawingCache(true);
14583                }
14584                cache = getDrawingCache(true);
14585            } else {
14586                switch (layerType) {
14587                    case LAYER_TYPE_SOFTWARE:
14588                        if (useDisplayListProperties) {
14589                            hasDisplayList = canHaveDisplayList();
14590                        } else {
14591                            buildDrawingCache(true);
14592                            cache = getDrawingCache(true);
14593                        }
14594                        break;
14595                    case LAYER_TYPE_HARDWARE:
14596                        if (useDisplayListProperties) {
14597                            hasDisplayList = canHaveDisplayList();
14598                        }
14599                        break;
14600                    case LAYER_TYPE_NONE:
14601                        // Delay getting the display list until animation-driven alpha values are
14602                        // set up and possibly passed on to the view
14603                        hasDisplayList = canHaveDisplayList();
14604                        break;
14605                }
14606            }
14607        }
14608        useDisplayListProperties &= hasDisplayList;
14609        if (useDisplayListProperties) {
14610            displayList = getDisplayList();
14611            if (!displayList.isValid()) {
14612                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14613                // to getDisplayList(), the display list will be marked invalid and we should not
14614                // try to use it again.
14615                displayList = null;
14616                hasDisplayList = false;
14617                useDisplayListProperties = false;
14618            }
14619        }
14620
14621        int sx = 0;
14622        int sy = 0;
14623        if (!hasDisplayList) {
14624            computeScroll();
14625            sx = mScrollX;
14626            sy = mScrollY;
14627        }
14628
14629        final boolean hasNoCache = cache == null || hasDisplayList;
14630        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14631                layerType != LAYER_TYPE_HARDWARE;
14632
14633        int restoreTo = -1;
14634        if (!useDisplayListProperties || transformToApply != null) {
14635            restoreTo = canvas.save();
14636        }
14637        if (offsetForScroll) {
14638            canvas.translate(mLeft - sx, mTop - sy);
14639        } else {
14640            if (!useDisplayListProperties) {
14641                canvas.translate(mLeft, mTop);
14642            }
14643            if (scalingRequired) {
14644                if (useDisplayListProperties) {
14645                    // TODO: Might not need this if we put everything inside the DL
14646                    restoreTo = canvas.save();
14647                }
14648                // mAttachInfo cannot be null, otherwise scalingRequired == false
14649                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14650                canvas.scale(scale, scale);
14651            }
14652        }
14653
14654        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14655        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14656                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14657            if (transformToApply != null || !childHasIdentityMatrix) {
14658                int transX = 0;
14659                int transY = 0;
14660
14661                if (offsetForScroll) {
14662                    transX = -sx;
14663                    transY = -sy;
14664                }
14665
14666                if (transformToApply != null) {
14667                    if (concatMatrix) {
14668                        if (useDisplayListProperties) {
14669                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14670                        } else {
14671                            // Undo the scroll translation, apply the transformation matrix,
14672                            // then redo the scroll translate to get the correct result.
14673                            canvas.translate(-transX, -transY);
14674                            canvas.concat(transformToApply.getMatrix());
14675                            canvas.translate(transX, transY);
14676                        }
14677                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14678                    }
14679
14680                    float transformAlpha = transformToApply.getAlpha();
14681                    if (transformAlpha < 1) {
14682                        alpha *= transformAlpha;
14683                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14684                    }
14685                }
14686
14687                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14688                    canvas.translate(-transX, -transY);
14689                    canvas.concat(getMatrix());
14690                    canvas.translate(transX, transY);
14691                }
14692            }
14693
14694            // Deal with alpha if it is or used to be <1
14695            if (alpha < 1 ||
14696                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14697                if (alpha < 1) {
14698                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14699                } else {
14700                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14701                }
14702                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14703                if (hasNoCache) {
14704                    final int multipliedAlpha = (int) (255 * alpha);
14705                    if (!onSetAlpha(multipliedAlpha)) {
14706                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14707                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14708                                layerType != LAYER_TYPE_NONE) {
14709                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14710                        }
14711                        if (useDisplayListProperties) {
14712                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14713                        } else  if (layerType == LAYER_TYPE_NONE) {
14714                            final int scrollX = hasDisplayList ? 0 : sx;
14715                            final int scrollY = hasDisplayList ? 0 : sy;
14716                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14717                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14718                        }
14719                    } else {
14720                        // Alpha is handled by the child directly, clobber the layer's alpha
14721                        mPrivateFlags |= PFLAG_ALPHA_SET;
14722                    }
14723                }
14724            }
14725        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14726            onSetAlpha(255);
14727            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14728        }
14729
14730        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14731                !useDisplayListProperties && cache == null) {
14732            if (offsetForScroll) {
14733                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14734            } else {
14735                if (!scalingRequired || cache == null) {
14736                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14737                } else {
14738                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14739                }
14740            }
14741        }
14742
14743        if (!useDisplayListProperties && hasDisplayList) {
14744            displayList = getDisplayList();
14745            if (!displayList.isValid()) {
14746                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14747                // to getDisplayList(), the display list will be marked invalid and we should not
14748                // try to use it again.
14749                displayList = null;
14750                hasDisplayList = false;
14751            }
14752        }
14753
14754        if (hasNoCache) {
14755            boolean layerRendered = false;
14756            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14757                final HardwareLayer layer = getHardwareLayer();
14758                if (layer != null && layer.isValid()) {
14759                    mLayerPaint.setAlpha((int) (alpha * 255));
14760                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14761                    layerRendered = true;
14762                } else {
14763                    final int scrollX = hasDisplayList ? 0 : sx;
14764                    final int scrollY = hasDisplayList ? 0 : sy;
14765                    canvas.saveLayer(scrollX, scrollY,
14766                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14767                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14768                }
14769            }
14770
14771            if (!layerRendered) {
14772                if (!hasDisplayList) {
14773                    // Fast path for layouts with no backgrounds
14774                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14775                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14776                        dispatchDraw(canvas);
14777                    } else {
14778                        draw(canvas);
14779                    }
14780                } else {
14781                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14782                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14783                }
14784            }
14785        } else if (cache != null) {
14786            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14787            Paint cachePaint;
14788
14789            if (layerType == LAYER_TYPE_NONE) {
14790                cachePaint = parent.mCachePaint;
14791                if (cachePaint == null) {
14792                    cachePaint = new Paint();
14793                    cachePaint.setDither(false);
14794                    parent.mCachePaint = cachePaint;
14795                }
14796                if (alpha < 1) {
14797                    cachePaint.setAlpha((int) (alpha * 255));
14798                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14799                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14800                    cachePaint.setAlpha(255);
14801                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14802                }
14803            } else {
14804                cachePaint = mLayerPaint;
14805                cachePaint.setAlpha((int) (alpha * 255));
14806            }
14807            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14808        }
14809
14810        if (restoreTo >= 0) {
14811            canvas.restoreToCount(restoreTo);
14812        }
14813
14814        if (a != null && !more) {
14815            if (!hardwareAccelerated && !a.getFillAfter()) {
14816                onSetAlpha(255);
14817            }
14818            parent.finishAnimatingView(this, a);
14819        }
14820
14821        if (more && hardwareAccelerated) {
14822            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14823                // alpha animations should cause the child to recreate its display list
14824                invalidate(true);
14825            }
14826        }
14827
14828        mRecreateDisplayList = false;
14829
14830        return more;
14831    }
14832
14833    /**
14834     * Manually render this view (and all of its children) to the given Canvas.
14835     * The view must have already done a full layout before this function is
14836     * called.  When implementing a view, implement
14837     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14838     * If you do need to override this method, call the superclass version.
14839     *
14840     * @param canvas The Canvas to which the View is rendered.
14841     */
14842    public void draw(Canvas canvas) {
14843        if (mClipBounds != null) {
14844            canvas.clipRect(mClipBounds);
14845        }
14846        final int privateFlags = mPrivateFlags;
14847        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14848                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14849        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14850
14851        /*
14852         * Draw traversal performs several drawing steps which must be executed
14853         * in the appropriate order:
14854         *
14855         *      1. Draw the background
14856         *      2. If necessary, save the canvas' layers to prepare for fading
14857         *      3. Draw view's content
14858         *      4. Draw children
14859         *      5. If necessary, draw the fading edges and restore layers
14860         *      6. Draw decorations (scrollbars for instance)
14861         */
14862
14863        // Step 1, draw the background, if needed
14864        int saveCount;
14865
14866        if (!dirtyOpaque) {
14867            drawBackground(canvas);
14868        }
14869
14870        // skip step 2 & 5 if possible (common case)
14871        final int viewFlags = mViewFlags;
14872        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14873        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14874        if (!verticalEdges && !horizontalEdges) {
14875            // Step 3, draw the content
14876            if (!dirtyOpaque) onDraw(canvas);
14877
14878            // Step 4, draw the children
14879            dispatchDraw(canvas);
14880
14881            // Step 6, draw decorations (scrollbars)
14882            onDrawScrollBars(canvas);
14883
14884            if (mOverlay != null && !mOverlay.isEmpty()) {
14885                mOverlay.getOverlayView().dispatchDraw(canvas);
14886            }
14887
14888            // we're done...
14889            return;
14890        }
14891
14892        /*
14893         * Here we do the full fledged routine...
14894         * (this is an uncommon case where speed matters less,
14895         * this is why we repeat some of the tests that have been
14896         * done above)
14897         */
14898
14899        boolean drawTop = false;
14900        boolean drawBottom = false;
14901        boolean drawLeft = false;
14902        boolean drawRight = false;
14903
14904        float topFadeStrength = 0.0f;
14905        float bottomFadeStrength = 0.0f;
14906        float leftFadeStrength = 0.0f;
14907        float rightFadeStrength = 0.0f;
14908
14909        // Step 2, save the canvas' layers
14910        int paddingLeft = mPaddingLeft;
14911
14912        final boolean offsetRequired = isPaddingOffsetRequired();
14913        if (offsetRequired) {
14914            paddingLeft += getLeftPaddingOffset();
14915        }
14916
14917        int left = mScrollX + paddingLeft;
14918        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14919        int top = mScrollY + getFadeTop(offsetRequired);
14920        int bottom = top + getFadeHeight(offsetRequired);
14921
14922        if (offsetRequired) {
14923            right += getRightPaddingOffset();
14924            bottom += getBottomPaddingOffset();
14925        }
14926
14927        final ScrollabilityCache scrollabilityCache = mScrollCache;
14928        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14929        int length = (int) fadeHeight;
14930
14931        // clip the fade length if top and bottom fades overlap
14932        // overlapping fades produce odd-looking artifacts
14933        if (verticalEdges && (top + length > bottom - length)) {
14934            length = (bottom - top) / 2;
14935        }
14936
14937        // also clip horizontal fades if necessary
14938        if (horizontalEdges && (left + length > right - length)) {
14939            length = (right - left) / 2;
14940        }
14941
14942        if (verticalEdges) {
14943            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14944            drawTop = topFadeStrength * fadeHeight > 1.0f;
14945            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14946            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14947        }
14948
14949        if (horizontalEdges) {
14950            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14951            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14952            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14953            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14954        }
14955
14956        saveCount = canvas.getSaveCount();
14957
14958        int solidColor = getSolidColor();
14959        if (solidColor == 0) {
14960            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14961
14962            if (drawTop) {
14963                canvas.saveLayer(left, top, right, top + length, null, flags);
14964            }
14965
14966            if (drawBottom) {
14967                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14968            }
14969
14970            if (drawLeft) {
14971                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14972            }
14973
14974            if (drawRight) {
14975                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14976            }
14977        } else {
14978            scrollabilityCache.setFadeColor(solidColor);
14979        }
14980
14981        // Step 3, draw the content
14982        if (!dirtyOpaque) onDraw(canvas);
14983
14984        // Step 4, draw the children
14985        dispatchDraw(canvas);
14986
14987        // Step 5, draw the fade effect and restore layers
14988        final Paint p = scrollabilityCache.paint;
14989        final Matrix matrix = scrollabilityCache.matrix;
14990        final Shader fade = scrollabilityCache.shader;
14991
14992        if (drawTop) {
14993            matrix.setScale(1, fadeHeight * topFadeStrength);
14994            matrix.postTranslate(left, top);
14995            fade.setLocalMatrix(matrix);
14996            canvas.drawRect(left, top, right, top + length, p);
14997        }
14998
14999        if (drawBottom) {
15000            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15001            matrix.postRotate(180);
15002            matrix.postTranslate(left, bottom);
15003            fade.setLocalMatrix(matrix);
15004            canvas.drawRect(left, bottom - length, right, bottom, p);
15005        }
15006
15007        if (drawLeft) {
15008            matrix.setScale(1, fadeHeight * leftFadeStrength);
15009            matrix.postRotate(-90);
15010            matrix.postTranslate(left, top);
15011            fade.setLocalMatrix(matrix);
15012            canvas.drawRect(left, top, left + length, bottom, p);
15013        }
15014
15015        if (drawRight) {
15016            matrix.setScale(1, fadeHeight * rightFadeStrength);
15017            matrix.postRotate(90);
15018            matrix.postTranslate(right, top);
15019            fade.setLocalMatrix(matrix);
15020            canvas.drawRect(right - length, top, right, bottom, p);
15021        }
15022
15023        canvas.restoreToCount(saveCount);
15024
15025        // Step 6, draw decorations (scrollbars)
15026        onDrawScrollBars(canvas);
15027
15028        if (mOverlay != null && !mOverlay.isEmpty()) {
15029            mOverlay.getOverlayView().dispatchDraw(canvas);
15030        }
15031    }
15032
15033    /**
15034     * Draws the background onto the specified canvas.
15035     *
15036     * @param canvas Canvas on which to draw the background
15037     */
15038    private void drawBackground(Canvas canvas) {
15039        final Drawable background = mBackground;
15040        if (background == null) {
15041            return;
15042        }
15043
15044        if (mBackgroundSizeChanged) {
15045            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15046            mBackgroundSizeChanged = false;
15047            queryOutlineFromBackgroundIfUndefined();
15048        }
15049
15050        // Attempt to use a display list if requested.
15051        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15052                && mAttachInfo.mHardwareRenderer != null) {
15053            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
15054
15055            final RenderNode displayList = mBackgroundDisplayList;
15056            if (displayList != null && displayList.isValid()) {
15057                setBackgroundDisplayListProperties(displayList);
15058                ((HardwareCanvas) canvas).drawDisplayList(displayList);
15059                return;
15060            }
15061        }
15062
15063        final int scrollX = mScrollX;
15064        final int scrollY = mScrollY;
15065        if ((scrollX | scrollY) == 0) {
15066            background.draw(canvas);
15067        } else {
15068            canvas.translate(scrollX, scrollY);
15069            background.draw(canvas);
15070            canvas.translate(-scrollX, -scrollY);
15071        }
15072    }
15073
15074    /**
15075     * Set up background drawable display list properties.
15076     *
15077     * @param displayList Valid display list for the background drawable
15078     */
15079    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15080        displayList.setTranslationX(mScrollX);
15081        displayList.setTranslationY(mScrollY);
15082    }
15083
15084    /**
15085     * Creates a new display list or updates the existing display list for the
15086     * specified Drawable.
15087     *
15088     * @param drawable Drawable for which to create a display list
15089     * @param displayList Existing display list, or {@code null}
15090     * @return A valid display list for the specified drawable
15091     */
15092    private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) {
15093        if (displayList == null) {
15094            displayList = RenderNode.create(drawable.getClass().getName());
15095        }
15096
15097        final Rect bounds = drawable.getBounds();
15098        final int width = bounds.width();
15099        final int height = bounds.height();
15100        final HardwareCanvas canvas = displayList.start(width, height);
15101        try {
15102            drawable.draw(canvas);
15103        } finally {
15104            displayList.end(canvas);
15105        }
15106
15107        // Set up drawable properties that are view-independent.
15108        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15109        displayList.setProjectBackwards(drawable.isProjected());
15110        displayList.setProjectionReceiver(true);
15111        displayList.setClipToBounds(false);
15112        return displayList;
15113    }
15114
15115    /**
15116     * Returns the overlay for this view, creating it if it does not yet exist.
15117     * Adding drawables to the overlay will cause them to be displayed whenever
15118     * the view itself is redrawn. Objects in the overlay should be actively
15119     * managed: remove them when they should not be displayed anymore. The
15120     * overlay will always have the same size as its host view.
15121     *
15122     * <p>Note: Overlays do not currently work correctly with {@link
15123     * SurfaceView} or {@link TextureView}; contents in overlays for these
15124     * types of views may not display correctly.</p>
15125     *
15126     * @return The ViewOverlay object for this view.
15127     * @see ViewOverlay
15128     */
15129    public ViewOverlay getOverlay() {
15130        if (mOverlay == null) {
15131            mOverlay = new ViewOverlay(mContext, this);
15132        }
15133        return mOverlay;
15134    }
15135
15136    /**
15137     * Override this if your view is known to always be drawn on top of a solid color background,
15138     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15139     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15140     * should be set to 0xFF.
15141     *
15142     * @see #setVerticalFadingEdgeEnabled(boolean)
15143     * @see #setHorizontalFadingEdgeEnabled(boolean)
15144     *
15145     * @return The known solid color background for this view, or 0 if the color may vary
15146     */
15147    @ViewDebug.ExportedProperty(category = "drawing")
15148    public int getSolidColor() {
15149        return 0;
15150    }
15151
15152    /**
15153     * Build a human readable string representation of the specified view flags.
15154     *
15155     * @param flags the view flags to convert to a string
15156     * @return a String representing the supplied flags
15157     */
15158    private static String printFlags(int flags) {
15159        String output = "";
15160        int numFlags = 0;
15161        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15162            output += "TAKES_FOCUS";
15163            numFlags++;
15164        }
15165
15166        switch (flags & VISIBILITY_MASK) {
15167        case INVISIBLE:
15168            if (numFlags > 0) {
15169                output += " ";
15170            }
15171            output += "INVISIBLE";
15172            // USELESS HERE numFlags++;
15173            break;
15174        case GONE:
15175            if (numFlags > 0) {
15176                output += " ";
15177            }
15178            output += "GONE";
15179            // USELESS HERE numFlags++;
15180            break;
15181        default:
15182            break;
15183        }
15184        return output;
15185    }
15186
15187    /**
15188     * Build a human readable string representation of the specified private
15189     * view flags.
15190     *
15191     * @param privateFlags the private view flags to convert to a string
15192     * @return a String representing the supplied flags
15193     */
15194    private static String printPrivateFlags(int privateFlags) {
15195        String output = "";
15196        int numFlags = 0;
15197
15198        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15199            output += "WANTS_FOCUS";
15200            numFlags++;
15201        }
15202
15203        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15204            if (numFlags > 0) {
15205                output += " ";
15206            }
15207            output += "FOCUSED";
15208            numFlags++;
15209        }
15210
15211        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15212            if (numFlags > 0) {
15213                output += " ";
15214            }
15215            output += "SELECTED";
15216            numFlags++;
15217        }
15218
15219        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15220            if (numFlags > 0) {
15221                output += " ";
15222            }
15223            output += "IS_ROOT_NAMESPACE";
15224            numFlags++;
15225        }
15226
15227        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15228            if (numFlags > 0) {
15229                output += " ";
15230            }
15231            output += "HAS_BOUNDS";
15232            numFlags++;
15233        }
15234
15235        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15236            if (numFlags > 0) {
15237                output += " ";
15238            }
15239            output += "DRAWN";
15240            // USELESS HERE numFlags++;
15241        }
15242        return output;
15243    }
15244
15245    /**
15246     * <p>Indicates whether or not this view's layout will be requested during
15247     * the next hierarchy layout pass.</p>
15248     *
15249     * @return true if the layout will be forced during next layout pass
15250     */
15251    public boolean isLayoutRequested() {
15252        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15253    }
15254
15255    /**
15256     * Return true if o is a ViewGroup that is laying out using optical bounds.
15257     * @hide
15258     */
15259    public static boolean isLayoutModeOptical(Object o) {
15260        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15261    }
15262
15263    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15264        Insets parentInsets = mParent instanceof View ?
15265                ((View) mParent).getOpticalInsets() : Insets.NONE;
15266        Insets childInsets = getOpticalInsets();
15267        return setFrame(
15268                left   + parentInsets.left - childInsets.left,
15269                top    + parentInsets.top  - childInsets.top,
15270                right  + parentInsets.left + childInsets.right,
15271                bottom + parentInsets.top  + childInsets.bottom);
15272    }
15273
15274    /**
15275     * Assign a size and position to a view and all of its
15276     * descendants
15277     *
15278     * <p>This is the second phase of the layout mechanism.
15279     * (The first is measuring). In this phase, each parent calls
15280     * layout on all of its children to position them.
15281     * This is typically done using the child measurements
15282     * that were stored in the measure pass().</p>
15283     *
15284     * <p>Derived classes should not override this method.
15285     * Derived classes with children should override
15286     * onLayout. In that method, they should
15287     * call layout on each of their children.</p>
15288     *
15289     * @param l Left position, relative to parent
15290     * @param t Top position, relative to parent
15291     * @param r Right position, relative to parent
15292     * @param b Bottom position, relative to parent
15293     */
15294    @SuppressWarnings({"unchecked"})
15295    public void layout(int l, int t, int r, int b) {
15296        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15297            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15298            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15299        }
15300
15301        int oldL = mLeft;
15302        int oldT = mTop;
15303        int oldB = mBottom;
15304        int oldR = mRight;
15305
15306        boolean changed = isLayoutModeOptical(mParent) ?
15307                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15308
15309        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15310            onLayout(changed, l, t, r, b);
15311            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15312
15313            ListenerInfo li = mListenerInfo;
15314            if (li != null && li.mOnLayoutChangeListeners != null) {
15315                ArrayList<OnLayoutChangeListener> listenersCopy =
15316                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15317                int numListeners = listenersCopy.size();
15318                for (int i = 0; i < numListeners; ++i) {
15319                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15320                }
15321            }
15322        }
15323
15324        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15325        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15326    }
15327
15328    /**
15329     * Called from layout when this view should
15330     * assign a size and position to each of its children.
15331     *
15332     * Derived classes with children should override
15333     * this method and call layout on each of
15334     * their children.
15335     * @param changed This is a new size or position for this view
15336     * @param left Left position, relative to parent
15337     * @param top Top position, relative to parent
15338     * @param right Right position, relative to parent
15339     * @param bottom Bottom position, relative to parent
15340     */
15341    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15342    }
15343
15344    /**
15345     * Assign a size and position to this view.
15346     *
15347     * This is called from layout.
15348     *
15349     * @param left Left position, relative to parent
15350     * @param top Top position, relative to parent
15351     * @param right Right position, relative to parent
15352     * @param bottom Bottom position, relative to parent
15353     * @return true if the new size and position are different than the
15354     *         previous ones
15355     * {@hide}
15356     */
15357    protected boolean setFrame(int left, int top, int right, int bottom) {
15358        boolean changed = false;
15359
15360        if (DBG) {
15361            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15362                    + right + "," + bottom + ")");
15363        }
15364
15365        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15366            changed = true;
15367
15368            // Remember our drawn bit
15369            int drawn = mPrivateFlags & PFLAG_DRAWN;
15370
15371            int oldWidth = mRight - mLeft;
15372            int oldHeight = mBottom - mTop;
15373            int newWidth = right - left;
15374            int newHeight = bottom - top;
15375            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15376
15377            // Invalidate our old position
15378            invalidate(sizeChanged);
15379
15380            mLeft = left;
15381            mTop = top;
15382            mRight = right;
15383            mBottom = bottom;
15384            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15385
15386            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15387
15388
15389            if (sizeChanged) {
15390                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15391            }
15392
15393            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15394                // If we are visible, force the DRAWN bit to on so that
15395                // this invalidate will go through (at least to our parent).
15396                // This is because someone may have invalidated this view
15397                // before this call to setFrame came in, thereby clearing
15398                // the DRAWN bit.
15399                mPrivateFlags |= PFLAG_DRAWN;
15400                invalidate(sizeChanged);
15401                // parent display list may need to be recreated based on a change in the bounds
15402                // of any child
15403                invalidateParentCaches();
15404            }
15405
15406            // Reset drawn bit to original value (invalidate turns it off)
15407            mPrivateFlags |= drawn;
15408
15409            mBackgroundSizeChanged = true;
15410
15411            notifySubtreeAccessibilityStateChangedIfNeeded();
15412        }
15413        return changed;
15414    }
15415
15416    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15417        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15418        if (mOverlay != null) {
15419            mOverlay.getOverlayView().setRight(newWidth);
15420            mOverlay.getOverlayView().setBottom(newHeight);
15421        }
15422    }
15423
15424    /**
15425     * Finalize inflating a view from XML.  This is called as the last phase
15426     * of inflation, after all child views have been added.
15427     *
15428     * <p>Even if the subclass overrides onFinishInflate, they should always be
15429     * sure to call the super method, so that we get called.
15430     */
15431    protected void onFinishInflate() {
15432    }
15433
15434    /**
15435     * Returns the resources associated with this view.
15436     *
15437     * @return Resources object.
15438     */
15439    public Resources getResources() {
15440        return mResources;
15441    }
15442
15443    /**
15444     * Invalidates the specified Drawable.
15445     *
15446     * @param drawable the drawable to invalidate
15447     */
15448    @Override
15449    public void invalidateDrawable(@NonNull Drawable drawable) {
15450        if (verifyDrawable(drawable)) {
15451            final Rect dirty = drawable.getDirtyBounds();
15452            final int scrollX = mScrollX;
15453            final int scrollY = mScrollY;
15454
15455            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15456                    dirty.right + scrollX, dirty.bottom + scrollY);
15457
15458            if (drawable == mBackground) {
15459                queryOutlineFromBackgroundIfUndefined();
15460            }
15461        }
15462    }
15463
15464    /**
15465     * Schedules an action on a drawable to occur at a specified time.
15466     *
15467     * @param who the recipient of the action
15468     * @param what the action to run on the drawable
15469     * @param when the time at which the action must occur. Uses the
15470     *        {@link SystemClock#uptimeMillis} timebase.
15471     */
15472    @Override
15473    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15474        if (verifyDrawable(who) && what != null) {
15475            final long delay = when - SystemClock.uptimeMillis();
15476            if (mAttachInfo != null) {
15477                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15478                        Choreographer.CALLBACK_ANIMATION, what, who,
15479                        Choreographer.subtractFrameDelay(delay));
15480            } else {
15481                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15482            }
15483        }
15484    }
15485
15486    /**
15487     * Cancels a scheduled action on a drawable.
15488     *
15489     * @param who the recipient of the action
15490     * @param what the action to cancel
15491     */
15492    @Override
15493    public void unscheduleDrawable(Drawable who, Runnable what) {
15494        if (verifyDrawable(who) && what != null) {
15495            if (mAttachInfo != null) {
15496                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15497                        Choreographer.CALLBACK_ANIMATION, what, who);
15498            }
15499            ViewRootImpl.getRunQueue().removeCallbacks(what);
15500        }
15501    }
15502
15503    /**
15504     * Unschedule any events associated with the given Drawable.  This can be
15505     * used when selecting a new Drawable into a view, so that the previous
15506     * one is completely unscheduled.
15507     *
15508     * @param who The Drawable to unschedule.
15509     *
15510     * @see #drawableStateChanged
15511     */
15512    public void unscheduleDrawable(Drawable who) {
15513        if (mAttachInfo != null && who != null) {
15514            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15515                    Choreographer.CALLBACK_ANIMATION, null, who);
15516        }
15517    }
15518
15519    /**
15520     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15521     * that the View directionality can and will be resolved before its Drawables.
15522     *
15523     * Will call {@link View#onResolveDrawables} when resolution is done.
15524     *
15525     * @hide
15526     */
15527    protected void resolveDrawables() {
15528        // Drawables resolution may need to happen before resolving the layout direction (which is
15529        // done only during the measure() call).
15530        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15531        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15532        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15533        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15534        // direction to be resolved as its resolved value will be the same as its raw value.
15535        if (!isLayoutDirectionResolved() &&
15536                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15537            return;
15538        }
15539
15540        final int layoutDirection = isLayoutDirectionResolved() ?
15541                getLayoutDirection() : getRawLayoutDirection();
15542
15543        if (mBackground != null) {
15544            mBackground.setLayoutDirection(layoutDirection);
15545        }
15546        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15547        onResolveDrawables(layoutDirection);
15548    }
15549
15550    /**
15551     * Called when layout direction has been resolved.
15552     *
15553     * The default implementation does nothing.
15554     *
15555     * @param layoutDirection The resolved layout direction.
15556     *
15557     * @see #LAYOUT_DIRECTION_LTR
15558     * @see #LAYOUT_DIRECTION_RTL
15559     *
15560     * @hide
15561     */
15562    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15563    }
15564
15565    /**
15566     * @hide
15567     */
15568    protected void resetResolvedDrawables() {
15569        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15570    }
15571
15572    private boolean isDrawablesResolved() {
15573        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15574    }
15575
15576    /**
15577     * If your view subclass is displaying its own Drawable objects, it should
15578     * override this function and return true for any Drawable it is
15579     * displaying.  This allows animations for those drawables to be
15580     * scheduled.
15581     *
15582     * <p>Be sure to call through to the super class when overriding this
15583     * function.
15584     *
15585     * @param who The Drawable to verify.  Return true if it is one you are
15586     *            displaying, else return the result of calling through to the
15587     *            super class.
15588     *
15589     * @return boolean If true than the Drawable is being displayed in the
15590     *         view; else false and it is not allowed to animate.
15591     *
15592     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15593     * @see #drawableStateChanged()
15594     */
15595    protected boolean verifyDrawable(Drawable who) {
15596        return who == mBackground;
15597    }
15598
15599    /**
15600     * This function is called whenever the state of the view changes in such
15601     * a way that it impacts the state of drawables being shown.
15602     * <p>
15603     * If the View has a StateListAnimator, it will also be called to run necessary state
15604     * change animations.
15605     * <p>
15606     * Be sure to call through to the superclass when overriding this function.
15607     *
15608     * @see Drawable#setState(int[])
15609     */
15610    protected void drawableStateChanged() {
15611        final Drawable d = mBackground;
15612        if (d != null && d.isStateful()) {
15613            d.setState(getDrawableState());
15614        }
15615
15616        if (mStateListAnimator != null) {
15617            mStateListAnimator.setState(getDrawableState());
15618        }
15619    }
15620
15621    /**
15622     * Call this to force a view to update its drawable state. This will cause
15623     * drawableStateChanged to be called on this view. Views that are interested
15624     * in the new state should call getDrawableState.
15625     *
15626     * @see #drawableStateChanged
15627     * @see #getDrawableState
15628     */
15629    public void refreshDrawableState() {
15630        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15631        drawableStateChanged();
15632
15633        ViewParent parent = mParent;
15634        if (parent != null) {
15635            parent.childDrawableStateChanged(this);
15636        }
15637    }
15638
15639    /**
15640     * Return an array of resource IDs of the drawable states representing the
15641     * current state of the view.
15642     *
15643     * @return The current drawable state
15644     *
15645     * @see Drawable#setState(int[])
15646     * @see #drawableStateChanged()
15647     * @see #onCreateDrawableState(int)
15648     */
15649    public final int[] getDrawableState() {
15650        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15651            return mDrawableState;
15652        } else {
15653            mDrawableState = onCreateDrawableState(0);
15654            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15655            return mDrawableState;
15656        }
15657    }
15658
15659    /**
15660     * Generate the new {@link android.graphics.drawable.Drawable} state for
15661     * this view. This is called by the view
15662     * system when the cached Drawable state is determined to be invalid.  To
15663     * retrieve the current state, you should use {@link #getDrawableState}.
15664     *
15665     * @param extraSpace if non-zero, this is the number of extra entries you
15666     * would like in the returned array in which you can place your own
15667     * states.
15668     *
15669     * @return Returns an array holding the current {@link Drawable} state of
15670     * the view.
15671     *
15672     * @see #mergeDrawableStates(int[], int[])
15673     */
15674    protected int[] onCreateDrawableState(int extraSpace) {
15675        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15676                mParent instanceof View) {
15677            return ((View) mParent).onCreateDrawableState(extraSpace);
15678        }
15679
15680        int[] drawableState;
15681
15682        int privateFlags = mPrivateFlags;
15683
15684        int viewStateIndex = 0;
15685        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15686        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15687        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15688        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15689        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15690        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15691        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15692                HardwareRenderer.isAvailable()) {
15693            // This is set if HW acceleration is requested, even if the current
15694            // process doesn't allow it.  This is just to allow app preview
15695            // windows to better match their app.
15696            viewStateIndex |= VIEW_STATE_ACCELERATED;
15697        }
15698        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15699
15700        final int privateFlags2 = mPrivateFlags2;
15701        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15702        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15703
15704        drawableState = VIEW_STATE_SETS[viewStateIndex];
15705
15706        //noinspection ConstantIfStatement
15707        if (false) {
15708            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15709            Log.i("View", toString()
15710                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15711                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15712                    + " fo=" + hasFocus()
15713                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15714                    + " wf=" + hasWindowFocus()
15715                    + ": " + Arrays.toString(drawableState));
15716        }
15717
15718        if (extraSpace == 0) {
15719            return drawableState;
15720        }
15721
15722        final int[] fullState;
15723        if (drawableState != null) {
15724            fullState = new int[drawableState.length + extraSpace];
15725            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15726        } else {
15727            fullState = new int[extraSpace];
15728        }
15729
15730        return fullState;
15731    }
15732
15733    /**
15734     * Merge your own state values in <var>additionalState</var> into the base
15735     * state values <var>baseState</var> that were returned by
15736     * {@link #onCreateDrawableState(int)}.
15737     *
15738     * @param baseState The base state values returned by
15739     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15740     * own additional state values.
15741     *
15742     * @param additionalState The additional state values you would like
15743     * added to <var>baseState</var>; this array is not modified.
15744     *
15745     * @return As a convenience, the <var>baseState</var> array you originally
15746     * passed into the function is returned.
15747     *
15748     * @see #onCreateDrawableState(int)
15749     */
15750    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15751        final int N = baseState.length;
15752        int i = N - 1;
15753        while (i >= 0 && baseState[i] == 0) {
15754            i--;
15755        }
15756        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15757        return baseState;
15758    }
15759
15760    /**
15761     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15762     * on all Drawable objects associated with this view.
15763     * <p>
15764     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15765     * attached to this view.
15766     */
15767    public void jumpDrawablesToCurrentState() {
15768        if (mBackground != null) {
15769            mBackground.jumpToCurrentState();
15770        }
15771        if (mStateListAnimator != null) {
15772            mStateListAnimator.jumpToCurrentState();
15773        }
15774    }
15775
15776    /**
15777     * Sets the background color for this view.
15778     * @param color the color of the background
15779     */
15780    @RemotableViewMethod
15781    public void setBackgroundColor(int color) {
15782        if (mBackground instanceof ColorDrawable) {
15783            ((ColorDrawable) mBackground.mutate()).setColor(color);
15784            computeOpaqueFlags();
15785            mBackgroundResource = 0;
15786        } else {
15787            setBackground(new ColorDrawable(color));
15788        }
15789    }
15790
15791    /**
15792     * Set the background to a given resource. The resource should refer to
15793     * a Drawable object or 0 to remove the background.
15794     * @param resid The identifier of the resource.
15795     *
15796     * @attr ref android.R.styleable#View_background
15797     */
15798    @RemotableViewMethod
15799    public void setBackgroundResource(int resid) {
15800        if (resid != 0 && resid == mBackgroundResource) {
15801            return;
15802        }
15803
15804        Drawable d= null;
15805        if (resid != 0) {
15806            d = mContext.getDrawable(resid);
15807        }
15808        setBackground(d);
15809
15810        mBackgroundResource = resid;
15811    }
15812
15813    /**
15814     * Set the background to a given Drawable, or remove the background. If the
15815     * background has padding, this View's padding is set to the background's
15816     * padding. However, when a background is removed, this View's padding isn't
15817     * touched. If setting the padding is desired, please use
15818     * {@link #setPadding(int, int, int, int)}.
15819     *
15820     * @param background The Drawable to use as the background, or null to remove the
15821     *        background
15822     */
15823    public void setBackground(Drawable background) {
15824        //noinspection deprecation
15825        setBackgroundDrawable(background);
15826    }
15827
15828    /**
15829     * @deprecated use {@link #setBackground(Drawable)} instead
15830     */
15831    @Deprecated
15832    public void setBackgroundDrawable(Drawable background) {
15833        computeOpaqueFlags();
15834
15835        if (background == mBackground) {
15836            return;
15837        }
15838
15839        boolean requestLayout = false;
15840
15841        mBackgroundResource = 0;
15842
15843        /*
15844         * Regardless of whether we're setting a new background or not, we want
15845         * to clear the previous drawable.
15846         */
15847        if (mBackground != null) {
15848            mBackground.setCallback(null);
15849            unscheduleDrawable(mBackground);
15850        }
15851
15852        if (background != null) {
15853            Rect padding = sThreadLocal.get();
15854            if (padding == null) {
15855                padding = new Rect();
15856                sThreadLocal.set(padding);
15857            }
15858            resetResolvedDrawables();
15859            background.setLayoutDirection(getLayoutDirection());
15860            if (background.getPadding(padding)) {
15861                resetResolvedPadding();
15862                switch (background.getLayoutDirection()) {
15863                    case LAYOUT_DIRECTION_RTL:
15864                        mUserPaddingLeftInitial = padding.right;
15865                        mUserPaddingRightInitial = padding.left;
15866                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15867                        break;
15868                    case LAYOUT_DIRECTION_LTR:
15869                    default:
15870                        mUserPaddingLeftInitial = padding.left;
15871                        mUserPaddingRightInitial = padding.right;
15872                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15873                }
15874                mLeftPaddingDefined = false;
15875                mRightPaddingDefined = false;
15876            }
15877
15878            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15879            // if it has a different minimum size, we should layout again
15880            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15881                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15882                requestLayout = true;
15883            }
15884
15885            background.setCallback(this);
15886            if (background.isStateful()) {
15887                background.setState(getDrawableState());
15888            }
15889            background.setVisible(getVisibility() == VISIBLE, false);
15890            mBackground = background;
15891
15892            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15893                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15894                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15895                requestLayout = true;
15896            }
15897        } else {
15898            /* Remove the background */
15899            mBackground = null;
15900
15901            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15902                /*
15903                 * This view ONLY drew the background before and we're removing
15904                 * the background, so now it won't draw anything
15905                 * (hence we SKIP_DRAW)
15906                 */
15907                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15908                mPrivateFlags |= PFLAG_SKIP_DRAW;
15909            }
15910
15911            /*
15912             * When the background is set, we try to apply its padding to this
15913             * View. When the background is removed, we don't touch this View's
15914             * padding. This is noted in the Javadocs. Hence, we don't need to
15915             * requestLayout(), the invalidate() below is sufficient.
15916             */
15917
15918            // The old background's minimum size could have affected this
15919            // View's layout, so let's requestLayout
15920            requestLayout = true;
15921        }
15922
15923        computeOpaqueFlags();
15924
15925        if (requestLayout) {
15926            requestLayout();
15927        }
15928
15929        mBackgroundSizeChanged = true;
15930        invalidate(true);
15931    }
15932
15933    /**
15934     * Gets the background drawable
15935     *
15936     * @return The drawable used as the background for this view, if any.
15937     *
15938     * @see #setBackground(Drawable)
15939     *
15940     * @attr ref android.R.styleable#View_background
15941     */
15942    public Drawable getBackground() {
15943        return mBackground;
15944    }
15945
15946    /**
15947     * Sets the padding. The view may add on the space required to display
15948     * the scrollbars, depending on the style and visibility of the scrollbars.
15949     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15950     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15951     * from the values set in this call.
15952     *
15953     * @attr ref android.R.styleable#View_padding
15954     * @attr ref android.R.styleable#View_paddingBottom
15955     * @attr ref android.R.styleable#View_paddingLeft
15956     * @attr ref android.R.styleable#View_paddingRight
15957     * @attr ref android.R.styleable#View_paddingTop
15958     * @param left the left padding in pixels
15959     * @param top the top padding in pixels
15960     * @param right the right padding in pixels
15961     * @param bottom the bottom padding in pixels
15962     */
15963    public void setPadding(int left, int top, int right, int bottom) {
15964        resetResolvedPadding();
15965
15966        mUserPaddingStart = UNDEFINED_PADDING;
15967        mUserPaddingEnd = UNDEFINED_PADDING;
15968
15969        mUserPaddingLeftInitial = left;
15970        mUserPaddingRightInitial = right;
15971
15972        mLeftPaddingDefined = true;
15973        mRightPaddingDefined = true;
15974
15975        internalSetPadding(left, top, right, bottom);
15976    }
15977
15978    /**
15979     * @hide
15980     */
15981    protected void internalSetPadding(int left, int top, int right, int bottom) {
15982        mUserPaddingLeft = left;
15983        mUserPaddingRight = right;
15984        mUserPaddingBottom = bottom;
15985
15986        final int viewFlags = mViewFlags;
15987        boolean changed = false;
15988
15989        // Common case is there are no scroll bars.
15990        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15991            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15992                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15993                        ? 0 : getVerticalScrollbarWidth();
15994                switch (mVerticalScrollbarPosition) {
15995                    case SCROLLBAR_POSITION_DEFAULT:
15996                        if (isLayoutRtl()) {
15997                            left += offset;
15998                        } else {
15999                            right += offset;
16000                        }
16001                        break;
16002                    case SCROLLBAR_POSITION_RIGHT:
16003                        right += offset;
16004                        break;
16005                    case SCROLLBAR_POSITION_LEFT:
16006                        left += offset;
16007                        break;
16008                }
16009            }
16010            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16011                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16012                        ? 0 : getHorizontalScrollbarHeight();
16013            }
16014        }
16015
16016        if (mPaddingLeft != left) {
16017            changed = true;
16018            mPaddingLeft = left;
16019        }
16020        if (mPaddingTop != top) {
16021            changed = true;
16022            mPaddingTop = top;
16023        }
16024        if (mPaddingRight != right) {
16025            changed = true;
16026            mPaddingRight = right;
16027        }
16028        if (mPaddingBottom != bottom) {
16029            changed = true;
16030            mPaddingBottom = bottom;
16031        }
16032
16033        if (changed) {
16034            requestLayout();
16035        }
16036    }
16037
16038    /**
16039     * Sets the relative padding. The view may add on the space required to display
16040     * the scrollbars, depending on the style and visibility of the scrollbars.
16041     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16042     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16043     * from the values set in this call.
16044     *
16045     * @attr ref android.R.styleable#View_padding
16046     * @attr ref android.R.styleable#View_paddingBottom
16047     * @attr ref android.R.styleable#View_paddingStart
16048     * @attr ref android.R.styleable#View_paddingEnd
16049     * @attr ref android.R.styleable#View_paddingTop
16050     * @param start the start padding in pixels
16051     * @param top the top padding in pixels
16052     * @param end the end padding in pixels
16053     * @param bottom the bottom padding in pixels
16054     */
16055    public void setPaddingRelative(int start, int top, int end, int bottom) {
16056        resetResolvedPadding();
16057
16058        mUserPaddingStart = start;
16059        mUserPaddingEnd = end;
16060        mLeftPaddingDefined = true;
16061        mRightPaddingDefined = true;
16062
16063        switch(getLayoutDirection()) {
16064            case LAYOUT_DIRECTION_RTL:
16065                mUserPaddingLeftInitial = end;
16066                mUserPaddingRightInitial = start;
16067                internalSetPadding(end, top, start, bottom);
16068                break;
16069            case LAYOUT_DIRECTION_LTR:
16070            default:
16071                mUserPaddingLeftInitial = start;
16072                mUserPaddingRightInitial = end;
16073                internalSetPadding(start, top, end, bottom);
16074        }
16075    }
16076
16077    /**
16078     * Returns the top padding of this view.
16079     *
16080     * @return the top padding in pixels
16081     */
16082    public int getPaddingTop() {
16083        return mPaddingTop;
16084    }
16085
16086    /**
16087     * Returns the bottom padding of this view. If there are inset and enabled
16088     * scrollbars, this value may include the space required to display the
16089     * scrollbars as well.
16090     *
16091     * @return the bottom padding in pixels
16092     */
16093    public int getPaddingBottom() {
16094        return mPaddingBottom;
16095    }
16096
16097    /**
16098     * Returns the left padding of this view. If there are inset and enabled
16099     * scrollbars, this value may include the space required to display the
16100     * scrollbars as well.
16101     *
16102     * @return the left padding in pixels
16103     */
16104    public int getPaddingLeft() {
16105        if (!isPaddingResolved()) {
16106            resolvePadding();
16107        }
16108        return mPaddingLeft;
16109    }
16110
16111    /**
16112     * Returns the start padding of this view depending on its resolved layout direction.
16113     * If there are inset and enabled scrollbars, this value may include the space
16114     * required to display the scrollbars as well.
16115     *
16116     * @return the start padding in pixels
16117     */
16118    public int getPaddingStart() {
16119        if (!isPaddingResolved()) {
16120            resolvePadding();
16121        }
16122        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16123                mPaddingRight : mPaddingLeft;
16124    }
16125
16126    /**
16127     * Returns the right padding of this view. If there are inset and enabled
16128     * scrollbars, this value may include the space required to display the
16129     * scrollbars as well.
16130     *
16131     * @return the right padding in pixels
16132     */
16133    public int getPaddingRight() {
16134        if (!isPaddingResolved()) {
16135            resolvePadding();
16136        }
16137        return mPaddingRight;
16138    }
16139
16140    /**
16141     * Returns the end padding of this view depending on its resolved layout direction.
16142     * If there are inset and enabled scrollbars, this value may include the space
16143     * required to display the scrollbars as well.
16144     *
16145     * @return the end padding in pixels
16146     */
16147    public int getPaddingEnd() {
16148        if (!isPaddingResolved()) {
16149            resolvePadding();
16150        }
16151        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16152                mPaddingLeft : mPaddingRight;
16153    }
16154
16155    /**
16156     * Return if the padding as been set thru relative values
16157     * {@link #setPaddingRelative(int, int, int, int)} or thru
16158     * @attr ref android.R.styleable#View_paddingStart or
16159     * @attr ref android.R.styleable#View_paddingEnd
16160     *
16161     * @return true if the padding is relative or false if it is not.
16162     */
16163    public boolean isPaddingRelative() {
16164        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16165    }
16166
16167    Insets computeOpticalInsets() {
16168        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16169    }
16170
16171    /**
16172     * @hide
16173     */
16174    public void resetPaddingToInitialValues() {
16175        if (isRtlCompatibilityMode()) {
16176            mPaddingLeft = mUserPaddingLeftInitial;
16177            mPaddingRight = mUserPaddingRightInitial;
16178            return;
16179        }
16180        if (isLayoutRtl()) {
16181            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16182            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16183        } else {
16184            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16185            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16186        }
16187    }
16188
16189    /**
16190     * @hide
16191     */
16192    public Insets getOpticalInsets() {
16193        if (mLayoutInsets == null) {
16194            mLayoutInsets = computeOpticalInsets();
16195        }
16196        return mLayoutInsets;
16197    }
16198
16199    /**
16200     * Changes the selection state of this view. A view can be selected or not.
16201     * Note that selection is not the same as focus. Views are typically
16202     * selected in the context of an AdapterView like ListView or GridView;
16203     * the selected view is the view that is highlighted.
16204     *
16205     * @param selected true if the view must be selected, false otherwise
16206     */
16207    public void setSelected(boolean selected) {
16208        //noinspection DoubleNegation
16209        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16210            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16211            if (!selected) resetPressedState();
16212            invalidate(true);
16213            refreshDrawableState();
16214            dispatchSetSelected(selected);
16215            notifyViewAccessibilityStateChangedIfNeeded(
16216                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16217        }
16218    }
16219
16220    /**
16221     * Dispatch setSelected to all of this View's children.
16222     *
16223     * @see #setSelected(boolean)
16224     *
16225     * @param selected The new selected state
16226     */
16227    protected void dispatchSetSelected(boolean selected) {
16228    }
16229
16230    /**
16231     * Indicates the selection state of this view.
16232     *
16233     * @return true if the view is selected, false otherwise
16234     */
16235    @ViewDebug.ExportedProperty
16236    public boolean isSelected() {
16237        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16238    }
16239
16240    /**
16241     * Changes the activated state of this view. A view can be activated or not.
16242     * Note that activation is not the same as selection.  Selection is
16243     * a transient property, representing the view (hierarchy) the user is
16244     * currently interacting with.  Activation is a longer-term state that the
16245     * user can move views in and out of.  For example, in a list view with
16246     * single or multiple selection enabled, the views in the current selection
16247     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16248     * here.)  The activated state is propagated down to children of the view it
16249     * is set on.
16250     *
16251     * @param activated true if the view must be activated, false otherwise
16252     */
16253    public void setActivated(boolean activated) {
16254        //noinspection DoubleNegation
16255        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16256            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16257            invalidate(true);
16258            refreshDrawableState();
16259            dispatchSetActivated(activated);
16260        }
16261    }
16262
16263    /**
16264     * Dispatch setActivated to all of this View's children.
16265     *
16266     * @see #setActivated(boolean)
16267     *
16268     * @param activated The new activated state
16269     */
16270    protected void dispatchSetActivated(boolean activated) {
16271    }
16272
16273    /**
16274     * Indicates the activation state of this view.
16275     *
16276     * @return true if the view is activated, false otherwise
16277     */
16278    @ViewDebug.ExportedProperty
16279    public boolean isActivated() {
16280        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16281    }
16282
16283    /**
16284     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16285     * observer can be used to get notifications when global events, like
16286     * layout, happen.
16287     *
16288     * The returned ViewTreeObserver observer is not guaranteed to remain
16289     * valid for the lifetime of this View. If the caller of this method keeps
16290     * a long-lived reference to ViewTreeObserver, it should always check for
16291     * the return value of {@link ViewTreeObserver#isAlive()}.
16292     *
16293     * @return The ViewTreeObserver for this view's hierarchy.
16294     */
16295    public ViewTreeObserver getViewTreeObserver() {
16296        if (mAttachInfo != null) {
16297            return mAttachInfo.mTreeObserver;
16298        }
16299        if (mFloatingTreeObserver == null) {
16300            mFloatingTreeObserver = new ViewTreeObserver();
16301        }
16302        return mFloatingTreeObserver;
16303    }
16304
16305    /**
16306     * <p>Finds the topmost view in the current view hierarchy.</p>
16307     *
16308     * @return the topmost view containing this view
16309     */
16310    public View getRootView() {
16311        if (mAttachInfo != null) {
16312            final View v = mAttachInfo.mRootView;
16313            if (v != null) {
16314                return v;
16315            }
16316        }
16317
16318        View parent = this;
16319
16320        while (parent.mParent != null && parent.mParent instanceof View) {
16321            parent = (View) parent.mParent;
16322        }
16323
16324        return parent;
16325    }
16326
16327    /**
16328     * Transforms a motion event from view-local coordinates to on-screen
16329     * coordinates.
16330     *
16331     * @param ev the view-local motion event
16332     * @return false if the transformation could not be applied
16333     * @hide
16334     */
16335    public boolean toGlobalMotionEvent(MotionEvent ev) {
16336        final AttachInfo info = mAttachInfo;
16337        if (info == null) {
16338            return false;
16339        }
16340
16341        final Matrix m = info.mTmpMatrix;
16342        m.set(Matrix.IDENTITY_MATRIX);
16343        transformMatrixToGlobal(m);
16344        ev.transform(m);
16345        return true;
16346    }
16347
16348    /**
16349     * Transforms a motion event from on-screen coordinates to view-local
16350     * coordinates.
16351     *
16352     * @param ev the on-screen motion event
16353     * @return false if the transformation could not be applied
16354     * @hide
16355     */
16356    public boolean toLocalMotionEvent(MotionEvent ev) {
16357        final AttachInfo info = mAttachInfo;
16358        if (info == null) {
16359            return false;
16360        }
16361
16362        final Matrix m = info.mTmpMatrix;
16363        m.set(Matrix.IDENTITY_MATRIX);
16364        transformMatrixToLocal(m);
16365        ev.transform(m);
16366        return true;
16367    }
16368
16369    /**
16370     * Modifies the input matrix such that it maps view-local coordinates to
16371     * on-screen coordinates.
16372     *
16373     * @param m input matrix to modify
16374     */
16375    void transformMatrixToGlobal(Matrix m) {
16376        final ViewParent parent = mParent;
16377        if (parent instanceof View) {
16378            final View vp = (View) parent;
16379            vp.transformMatrixToGlobal(m);
16380            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16381        } else if (parent instanceof ViewRootImpl) {
16382            final ViewRootImpl vr = (ViewRootImpl) parent;
16383            vr.transformMatrixToGlobal(m);
16384            m.postTranslate(0, -vr.mCurScrollY);
16385        }
16386
16387        m.postTranslate(mLeft, mTop);
16388
16389        if (!hasIdentityMatrix()) {
16390            m.postConcat(getMatrix());
16391        }
16392    }
16393
16394    /**
16395     * Modifies the input matrix such that it maps on-screen coordinates to
16396     * view-local coordinates.
16397     *
16398     * @param m input matrix to modify
16399     */
16400    void transformMatrixToLocal(Matrix m) {
16401        final ViewParent parent = mParent;
16402        if (parent instanceof View) {
16403            final View vp = (View) parent;
16404            vp.transformMatrixToLocal(m);
16405            m.preTranslate(vp.mScrollX, vp.mScrollY);
16406        } else if (parent instanceof ViewRootImpl) {
16407            final ViewRootImpl vr = (ViewRootImpl) parent;
16408            vr.transformMatrixToLocal(m);
16409            m.preTranslate(0, vr.mCurScrollY);
16410        }
16411
16412        m.preTranslate(-mLeft, -mTop);
16413
16414        if (!hasIdentityMatrix()) {
16415            m.preConcat(getInverseMatrix());
16416        }
16417    }
16418
16419    /**
16420     * <p>Computes the coordinates of this view on the screen. The argument
16421     * must be an array of two integers. After the method returns, the array
16422     * contains the x and y location in that order.</p>
16423     *
16424     * @param location an array of two integers in which to hold the coordinates
16425     */
16426    public void getLocationOnScreen(int[] location) {
16427        getLocationInWindow(location);
16428
16429        final AttachInfo info = mAttachInfo;
16430        if (info != null) {
16431            location[0] += info.mWindowLeft;
16432            location[1] += info.mWindowTop;
16433        }
16434    }
16435
16436    /**
16437     * <p>Computes the coordinates of this view in its window. The argument
16438     * must be an array of two integers. After the method returns, the array
16439     * contains the x and y location in that order.</p>
16440     *
16441     * @param location an array of two integers in which to hold the coordinates
16442     */
16443    public void getLocationInWindow(int[] location) {
16444        if (location == null || location.length < 2) {
16445            throw new IllegalArgumentException("location must be an array of two integers");
16446        }
16447
16448        if (mAttachInfo == null) {
16449            // When the view is not attached to a window, this method does not make sense
16450            location[0] = location[1] = 0;
16451            return;
16452        }
16453
16454        float[] position = mAttachInfo.mTmpTransformLocation;
16455        position[0] = position[1] = 0.0f;
16456
16457        if (!hasIdentityMatrix()) {
16458            getMatrix().mapPoints(position);
16459        }
16460
16461        position[0] += mLeft;
16462        position[1] += mTop;
16463
16464        ViewParent viewParent = mParent;
16465        while (viewParent instanceof View) {
16466            final View view = (View) viewParent;
16467
16468            position[0] -= view.mScrollX;
16469            position[1] -= view.mScrollY;
16470
16471            if (!view.hasIdentityMatrix()) {
16472                view.getMatrix().mapPoints(position);
16473            }
16474
16475            position[0] += view.mLeft;
16476            position[1] += view.mTop;
16477
16478            viewParent = view.mParent;
16479         }
16480
16481        if (viewParent instanceof ViewRootImpl) {
16482            // *cough*
16483            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16484            position[1] -= vr.mCurScrollY;
16485        }
16486
16487        location[0] = (int) (position[0] + 0.5f);
16488        location[1] = (int) (position[1] + 0.5f);
16489    }
16490
16491    /**
16492     * {@hide}
16493     * @param id the id of the view to be found
16494     * @return the view of the specified id, null if cannot be found
16495     */
16496    protected View findViewTraversal(int id) {
16497        if (id == mID) {
16498            return this;
16499        }
16500        return null;
16501    }
16502
16503    /**
16504     * {@hide}
16505     * @param tag the tag of the view to be found
16506     * @return the view of specified tag, null if cannot be found
16507     */
16508    protected View findViewWithTagTraversal(Object tag) {
16509        if (tag != null && tag.equals(mTag)) {
16510            return this;
16511        }
16512        return null;
16513    }
16514
16515    /**
16516     * {@hide}
16517     * @param predicate The predicate to evaluate.
16518     * @param childToSkip If not null, ignores this child during the recursive traversal.
16519     * @return The first view that matches the predicate or null.
16520     */
16521    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16522        if (predicate.apply(this)) {
16523            return this;
16524        }
16525        return null;
16526    }
16527
16528    /**
16529     * Look for a child view with the given id.  If this view has the given
16530     * id, return this view.
16531     *
16532     * @param id The id to search for.
16533     * @return The view that has the given id in the hierarchy or null
16534     */
16535    public final View findViewById(int id) {
16536        if (id < 0) {
16537            return null;
16538        }
16539        return findViewTraversal(id);
16540    }
16541
16542    /**
16543     * Finds a view by its unuque and stable accessibility id.
16544     *
16545     * @param accessibilityId The searched accessibility id.
16546     * @return The found view.
16547     */
16548    final View findViewByAccessibilityId(int accessibilityId) {
16549        if (accessibilityId < 0) {
16550            return null;
16551        }
16552        return findViewByAccessibilityIdTraversal(accessibilityId);
16553    }
16554
16555    /**
16556     * Performs the traversal to find a view by its unuque and stable accessibility id.
16557     *
16558     * <strong>Note:</strong>This method does not stop at the root namespace
16559     * boundary since the user can touch the screen at an arbitrary location
16560     * potentially crossing the root namespace bounday which will send an
16561     * accessibility event to accessibility services and they should be able
16562     * to obtain the event source. Also accessibility ids are guaranteed to be
16563     * unique in the window.
16564     *
16565     * @param accessibilityId The accessibility id.
16566     * @return The found view.
16567     *
16568     * @hide
16569     */
16570    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16571        if (getAccessibilityViewId() == accessibilityId) {
16572            return this;
16573        }
16574        return null;
16575    }
16576
16577    /**
16578     * Look for a child view with the given tag.  If this view has the given
16579     * tag, return this view.
16580     *
16581     * @param tag The tag to search for, using "tag.equals(getTag())".
16582     * @return The View that has the given tag in the hierarchy or null
16583     */
16584    public final View findViewWithTag(Object tag) {
16585        if (tag == null) {
16586            return null;
16587        }
16588        return findViewWithTagTraversal(tag);
16589    }
16590
16591    /**
16592     * {@hide}
16593     * Look for a child view that matches the specified predicate.
16594     * If this view matches the predicate, return this view.
16595     *
16596     * @param predicate The predicate to evaluate.
16597     * @return The first view that matches the predicate or null.
16598     */
16599    public final View findViewByPredicate(Predicate<View> predicate) {
16600        return findViewByPredicateTraversal(predicate, null);
16601    }
16602
16603    /**
16604     * {@hide}
16605     * Look for a child view that matches the specified predicate,
16606     * starting with the specified view and its descendents and then
16607     * recusively searching the ancestors and siblings of that view
16608     * until this view is reached.
16609     *
16610     * This method is useful in cases where the predicate does not match
16611     * a single unique view (perhaps multiple views use the same id)
16612     * and we are trying to find the view that is "closest" in scope to the
16613     * starting view.
16614     *
16615     * @param start The view to start from.
16616     * @param predicate The predicate to evaluate.
16617     * @return The first view that matches the predicate or null.
16618     */
16619    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16620        View childToSkip = null;
16621        for (;;) {
16622            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16623            if (view != null || start == this) {
16624                return view;
16625            }
16626
16627            ViewParent parent = start.getParent();
16628            if (parent == null || !(parent instanceof View)) {
16629                return null;
16630            }
16631
16632            childToSkip = start;
16633            start = (View) parent;
16634        }
16635    }
16636
16637    /**
16638     * Sets the identifier for this view. The identifier does not have to be
16639     * unique in this view's hierarchy. The identifier should be a positive
16640     * number.
16641     *
16642     * @see #NO_ID
16643     * @see #getId()
16644     * @see #findViewById(int)
16645     *
16646     * @param id a number used to identify the view
16647     *
16648     * @attr ref android.R.styleable#View_id
16649     */
16650    public void setId(int id) {
16651        mID = id;
16652        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16653            mID = generateViewId();
16654        }
16655    }
16656
16657    /**
16658     * {@hide}
16659     *
16660     * @param isRoot true if the view belongs to the root namespace, false
16661     *        otherwise
16662     */
16663    public void setIsRootNamespace(boolean isRoot) {
16664        if (isRoot) {
16665            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16666        } else {
16667            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16668        }
16669    }
16670
16671    /**
16672     * {@hide}
16673     *
16674     * @return true if the view belongs to the root namespace, false otherwise
16675     */
16676    public boolean isRootNamespace() {
16677        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16678    }
16679
16680    /**
16681     * Returns this view's identifier.
16682     *
16683     * @return a positive integer used to identify the view or {@link #NO_ID}
16684     *         if the view has no ID
16685     *
16686     * @see #setId(int)
16687     * @see #findViewById(int)
16688     * @attr ref android.R.styleable#View_id
16689     */
16690    @ViewDebug.CapturedViewProperty
16691    public int getId() {
16692        return mID;
16693    }
16694
16695    /**
16696     * Returns this view's tag.
16697     *
16698     * @return the Object stored in this view as a tag, or {@code null} if not
16699     *         set
16700     *
16701     * @see #setTag(Object)
16702     * @see #getTag(int)
16703     */
16704    @ViewDebug.ExportedProperty
16705    public Object getTag() {
16706        return mTag;
16707    }
16708
16709    /**
16710     * Sets the tag associated with this view. A tag can be used to mark
16711     * a view in its hierarchy and does not have to be unique within the
16712     * hierarchy. Tags can also be used to store data within a view without
16713     * resorting to another data structure.
16714     *
16715     * @param tag an Object to tag the view with
16716     *
16717     * @see #getTag()
16718     * @see #setTag(int, Object)
16719     */
16720    public void setTag(final Object tag) {
16721        mTag = tag;
16722    }
16723
16724    /**
16725     * Returns the tag associated with this view and the specified key.
16726     *
16727     * @param key The key identifying the tag
16728     *
16729     * @return the Object stored in this view as a tag, or {@code null} if not
16730     *         set
16731     *
16732     * @see #setTag(int, Object)
16733     * @see #getTag()
16734     */
16735    public Object getTag(int key) {
16736        if (mKeyedTags != null) return mKeyedTags.get(key);
16737        return null;
16738    }
16739
16740    /**
16741     * Sets a tag associated with this view and a key. A tag can be used
16742     * to mark a view in its hierarchy and does not have to be unique within
16743     * the hierarchy. Tags can also be used to store data within a view
16744     * without resorting to another data structure.
16745     *
16746     * The specified key should be an id declared in the resources of the
16747     * application to ensure it is unique (see the <a
16748     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16749     * Keys identified as belonging to
16750     * the Android framework or not associated with any package will cause
16751     * an {@link IllegalArgumentException} to be thrown.
16752     *
16753     * @param key The key identifying the tag
16754     * @param tag An Object to tag the view with
16755     *
16756     * @throws IllegalArgumentException If they specified key is not valid
16757     *
16758     * @see #setTag(Object)
16759     * @see #getTag(int)
16760     */
16761    public void setTag(int key, final Object tag) {
16762        // If the package id is 0x00 or 0x01, it's either an undefined package
16763        // or a framework id
16764        if ((key >>> 24) < 2) {
16765            throw new IllegalArgumentException("The key must be an application-specific "
16766                    + "resource id.");
16767        }
16768
16769        setKeyedTag(key, tag);
16770    }
16771
16772    /**
16773     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16774     * framework id.
16775     *
16776     * @hide
16777     */
16778    public void setTagInternal(int key, Object tag) {
16779        if ((key >>> 24) != 0x1) {
16780            throw new IllegalArgumentException("The key must be a framework-specific "
16781                    + "resource id.");
16782        }
16783
16784        setKeyedTag(key, tag);
16785    }
16786
16787    private void setKeyedTag(int key, Object tag) {
16788        if (mKeyedTags == null) {
16789            mKeyedTags = new SparseArray<Object>(2);
16790        }
16791
16792        mKeyedTags.put(key, tag);
16793    }
16794
16795    /**
16796     * Prints information about this view in the log output, with the tag
16797     * {@link #VIEW_LOG_TAG}.
16798     *
16799     * @hide
16800     */
16801    public void debug() {
16802        debug(0);
16803    }
16804
16805    /**
16806     * Prints information about this view in the log output, with the tag
16807     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16808     * indentation defined by the <code>depth</code>.
16809     *
16810     * @param depth the indentation level
16811     *
16812     * @hide
16813     */
16814    protected void debug(int depth) {
16815        String output = debugIndent(depth - 1);
16816
16817        output += "+ " + this;
16818        int id = getId();
16819        if (id != -1) {
16820            output += " (id=" + id + ")";
16821        }
16822        Object tag = getTag();
16823        if (tag != null) {
16824            output += " (tag=" + tag + ")";
16825        }
16826        Log.d(VIEW_LOG_TAG, output);
16827
16828        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16829            output = debugIndent(depth) + " FOCUSED";
16830            Log.d(VIEW_LOG_TAG, output);
16831        }
16832
16833        output = debugIndent(depth);
16834        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16835                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16836                + "} ";
16837        Log.d(VIEW_LOG_TAG, output);
16838
16839        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16840                || mPaddingBottom != 0) {
16841            output = debugIndent(depth);
16842            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16843                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16844            Log.d(VIEW_LOG_TAG, output);
16845        }
16846
16847        output = debugIndent(depth);
16848        output += "mMeasureWidth=" + mMeasuredWidth +
16849                " mMeasureHeight=" + mMeasuredHeight;
16850        Log.d(VIEW_LOG_TAG, output);
16851
16852        output = debugIndent(depth);
16853        if (mLayoutParams == null) {
16854            output += "BAD! no layout params";
16855        } else {
16856            output = mLayoutParams.debug(output);
16857        }
16858        Log.d(VIEW_LOG_TAG, output);
16859
16860        output = debugIndent(depth);
16861        output += "flags={";
16862        output += View.printFlags(mViewFlags);
16863        output += "}";
16864        Log.d(VIEW_LOG_TAG, output);
16865
16866        output = debugIndent(depth);
16867        output += "privateFlags={";
16868        output += View.printPrivateFlags(mPrivateFlags);
16869        output += "}";
16870        Log.d(VIEW_LOG_TAG, output);
16871    }
16872
16873    /**
16874     * Creates a string of whitespaces used for indentation.
16875     *
16876     * @param depth the indentation level
16877     * @return a String containing (depth * 2 + 3) * 2 white spaces
16878     *
16879     * @hide
16880     */
16881    protected static String debugIndent(int depth) {
16882        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16883        for (int i = 0; i < (depth * 2) + 3; i++) {
16884            spaces.append(' ').append(' ');
16885        }
16886        return spaces.toString();
16887    }
16888
16889    /**
16890     * <p>Return the offset of the widget's text baseline from the widget's top
16891     * boundary. If this widget does not support baseline alignment, this
16892     * method returns -1. </p>
16893     *
16894     * @return the offset of the baseline within the widget's bounds or -1
16895     *         if baseline alignment is not supported
16896     */
16897    @ViewDebug.ExportedProperty(category = "layout")
16898    public int getBaseline() {
16899        return -1;
16900    }
16901
16902    /**
16903     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16904     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16905     * a layout pass.
16906     *
16907     * @return whether the view hierarchy is currently undergoing a layout pass
16908     */
16909    public boolean isInLayout() {
16910        ViewRootImpl viewRoot = getViewRootImpl();
16911        return (viewRoot != null && viewRoot.isInLayout());
16912    }
16913
16914    /**
16915     * Call this when something has changed which has invalidated the
16916     * layout of this view. This will schedule a layout pass of the view
16917     * tree. This should not be called while the view hierarchy is currently in a layout
16918     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16919     * end of the current layout pass (and then layout will run again) or after the current
16920     * frame is drawn and the next layout occurs.
16921     *
16922     * <p>Subclasses which override this method should call the superclass method to
16923     * handle possible request-during-layout errors correctly.</p>
16924     */
16925    public void requestLayout() {
16926        if (mMeasureCache != null) mMeasureCache.clear();
16927
16928        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16929            // Only trigger request-during-layout logic if this is the view requesting it,
16930            // not the views in its parent hierarchy
16931            ViewRootImpl viewRoot = getViewRootImpl();
16932            if (viewRoot != null && viewRoot.isInLayout()) {
16933                if (!viewRoot.requestLayoutDuringLayout(this)) {
16934                    return;
16935                }
16936            }
16937            mAttachInfo.mViewRequestingLayout = this;
16938        }
16939
16940        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16941        mPrivateFlags |= PFLAG_INVALIDATED;
16942
16943        if (mParent != null && !mParent.isLayoutRequested()) {
16944            mParent.requestLayout();
16945        }
16946        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16947            mAttachInfo.mViewRequestingLayout = null;
16948        }
16949    }
16950
16951    /**
16952     * Forces this view to be laid out during the next layout pass.
16953     * This method does not call requestLayout() or forceLayout()
16954     * on the parent.
16955     */
16956    public void forceLayout() {
16957        if (mMeasureCache != null) mMeasureCache.clear();
16958
16959        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16960        mPrivateFlags |= PFLAG_INVALIDATED;
16961    }
16962
16963    /**
16964     * <p>
16965     * This is called to find out how big a view should be. The parent
16966     * supplies constraint information in the width and height parameters.
16967     * </p>
16968     *
16969     * <p>
16970     * The actual measurement work of a view is performed in
16971     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16972     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16973     * </p>
16974     *
16975     *
16976     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16977     *        parent
16978     * @param heightMeasureSpec Vertical space requirements as imposed by the
16979     *        parent
16980     *
16981     * @see #onMeasure(int, int)
16982     */
16983    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16984        boolean optical = isLayoutModeOptical(this);
16985        if (optical != isLayoutModeOptical(mParent)) {
16986            Insets insets = getOpticalInsets();
16987            int oWidth  = insets.left + insets.right;
16988            int oHeight = insets.top  + insets.bottom;
16989            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16990            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16991        }
16992
16993        // Suppress sign extension for the low bytes
16994        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16995        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16996
16997        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16998                widthMeasureSpec != mOldWidthMeasureSpec ||
16999                heightMeasureSpec != mOldHeightMeasureSpec) {
17000
17001            // first clears the measured dimension flag
17002            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17003
17004            resolveRtlPropertiesIfNeeded();
17005
17006            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17007                    mMeasureCache.indexOfKey(key);
17008            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17009                // measure ourselves, this should set the measured dimension flag back
17010                onMeasure(widthMeasureSpec, heightMeasureSpec);
17011                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17012            } else {
17013                long value = mMeasureCache.valueAt(cacheIndex);
17014                // Casting a long to int drops the high 32 bits, no mask needed
17015                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17016                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17017            }
17018
17019            // flag not set, setMeasuredDimension() was not invoked, we raise
17020            // an exception to warn the developer
17021            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17022                throw new IllegalStateException("onMeasure() did not set the"
17023                        + " measured dimension by calling"
17024                        + " setMeasuredDimension()");
17025            }
17026
17027            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17028        }
17029
17030        mOldWidthMeasureSpec = widthMeasureSpec;
17031        mOldHeightMeasureSpec = heightMeasureSpec;
17032
17033        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17034                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17035    }
17036
17037    /**
17038     * <p>
17039     * Measure the view and its content to determine the measured width and the
17040     * measured height. This method is invoked by {@link #measure(int, int)} and
17041     * should be overriden by subclasses to provide accurate and efficient
17042     * measurement of their contents.
17043     * </p>
17044     *
17045     * <p>
17046     * <strong>CONTRACT:</strong> When overriding this method, you
17047     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17048     * measured width and height of this view. Failure to do so will trigger an
17049     * <code>IllegalStateException</code>, thrown by
17050     * {@link #measure(int, int)}. Calling the superclass'
17051     * {@link #onMeasure(int, int)} is a valid use.
17052     * </p>
17053     *
17054     * <p>
17055     * The base class implementation of measure defaults to the background size,
17056     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17057     * override {@link #onMeasure(int, int)} to provide better measurements of
17058     * their content.
17059     * </p>
17060     *
17061     * <p>
17062     * If this method is overridden, it is the subclass's responsibility to make
17063     * sure the measured height and width are at least the view's minimum height
17064     * and width ({@link #getSuggestedMinimumHeight()} and
17065     * {@link #getSuggestedMinimumWidth()}).
17066     * </p>
17067     *
17068     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17069     *                         The requirements are encoded with
17070     *                         {@link android.view.View.MeasureSpec}.
17071     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17072     *                         The requirements are encoded with
17073     *                         {@link android.view.View.MeasureSpec}.
17074     *
17075     * @see #getMeasuredWidth()
17076     * @see #getMeasuredHeight()
17077     * @see #setMeasuredDimension(int, int)
17078     * @see #getSuggestedMinimumHeight()
17079     * @see #getSuggestedMinimumWidth()
17080     * @see android.view.View.MeasureSpec#getMode(int)
17081     * @see android.view.View.MeasureSpec#getSize(int)
17082     */
17083    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17084        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17085                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17086    }
17087
17088    /**
17089     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17090     * measured width and measured height. Failing to do so will trigger an
17091     * exception at measurement time.</p>
17092     *
17093     * @param measuredWidth The measured width of this view.  May be a complex
17094     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17095     * {@link #MEASURED_STATE_TOO_SMALL}.
17096     * @param measuredHeight The measured height of this view.  May be a complex
17097     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17098     * {@link #MEASURED_STATE_TOO_SMALL}.
17099     */
17100    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17101        boolean optical = isLayoutModeOptical(this);
17102        if (optical != isLayoutModeOptical(mParent)) {
17103            Insets insets = getOpticalInsets();
17104            int opticalWidth  = insets.left + insets.right;
17105            int opticalHeight = insets.top  + insets.bottom;
17106
17107            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17108            measuredHeight += optical ? opticalHeight : -opticalHeight;
17109        }
17110        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17111    }
17112
17113    /**
17114     * Sets the measured dimension without extra processing for things like optical bounds.
17115     * Useful for reapplying consistent values that have already been cooked with adjustments
17116     * for optical bounds, etc. such as those from the measurement cache.
17117     *
17118     * @param measuredWidth The measured width of this view.  May be a complex
17119     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17120     * {@link #MEASURED_STATE_TOO_SMALL}.
17121     * @param measuredHeight The measured height of this view.  May be a complex
17122     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17123     * {@link #MEASURED_STATE_TOO_SMALL}.
17124     */
17125    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17126        mMeasuredWidth = measuredWidth;
17127        mMeasuredHeight = measuredHeight;
17128
17129        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17130    }
17131
17132    /**
17133     * Merge two states as returned by {@link #getMeasuredState()}.
17134     * @param curState The current state as returned from a view or the result
17135     * of combining multiple views.
17136     * @param newState The new view state to combine.
17137     * @return Returns a new integer reflecting the combination of the two
17138     * states.
17139     */
17140    public static int combineMeasuredStates(int curState, int newState) {
17141        return curState | newState;
17142    }
17143
17144    /**
17145     * Version of {@link #resolveSizeAndState(int, int, int)}
17146     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17147     */
17148    public static int resolveSize(int size, int measureSpec) {
17149        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17150    }
17151
17152    /**
17153     * Utility to reconcile a desired size and state, with constraints imposed
17154     * by a MeasureSpec.  Will take the desired size, unless a different size
17155     * is imposed by the constraints.  The returned value is a compound integer,
17156     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17157     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17158     * size is smaller than the size the view wants to be.
17159     *
17160     * @param size How big the view wants to be
17161     * @param measureSpec Constraints imposed by the parent
17162     * @return Size information bit mask as defined by
17163     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17164     */
17165    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17166        int result = size;
17167        int specMode = MeasureSpec.getMode(measureSpec);
17168        int specSize =  MeasureSpec.getSize(measureSpec);
17169        switch (specMode) {
17170        case MeasureSpec.UNSPECIFIED:
17171            result = size;
17172            break;
17173        case MeasureSpec.AT_MOST:
17174            if (specSize < size) {
17175                result = specSize | MEASURED_STATE_TOO_SMALL;
17176            } else {
17177                result = size;
17178            }
17179            break;
17180        case MeasureSpec.EXACTLY:
17181            result = specSize;
17182            break;
17183        }
17184        return result | (childMeasuredState&MEASURED_STATE_MASK);
17185    }
17186
17187    /**
17188     * Utility to return a default size. Uses the supplied size if the
17189     * MeasureSpec imposed no constraints. Will get larger if allowed
17190     * by the MeasureSpec.
17191     *
17192     * @param size Default size for this view
17193     * @param measureSpec Constraints imposed by the parent
17194     * @return The size this view should be.
17195     */
17196    public static int getDefaultSize(int size, int measureSpec) {
17197        int result = size;
17198        int specMode = MeasureSpec.getMode(measureSpec);
17199        int specSize = MeasureSpec.getSize(measureSpec);
17200
17201        switch (specMode) {
17202        case MeasureSpec.UNSPECIFIED:
17203            result = size;
17204            break;
17205        case MeasureSpec.AT_MOST:
17206        case MeasureSpec.EXACTLY:
17207            result = specSize;
17208            break;
17209        }
17210        return result;
17211    }
17212
17213    /**
17214     * Returns the suggested minimum height that the view should use. This
17215     * returns the maximum of the view's minimum height
17216     * and the background's minimum height
17217     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17218     * <p>
17219     * When being used in {@link #onMeasure(int, int)}, the caller should still
17220     * ensure the returned height is within the requirements of the parent.
17221     *
17222     * @return The suggested minimum height of the view.
17223     */
17224    protected int getSuggestedMinimumHeight() {
17225        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17226
17227    }
17228
17229    /**
17230     * Returns the suggested minimum width that the view should use. This
17231     * returns the maximum of the view's minimum width)
17232     * and the background's minimum width
17233     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17234     * <p>
17235     * When being used in {@link #onMeasure(int, int)}, the caller should still
17236     * ensure the returned width is within the requirements of the parent.
17237     *
17238     * @return The suggested minimum width of the view.
17239     */
17240    protected int getSuggestedMinimumWidth() {
17241        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17242    }
17243
17244    /**
17245     * Returns the minimum height of the view.
17246     *
17247     * @return the minimum height the view will try to be.
17248     *
17249     * @see #setMinimumHeight(int)
17250     *
17251     * @attr ref android.R.styleable#View_minHeight
17252     */
17253    public int getMinimumHeight() {
17254        return mMinHeight;
17255    }
17256
17257    /**
17258     * Sets the minimum height of the view. It is not guaranteed the view will
17259     * be able to achieve this minimum height (for example, if its parent layout
17260     * constrains it with less available height).
17261     *
17262     * @param minHeight The minimum height the view will try to be.
17263     *
17264     * @see #getMinimumHeight()
17265     *
17266     * @attr ref android.R.styleable#View_minHeight
17267     */
17268    public void setMinimumHeight(int minHeight) {
17269        mMinHeight = minHeight;
17270        requestLayout();
17271    }
17272
17273    /**
17274     * Returns the minimum width of the view.
17275     *
17276     * @return the minimum width the view will try to be.
17277     *
17278     * @see #setMinimumWidth(int)
17279     *
17280     * @attr ref android.R.styleable#View_minWidth
17281     */
17282    public int getMinimumWidth() {
17283        return mMinWidth;
17284    }
17285
17286    /**
17287     * Sets the minimum width of the view. It is not guaranteed the view will
17288     * be able to achieve this minimum width (for example, if its parent layout
17289     * constrains it with less available width).
17290     *
17291     * @param minWidth The minimum width the view will try to be.
17292     *
17293     * @see #getMinimumWidth()
17294     *
17295     * @attr ref android.R.styleable#View_minWidth
17296     */
17297    public void setMinimumWidth(int minWidth) {
17298        mMinWidth = minWidth;
17299        requestLayout();
17300
17301    }
17302
17303    /**
17304     * Get the animation currently associated with this view.
17305     *
17306     * @return The animation that is currently playing or
17307     *         scheduled to play for this view.
17308     */
17309    public Animation getAnimation() {
17310        return mCurrentAnimation;
17311    }
17312
17313    /**
17314     * Start the specified animation now.
17315     *
17316     * @param animation the animation to start now
17317     */
17318    public void startAnimation(Animation animation) {
17319        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17320        setAnimation(animation);
17321        invalidateParentCaches();
17322        invalidate(true);
17323    }
17324
17325    /**
17326     * Cancels any animations for this view.
17327     */
17328    public void clearAnimation() {
17329        if (mCurrentAnimation != null) {
17330            mCurrentAnimation.detach();
17331        }
17332        mCurrentAnimation = null;
17333        invalidateParentIfNeeded();
17334    }
17335
17336    /**
17337     * Sets the next animation to play for this view.
17338     * If you want the animation to play immediately, use
17339     * {@link #startAnimation(android.view.animation.Animation)} instead.
17340     * This method provides allows fine-grained
17341     * control over the start time and invalidation, but you
17342     * must make sure that 1) the animation has a start time set, and
17343     * 2) the view's parent (which controls animations on its children)
17344     * will be invalidated when the animation is supposed to
17345     * start.
17346     *
17347     * @param animation The next animation, or null.
17348     */
17349    public void setAnimation(Animation animation) {
17350        mCurrentAnimation = animation;
17351
17352        if (animation != null) {
17353            // If the screen is off assume the animation start time is now instead of
17354            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17355            // would cause the animation to start when the screen turns back on
17356            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17357                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17358                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17359            }
17360            animation.reset();
17361        }
17362    }
17363
17364    /**
17365     * Invoked by a parent ViewGroup to notify the start of the animation
17366     * currently associated with this view. If you override this method,
17367     * always call super.onAnimationStart();
17368     *
17369     * @see #setAnimation(android.view.animation.Animation)
17370     * @see #getAnimation()
17371     */
17372    protected void onAnimationStart() {
17373        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17374    }
17375
17376    /**
17377     * Invoked by a parent ViewGroup to notify the end of the animation
17378     * currently associated with this view. If you override this method,
17379     * always call super.onAnimationEnd();
17380     *
17381     * @see #setAnimation(android.view.animation.Animation)
17382     * @see #getAnimation()
17383     */
17384    protected void onAnimationEnd() {
17385        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17386    }
17387
17388    /**
17389     * Invoked if there is a Transform that involves alpha. Subclass that can
17390     * draw themselves with the specified alpha should return true, and then
17391     * respect that alpha when their onDraw() is called. If this returns false
17392     * then the view may be redirected to draw into an offscreen buffer to
17393     * fulfill the request, which will look fine, but may be slower than if the
17394     * subclass handles it internally. The default implementation returns false.
17395     *
17396     * @param alpha The alpha (0..255) to apply to the view's drawing
17397     * @return true if the view can draw with the specified alpha.
17398     */
17399    protected boolean onSetAlpha(int alpha) {
17400        return false;
17401    }
17402
17403    /**
17404     * This is used by the RootView to perform an optimization when
17405     * the view hierarchy contains one or several SurfaceView.
17406     * SurfaceView is always considered transparent, but its children are not,
17407     * therefore all View objects remove themselves from the global transparent
17408     * region (passed as a parameter to this function).
17409     *
17410     * @param region The transparent region for this ViewAncestor (window).
17411     *
17412     * @return Returns true if the effective visibility of the view at this
17413     * point is opaque, regardless of the transparent region; returns false
17414     * if it is possible for underlying windows to be seen behind the view.
17415     *
17416     * {@hide}
17417     */
17418    public boolean gatherTransparentRegion(Region region) {
17419        final AttachInfo attachInfo = mAttachInfo;
17420        if (region != null && attachInfo != null) {
17421            final int pflags = mPrivateFlags;
17422            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17423                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17424                // remove it from the transparent region.
17425                final int[] location = attachInfo.mTransparentLocation;
17426                getLocationInWindow(location);
17427                region.op(location[0], location[1], location[0] + mRight - mLeft,
17428                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17429            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17430                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17431                // exists, so we remove the background drawable's non-transparent
17432                // parts from this transparent region.
17433                applyDrawableToTransparentRegion(mBackground, region);
17434            }
17435        }
17436        return true;
17437    }
17438
17439    /**
17440     * Play a sound effect for this view.
17441     *
17442     * <p>The framework will play sound effects for some built in actions, such as
17443     * clicking, but you may wish to play these effects in your widget,
17444     * for instance, for internal navigation.
17445     *
17446     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17447     * {@link #isSoundEffectsEnabled()} is true.
17448     *
17449     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17450     */
17451    public void playSoundEffect(int soundConstant) {
17452        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17453            return;
17454        }
17455        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17456    }
17457
17458    /**
17459     * BZZZTT!!1!
17460     *
17461     * <p>Provide haptic feedback to the user for this view.
17462     *
17463     * <p>The framework will provide haptic feedback for some built in actions,
17464     * such as long presses, but you may wish to provide feedback for your
17465     * own widget.
17466     *
17467     * <p>The feedback will only be performed if
17468     * {@link #isHapticFeedbackEnabled()} is true.
17469     *
17470     * @param feedbackConstant One of the constants defined in
17471     * {@link HapticFeedbackConstants}
17472     */
17473    public boolean performHapticFeedback(int feedbackConstant) {
17474        return performHapticFeedback(feedbackConstant, 0);
17475    }
17476
17477    /**
17478     * BZZZTT!!1!
17479     *
17480     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17481     *
17482     * @param feedbackConstant One of the constants defined in
17483     * {@link HapticFeedbackConstants}
17484     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17485     */
17486    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17487        if (mAttachInfo == null) {
17488            return false;
17489        }
17490        //noinspection SimplifiableIfStatement
17491        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17492                && !isHapticFeedbackEnabled()) {
17493            return false;
17494        }
17495        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17496                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17497    }
17498
17499    /**
17500     * Request that the visibility of the status bar or other screen/window
17501     * decorations be changed.
17502     *
17503     * <p>This method is used to put the over device UI into temporary modes
17504     * where the user's attention is focused more on the application content,
17505     * by dimming or hiding surrounding system affordances.  This is typically
17506     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17507     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17508     * to be placed behind the action bar (and with these flags other system
17509     * affordances) so that smooth transitions between hiding and showing them
17510     * can be done.
17511     *
17512     * <p>Two representative examples of the use of system UI visibility is
17513     * implementing a content browsing application (like a magazine reader)
17514     * and a video playing application.
17515     *
17516     * <p>The first code shows a typical implementation of a View in a content
17517     * browsing application.  In this implementation, the application goes
17518     * into a content-oriented mode by hiding the status bar and action bar,
17519     * and putting the navigation elements into lights out mode.  The user can
17520     * then interact with content while in this mode.  Such an application should
17521     * provide an easy way for the user to toggle out of the mode (such as to
17522     * check information in the status bar or access notifications).  In the
17523     * implementation here, this is done simply by tapping on the content.
17524     *
17525     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17526     *      content}
17527     *
17528     * <p>This second code sample shows a typical implementation of a View
17529     * in a video playing application.  In this situation, while the video is
17530     * playing the application would like to go into a complete full-screen mode,
17531     * to use as much of the display as possible for the video.  When in this state
17532     * the user can not interact with the application; the system intercepts
17533     * touching on the screen to pop the UI out of full screen mode.  See
17534     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17535     *
17536     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17537     *      content}
17538     *
17539     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17540     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17541     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17542     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17543     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17544     */
17545    public void setSystemUiVisibility(int visibility) {
17546        if (visibility != mSystemUiVisibility) {
17547            mSystemUiVisibility = visibility;
17548            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17549                mParent.recomputeViewAttributes(this);
17550            }
17551        }
17552    }
17553
17554    /**
17555     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17556     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17557     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17558     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17559     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17560     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17561     */
17562    public int getSystemUiVisibility() {
17563        return mSystemUiVisibility;
17564    }
17565
17566    /**
17567     * Returns the current system UI visibility that is currently set for
17568     * the entire window.  This is the combination of the
17569     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17570     * views in the window.
17571     */
17572    public int getWindowSystemUiVisibility() {
17573        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17574    }
17575
17576    /**
17577     * Override to find out when the window's requested system UI visibility
17578     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17579     * This is different from the callbacks received through
17580     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17581     * in that this is only telling you about the local request of the window,
17582     * not the actual values applied by the system.
17583     */
17584    public void onWindowSystemUiVisibilityChanged(int visible) {
17585    }
17586
17587    /**
17588     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17589     * the view hierarchy.
17590     */
17591    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17592        onWindowSystemUiVisibilityChanged(visible);
17593    }
17594
17595    /**
17596     * Set a listener to receive callbacks when the visibility of the system bar changes.
17597     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17598     */
17599    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17600        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17601        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17602            mParent.recomputeViewAttributes(this);
17603        }
17604    }
17605
17606    /**
17607     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17608     * the view hierarchy.
17609     */
17610    public void dispatchSystemUiVisibilityChanged(int visibility) {
17611        ListenerInfo li = mListenerInfo;
17612        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17613            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17614                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17615        }
17616    }
17617
17618    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17619        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17620        if (val != mSystemUiVisibility) {
17621            setSystemUiVisibility(val);
17622            return true;
17623        }
17624        return false;
17625    }
17626
17627    /** @hide */
17628    public void setDisabledSystemUiVisibility(int flags) {
17629        if (mAttachInfo != null) {
17630            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17631                mAttachInfo.mDisabledSystemUiVisibility = flags;
17632                if (mParent != null) {
17633                    mParent.recomputeViewAttributes(this);
17634                }
17635            }
17636        }
17637    }
17638
17639    /**
17640     * Creates an image that the system displays during the drag and drop
17641     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17642     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17643     * appearance as the given View. The default also positions the center of the drag shadow
17644     * directly under the touch point. If no View is provided (the constructor with no parameters
17645     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17646     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17647     * default is an invisible drag shadow.
17648     * <p>
17649     * You are not required to use the View you provide to the constructor as the basis of the
17650     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17651     * anything you want as the drag shadow.
17652     * </p>
17653     * <p>
17654     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17655     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17656     *  size and position of the drag shadow. It uses this data to construct a
17657     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17658     *  so that your application can draw the shadow image in the Canvas.
17659     * </p>
17660     *
17661     * <div class="special reference">
17662     * <h3>Developer Guides</h3>
17663     * <p>For a guide to implementing drag and drop features, read the
17664     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17665     * </div>
17666     */
17667    public static class DragShadowBuilder {
17668        private final WeakReference<View> mView;
17669
17670        /**
17671         * Constructs a shadow image builder based on a View. By default, the resulting drag
17672         * shadow will have the same appearance and dimensions as the View, with the touch point
17673         * over the center of the View.
17674         * @param view A View. Any View in scope can be used.
17675         */
17676        public DragShadowBuilder(View view) {
17677            mView = new WeakReference<View>(view);
17678        }
17679
17680        /**
17681         * Construct a shadow builder object with no associated View.  This
17682         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17683         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17684         * to supply the drag shadow's dimensions and appearance without
17685         * reference to any View object. If they are not overridden, then the result is an
17686         * invisible drag shadow.
17687         */
17688        public DragShadowBuilder() {
17689            mView = new WeakReference<View>(null);
17690        }
17691
17692        /**
17693         * Returns the View object that had been passed to the
17694         * {@link #View.DragShadowBuilder(View)}
17695         * constructor.  If that View parameter was {@code null} or if the
17696         * {@link #View.DragShadowBuilder()}
17697         * constructor was used to instantiate the builder object, this method will return
17698         * null.
17699         *
17700         * @return The View object associate with this builder object.
17701         */
17702        @SuppressWarnings({"JavadocReference"})
17703        final public View getView() {
17704            return mView.get();
17705        }
17706
17707        /**
17708         * Provides the metrics for the shadow image. These include the dimensions of
17709         * the shadow image, and the point within that shadow that should
17710         * be centered under the touch location while dragging.
17711         * <p>
17712         * The default implementation sets the dimensions of the shadow to be the
17713         * same as the dimensions of the View itself and centers the shadow under
17714         * the touch point.
17715         * </p>
17716         *
17717         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17718         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17719         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17720         * image.
17721         *
17722         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17723         * shadow image that should be underneath the touch point during the drag and drop
17724         * operation. Your application must set {@link android.graphics.Point#x} to the
17725         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17726         */
17727        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17728            final View view = mView.get();
17729            if (view != null) {
17730                shadowSize.set(view.getWidth(), view.getHeight());
17731                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17732            } else {
17733                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17734            }
17735        }
17736
17737        /**
17738         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17739         * based on the dimensions it received from the
17740         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17741         *
17742         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17743         */
17744        public void onDrawShadow(Canvas canvas) {
17745            final View view = mView.get();
17746            if (view != null) {
17747                view.draw(canvas);
17748            } else {
17749                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17750            }
17751        }
17752    }
17753
17754    /**
17755     * Starts a drag and drop operation. When your application calls this method, it passes a
17756     * {@link android.view.View.DragShadowBuilder} object to the system. The
17757     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17758     * to get metrics for the drag shadow, and then calls the object's
17759     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17760     * <p>
17761     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17762     *  drag events to all the View objects in your application that are currently visible. It does
17763     *  this either by calling the View object's drag listener (an implementation of
17764     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17765     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17766     *  Both are passed a {@link android.view.DragEvent} object that has a
17767     *  {@link android.view.DragEvent#getAction()} value of
17768     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17769     * </p>
17770     * <p>
17771     * Your application can invoke startDrag() on any attached View object. The View object does not
17772     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17773     * be related to the View the user selected for dragging.
17774     * </p>
17775     * @param data A {@link android.content.ClipData} object pointing to the data to be
17776     * transferred by the drag and drop operation.
17777     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17778     * drag shadow.
17779     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17780     * drop operation. This Object is put into every DragEvent object sent by the system during the
17781     * current drag.
17782     * <p>
17783     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17784     * to the target Views. For example, it can contain flags that differentiate between a
17785     * a copy operation and a move operation.
17786     * </p>
17787     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17788     * so the parameter should be set to 0.
17789     * @return {@code true} if the method completes successfully, or
17790     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17791     * do a drag, and so no drag operation is in progress.
17792     */
17793    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17794            Object myLocalState, int flags) {
17795        if (ViewDebug.DEBUG_DRAG) {
17796            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17797        }
17798        boolean okay = false;
17799
17800        Point shadowSize = new Point();
17801        Point shadowTouchPoint = new Point();
17802        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17803
17804        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17805                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17806            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17807        }
17808
17809        if (ViewDebug.DEBUG_DRAG) {
17810            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17811                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17812        }
17813        Surface surface = new Surface();
17814        try {
17815            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17816                    flags, shadowSize.x, shadowSize.y, surface);
17817            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17818                    + " surface=" + surface);
17819            if (token != null) {
17820                Canvas canvas = surface.lockCanvas(null);
17821                try {
17822                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17823                    shadowBuilder.onDrawShadow(canvas);
17824                } finally {
17825                    surface.unlockCanvasAndPost(canvas);
17826                }
17827
17828                final ViewRootImpl root = getViewRootImpl();
17829
17830                // Cache the local state object for delivery with DragEvents
17831                root.setLocalDragState(myLocalState);
17832
17833                // repurpose 'shadowSize' for the last touch point
17834                root.getLastTouchPoint(shadowSize);
17835
17836                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17837                        shadowSize.x, shadowSize.y,
17838                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17839                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17840
17841                // Off and running!  Release our local surface instance; the drag
17842                // shadow surface is now managed by the system process.
17843                surface.release();
17844            }
17845        } catch (Exception e) {
17846            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17847            surface.destroy();
17848        }
17849
17850        return okay;
17851    }
17852
17853    /**
17854     * Handles drag events sent by the system following a call to
17855     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17856     *<p>
17857     * When the system calls this method, it passes a
17858     * {@link android.view.DragEvent} object. A call to
17859     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17860     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17861     * operation.
17862     * @param event The {@link android.view.DragEvent} sent by the system.
17863     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17864     * in DragEvent, indicating the type of drag event represented by this object.
17865     * @return {@code true} if the method was successful, otherwise {@code false}.
17866     * <p>
17867     *  The method should return {@code true} in response to an action type of
17868     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17869     *  operation.
17870     * </p>
17871     * <p>
17872     *  The method should also return {@code true} in response to an action type of
17873     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17874     *  {@code false} if it didn't.
17875     * </p>
17876     */
17877    public boolean onDragEvent(DragEvent event) {
17878        return false;
17879    }
17880
17881    /**
17882     * Detects if this View is enabled and has a drag event listener.
17883     * If both are true, then it calls the drag event listener with the
17884     * {@link android.view.DragEvent} it received. If the drag event listener returns
17885     * {@code true}, then dispatchDragEvent() returns {@code true}.
17886     * <p>
17887     * For all other cases, the method calls the
17888     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17889     * method and returns its result.
17890     * </p>
17891     * <p>
17892     * This ensures that a drag event is always consumed, even if the View does not have a drag
17893     * event listener. However, if the View has a listener and the listener returns true, then
17894     * onDragEvent() is not called.
17895     * </p>
17896     */
17897    public boolean dispatchDragEvent(DragEvent event) {
17898        ListenerInfo li = mListenerInfo;
17899        //noinspection SimplifiableIfStatement
17900        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17901                && li.mOnDragListener.onDrag(this, event)) {
17902            return true;
17903        }
17904        return onDragEvent(event);
17905    }
17906
17907    boolean canAcceptDrag() {
17908        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17909    }
17910
17911    /**
17912     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17913     * it is ever exposed at all.
17914     * @hide
17915     */
17916    public void onCloseSystemDialogs(String reason) {
17917    }
17918
17919    /**
17920     * Given a Drawable whose bounds have been set to draw into this view,
17921     * update a Region being computed for
17922     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17923     * that any non-transparent parts of the Drawable are removed from the
17924     * given transparent region.
17925     *
17926     * @param dr The Drawable whose transparency is to be applied to the region.
17927     * @param region A Region holding the current transparency information,
17928     * where any parts of the region that are set are considered to be
17929     * transparent.  On return, this region will be modified to have the
17930     * transparency information reduced by the corresponding parts of the
17931     * Drawable that are not transparent.
17932     * {@hide}
17933     */
17934    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17935        if (DBG) {
17936            Log.i("View", "Getting transparent region for: " + this);
17937        }
17938        final Region r = dr.getTransparentRegion();
17939        final Rect db = dr.getBounds();
17940        final AttachInfo attachInfo = mAttachInfo;
17941        if (r != null && attachInfo != null) {
17942            final int w = getRight()-getLeft();
17943            final int h = getBottom()-getTop();
17944            if (db.left > 0) {
17945                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17946                r.op(0, 0, db.left, h, Region.Op.UNION);
17947            }
17948            if (db.right < w) {
17949                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17950                r.op(db.right, 0, w, h, Region.Op.UNION);
17951            }
17952            if (db.top > 0) {
17953                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17954                r.op(0, 0, w, db.top, Region.Op.UNION);
17955            }
17956            if (db.bottom < h) {
17957                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17958                r.op(0, db.bottom, w, h, Region.Op.UNION);
17959            }
17960            final int[] location = attachInfo.mTransparentLocation;
17961            getLocationInWindow(location);
17962            r.translate(location[0], location[1]);
17963            region.op(r, Region.Op.INTERSECT);
17964        } else {
17965            region.op(db, Region.Op.DIFFERENCE);
17966        }
17967    }
17968
17969    private void checkForLongClick(int delayOffset) {
17970        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17971            mHasPerformedLongPress = false;
17972
17973            if (mPendingCheckForLongPress == null) {
17974                mPendingCheckForLongPress = new CheckForLongPress();
17975            }
17976            mPendingCheckForLongPress.rememberWindowAttachCount();
17977            postDelayed(mPendingCheckForLongPress,
17978                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17979        }
17980    }
17981
17982    /**
17983     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17984     * LayoutInflater} class, which provides a full range of options for view inflation.
17985     *
17986     * @param context The Context object for your activity or application.
17987     * @param resource The resource ID to inflate
17988     * @param root A view group that will be the parent.  Used to properly inflate the
17989     * layout_* parameters.
17990     * @see LayoutInflater
17991     */
17992    public static View inflate(Context context, int resource, ViewGroup root) {
17993        LayoutInflater factory = LayoutInflater.from(context);
17994        return factory.inflate(resource, root);
17995    }
17996
17997    /**
17998     * Scroll the view with standard behavior for scrolling beyond the normal
17999     * content boundaries. Views that call this method should override
18000     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18001     * results of an over-scroll operation.
18002     *
18003     * Views can use this method to handle any touch or fling-based scrolling.
18004     *
18005     * @param deltaX Change in X in pixels
18006     * @param deltaY Change in Y in pixels
18007     * @param scrollX Current X scroll value in pixels before applying deltaX
18008     * @param scrollY Current Y scroll value in pixels before applying deltaY
18009     * @param scrollRangeX Maximum content scroll range along the X axis
18010     * @param scrollRangeY Maximum content scroll range along the Y axis
18011     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18012     *          along the X axis.
18013     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18014     *          along the Y axis.
18015     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18016     * @return true if scrolling was clamped to an over-scroll boundary along either
18017     *          axis, false otherwise.
18018     */
18019    @SuppressWarnings({"UnusedParameters"})
18020    protected boolean overScrollBy(int deltaX, int deltaY,
18021            int scrollX, int scrollY,
18022            int scrollRangeX, int scrollRangeY,
18023            int maxOverScrollX, int maxOverScrollY,
18024            boolean isTouchEvent) {
18025        final int overScrollMode = mOverScrollMode;
18026        final boolean canScrollHorizontal =
18027                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18028        final boolean canScrollVertical =
18029                computeVerticalScrollRange() > computeVerticalScrollExtent();
18030        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18031                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18032        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18033                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18034
18035        int newScrollX = scrollX + deltaX;
18036        if (!overScrollHorizontal) {
18037            maxOverScrollX = 0;
18038        }
18039
18040        int newScrollY = scrollY + deltaY;
18041        if (!overScrollVertical) {
18042            maxOverScrollY = 0;
18043        }
18044
18045        // Clamp values if at the limits and record
18046        final int left = -maxOverScrollX;
18047        final int right = maxOverScrollX + scrollRangeX;
18048        final int top = -maxOverScrollY;
18049        final int bottom = maxOverScrollY + scrollRangeY;
18050
18051        boolean clampedX = false;
18052        if (newScrollX > right) {
18053            newScrollX = right;
18054            clampedX = true;
18055        } else if (newScrollX < left) {
18056            newScrollX = left;
18057            clampedX = true;
18058        }
18059
18060        boolean clampedY = false;
18061        if (newScrollY > bottom) {
18062            newScrollY = bottom;
18063            clampedY = true;
18064        } else if (newScrollY < top) {
18065            newScrollY = top;
18066            clampedY = true;
18067        }
18068
18069        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18070
18071        return clampedX || clampedY;
18072    }
18073
18074    /**
18075     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18076     * respond to the results of an over-scroll operation.
18077     *
18078     * @param scrollX New X scroll value in pixels
18079     * @param scrollY New Y scroll value in pixels
18080     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18081     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18082     */
18083    protected void onOverScrolled(int scrollX, int scrollY,
18084            boolean clampedX, boolean clampedY) {
18085        // Intentionally empty.
18086    }
18087
18088    /**
18089     * Returns the over-scroll mode for this view. The result will be
18090     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18091     * (allow over-scrolling only if the view content is larger than the container),
18092     * or {@link #OVER_SCROLL_NEVER}.
18093     *
18094     * @return This view's over-scroll mode.
18095     */
18096    public int getOverScrollMode() {
18097        return mOverScrollMode;
18098    }
18099
18100    /**
18101     * Set the over-scroll mode for this view. Valid over-scroll modes are
18102     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18103     * (allow over-scrolling only if the view content is larger than the container),
18104     * or {@link #OVER_SCROLL_NEVER}.
18105     *
18106     * Setting the over-scroll mode of a view will have an effect only if the
18107     * view is capable of scrolling.
18108     *
18109     * @param overScrollMode The new over-scroll mode for this view.
18110     */
18111    public void setOverScrollMode(int overScrollMode) {
18112        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18113                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18114                overScrollMode != OVER_SCROLL_NEVER) {
18115            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18116        }
18117        mOverScrollMode = overScrollMode;
18118    }
18119
18120    /**
18121     * Enable or disable nested scrolling for this view.
18122     *
18123     * <p>If this property is set to true the view will be permitted to initiate nested
18124     * scrolling operations with a compatible parent view in the current hierarchy. If this
18125     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18126     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18127     * the nested scroll.</p>
18128     *
18129     * @param enabled true to enable nested scrolling, false to disable
18130     *
18131     * @see #isNestedScrollingEnabled()
18132     */
18133    public void setNestedScrollingEnabled(boolean enabled) {
18134        if (enabled) {
18135            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18136        } else {
18137            stopNestedScroll();
18138            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18139        }
18140    }
18141
18142    /**
18143     * Returns true if nested scrolling is enabled for this view.
18144     *
18145     * <p>If nested scrolling is enabled and this View class implementation supports it,
18146     * this view will act as a nested scrolling child view when applicable, forwarding data
18147     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18148     * parent.</p>
18149     *
18150     * @return true if nested scrolling is enabled
18151     *
18152     * @see #setNestedScrollingEnabled(boolean)
18153     */
18154    public boolean isNestedScrollingEnabled() {
18155        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18156                PFLAG3_NESTED_SCROLLING_ENABLED;
18157    }
18158
18159    /**
18160     * Begin a nestable scroll operation along the given axes.
18161     *
18162     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18163     *
18164     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18165     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18166     * In the case of touch scrolling the nested scroll will be terminated automatically in
18167     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18168     * In the event of programmatic scrolling the caller must explicitly call
18169     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18170     *
18171     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18172     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18173     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18174     *
18175     * <p>At each incremental step of the scroll the caller should invoke
18176     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18177     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18178     * parent at least partially consumed the scroll and the caller should adjust the amount it
18179     * scrolls by.</p>
18180     *
18181     * <p>After applying the remainder of the scroll delta the caller should invoke
18182     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18183     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18184     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18185     * </p>
18186     *
18187     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18188     *             {@link #SCROLL_AXIS_VERTICAL}.
18189     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18190     *         the current gesture.
18191     *
18192     * @see #stopNestedScroll()
18193     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18194     * @see #dispatchNestedScroll(int, int, int, int, int[])
18195     */
18196    public boolean startNestedScroll(int axes) {
18197        if (hasNestedScrollingParent()) {
18198            // Already in progress
18199            return true;
18200        }
18201        if (isNestedScrollingEnabled()) {
18202            ViewParent p = getParent();
18203            View child = this;
18204            while (p != null) {
18205                try {
18206                    if (p.onStartNestedScroll(child, this, axes)) {
18207                        mNestedScrollingParent = p;
18208                        p.onNestedScrollAccepted(child, this, axes);
18209                        return true;
18210                    }
18211                } catch (AbstractMethodError e) {
18212                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18213                            "method onStartNestedScroll", e);
18214                    // Allow the search upward to continue
18215                }
18216                if (p instanceof View) {
18217                    child = (View) p;
18218                }
18219                p = p.getParent();
18220            }
18221        }
18222        return false;
18223    }
18224
18225    /**
18226     * Stop a nested scroll in progress.
18227     *
18228     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18229     *
18230     * @see #startNestedScroll(int)
18231     */
18232    public void stopNestedScroll() {
18233        if (mNestedScrollingParent != null) {
18234            mNestedScrollingParent.onStopNestedScroll(this);
18235            mNestedScrollingParent = null;
18236        }
18237    }
18238
18239    /**
18240     * Returns true if this view has a nested scrolling parent.
18241     *
18242     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18243     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18244     *
18245     * @return whether this view has a nested scrolling parent
18246     */
18247    public boolean hasNestedScrollingParent() {
18248        return mNestedScrollingParent != null;
18249    }
18250
18251    /**
18252     * Dispatch one step of a nested scroll in progress.
18253     *
18254     * <p>Implementations of views that support nested scrolling should call this to report
18255     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18256     * is not currently in progress or nested scrolling is not
18257     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18258     *
18259     * <p>Compatible View implementations should also call
18260     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18261     * consuming a component of the scroll event themselves.</p>
18262     *
18263     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18264     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18265     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18266     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18267     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18268     *                       in local view coordinates of this view from before this operation
18269     *                       to after it completes. View implementations may use this to adjust
18270     *                       expected input coordinate tracking.
18271     * @return true if the event was dispatched, false if it could not be dispatched.
18272     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18273     */
18274    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18275            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18276        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18277            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18278                int startX = 0;
18279                int startY = 0;
18280                if (offsetInWindow != null) {
18281                    getLocationInWindow(offsetInWindow);
18282                    startX = offsetInWindow[0];
18283                    startY = offsetInWindow[1];
18284                }
18285
18286                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18287                        dxUnconsumed, dyUnconsumed);
18288
18289                if (offsetInWindow != null) {
18290                    getLocationInWindow(offsetInWindow);
18291                    offsetInWindow[0] -= startX;
18292                    offsetInWindow[1] -= startY;
18293                }
18294                return true;
18295            } else if (offsetInWindow != null) {
18296                // No motion, no dispatch. Keep offsetInWindow up to date.
18297                offsetInWindow[0] = 0;
18298                offsetInWindow[1] = 0;
18299            }
18300        }
18301        return false;
18302    }
18303
18304    /**
18305     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18306     *
18307     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18308     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18309     * scrolling operation to consume some or all of the scroll operation before the child view
18310     * consumes it.</p>
18311     *
18312     * @param dx Horizontal scroll distance in pixels
18313     * @param dy Vertical scroll distance in pixels
18314     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18315     *                 and consumed[1] the consumed dy.
18316     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18317     *                       in local view coordinates of this view from before this operation
18318     *                       to after it completes. View implementations may use this to adjust
18319     *                       expected input coordinate tracking.
18320     * @return true if the parent consumed some or all of the scroll delta
18321     * @see #dispatchNestedScroll(int, int, int, int, int[])
18322     */
18323    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18324        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18325            if (dx != 0 || dy != 0) {
18326                int startX = 0;
18327                int startY = 0;
18328                if (offsetInWindow != null) {
18329                    getLocationInWindow(offsetInWindow);
18330                    startX = offsetInWindow[0];
18331                    startY = offsetInWindow[1];
18332                }
18333
18334                if (consumed == null) {
18335                    if (mTempNestedScrollConsumed == null) {
18336                        mTempNestedScrollConsumed = new int[2];
18337                    }
18338                    consumed = mTempNestedScrollConsumed;
18339                }
18340                consumed[0] = 0;
18341                consumed[1] = 0;
18342                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18343
18344                if (offsetInWindow != null) {
18345                    getLocationInWindow(offsetInWindow);
18346                    offsetInWindow[0] -= startX;
18347                    offsetInWindow[1] -= startY;
18348                }
18349                return consumed[0] != 0 || consumed[1] != 0;
18350            } else if (offsetInWindow != null) {
18351                offsetInWindow[0] = 0;
18352                offsetInWindow[1] = 0;
18353            }
18354        }
18355        return false;
18356    }
18357
18358    /**
18359     * Dispatch a fling to a nested scrolling parent.
18360     *
18361     * <p>This method should be used to indicate that a nested scrolling child has detected
18362     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18363     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18364     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18365     * along a scrollable axis.</p>
18366     *
18367     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18368     * its own content, it can use this method to delegate the fling to its nested scrolling
18369     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18370     *
18371     * @param velocityX Horizontal fling velocity in pixels per second
18372     * @param velocityY Vertical fling velocity in pixels per second
18373     * @param consumed true if the child consumed the fling, false otherwise
18374     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18375     */
18376    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18377        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18378            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18379        }
18380        return false;
18381    }
18382
18383    /**
18384     * Gets a scale factor that determines the distance the view should scroll
18385     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18386     * @return The vertical scroll scale factor.
18387     * @hide
18388     */
18389    protected float getVerticalScrollFactor() {
18390        if (mVerticalScrollFactor == 0) {
18391            TypedValue outValue = new TypedValue();
18392            if (!mContext.getTheme().resolveAttribute(
18393                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18394                throw new IllegalStateException(
18395                        "Expected theme to define listPreferredItemHeight.");
18396            }
18397            mVerticalScrollFactor = outValue.getDimension(
18398                    mContext.getResources().getDisplayMetrics());
18399        }
18400        return mVerticalScrollFactor;
18401    }
18402
18403    /**
18404     * Gets a scale factor that determines the distance the view should scroll
18405     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18406     * @return The horizontal scroll scale factor.
18407     * @hide
18408     */
18409    protected float getHorizontalScrollFactor() {
18410        // TODO: Should use something else.
18411        return getVerticalScrollFactor();
18412    }
18413
18414    /**
18415     * Return the value specifying the text direction or policy that was set with
18416     * {@link #setTextDirection(int)}.
18417     *
18418     * @return the defined text direction. It can be one of:
18419     *
18420     * {@link #TEXT_DIRECTION_INHERIT},
18421     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18422     * {@link #TEXT_DIRECTION_ANY_RTL},
18423     * {@link #TEXT_DIRECTION_LTR},
18424     * {@link #TEXT_DIRECTION_RTL},
18425     * {@link #TEXT_DIRECTION_LOCALE}
18426     *
18427     * @attr ref android.R.styleable#View_textDirection
18428     *
18429     * @hide
18430     */
18431    @ViewDebug.ExportedProperty(category = "text", mapping = {
18432            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18433            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18434            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18435            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18436            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18437            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18438    })
18439    public int getRawTextDirection() {
18440        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18441    }
18442
18443    /**
18444     * Set the text direction.
18445     *
18446     * @param textDirection the direction to set. Should be one of:
18447     *
18448     * {@link #TEXT_DIRECTION_INHERIT},
18449     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18450     * {@link #TEXT_DIRECTION_ANY_RTL},
18451     * {@link #TEXT_DIRECTION_LTR},
18452     * {@link #TEXT_DIRECTION_RTL},
18453     * {@link #TEXT_DIRECTION_LOCALE}
18454     *
18455     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18456     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18457     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18458     *
18459     * @attr ref android.R.styleable#View_textDirection
18460     */
18461    public void setTextDirection(int textDirection) {
18462        if (getRawTextDirection() != textDirection) {
18463            // Reset the current text direction and the resolved one
18464            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18465            resetResolvedTextDirection();
18466            // Set the new text direction
18467            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18468            // Do resolution
18469            resolveTextDirection();
18470            // Notify change
18471            onRtlPropertiesChanged(getLayoutDirection());
18472            // Refresh
18473            requestLayout();
18474            invalidate(true);
18475        }
18476    }
18477
18478    /**
18479     * Return the resolved text direction.
18480     *
18481     * @return the resolved text direction. Returns one of:
18482     *
18483     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18484     * {@link #TEXT_DIRECTION_ANY_RTL},
18485     * {@link #TEXT_DIRECTION_LTR},
18486     * {@link #TEXT_DIRECTION_RTL},
18487     * {@link #TEXT_DIRECTION_LOCALE}
18488     *
18489     * @attr ref android.R.styleable#View_textDirection
18490     */
18491    @ViewDebug.ExportedProperty(category = "text", mapping = {
18492            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18493            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18494            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18495            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18496            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18497            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18498    })
18499    public int getTextDirection() {
18500        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18501    }
18502
18503    /**
18504     * Resolve the text direction.
18505     *
18506     * @return true if resolution has been done, false otherwise.
18507     *
18508     * @hide
18509     */
18510    public boolean resolveTextDirection() {
18511        // Reset any previous text direction resolution
18512        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18513
18514        if (hasRtlSupport()) {
18515            // Set resolved text direction flag depending on text direction flag
18516            final int textDirection = getRawTextDirection();
18517            switch(textDirection) {
18518                case TEXT_DIRECTION_INHERIT:
18519                    if (!canResolveTextDirection()) {
18520                        // We cannot do the resolution if there is no parent, so use the default one
18521                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18522                        // Resolution will need to happen again later
18523                        return false;
18524                    }
18525
18526                    // Parent has not yet resolved, so we still return the default
18527                    try {
18528                        if (!mParent.isTextDirectionResolved()) {
18529                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18530                            // Resolution will need to happen again later
18531                            return false;
18532                        }
18533                    } catch (AbstractMethodError e) {
18534                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18535                                " does not fully implement ViewParent", e);
18536                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18537                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18538                        return true;
18539                    }
18540
18541                    // Set current resolved direction to the same value as the parent's one
18542                    int parentResolvedDirection;
18543                    try {
18544                        parentResolvedDirection = mParent.getTextDirection();
18545                    } catch (AbstractMethodError e) {
18546                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18547                                " does not fully implement ViewParent", e);
18548                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18549                    }
18550                    switch (parentResolvedDirection) {
18551                        case TEXT_DIRECTION_FIRST_STRONG:
18552                        case TEXT_DIRECTION_ANY_RTL:
18553                        case TEXT_DIRECTION_LTR:
18554                        case TEXT_DIRECTION_RTL:
18555                        case TEXT_DIRECTION_LOCALE:
18556                            mPrivateFlags2 |=
18557                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18558                            break;
18559                        default:
18560                            // Default resolved direction is "first strong" heuristic
18561                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18562                    }
18563                    break;
18564                case TEXT_DIRECTION_FIRST_STRONG:
18565                case TEXT_DIRECTION_ANY_RTL:
18566                case TEXT_DIRECTION_LTR:
18567                case TEXT_DIRECTION_RTL:
18568                case TEXT_DIRECTION_LOCALE:
18569                    // Resolved direction is the same as text direction
18570                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18571                    break;
18572                default:
18573                    // Default resolved direction is "first strong" heuristic
18574                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18575            }
18576        } else {
18577            // Default resolved direction is "first strong" heuristic
18578            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18579        }
18580
18581        // Set to resolved
18582        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18583        return true;
18584    }
18585
18586    /**
18587     * Check if text direction resolution can be done.
18588     *
18589     * @return true if text direction resolution can be done otherwise return false.
18590     */
18591    public boolean canResolveTextDirection() {
18592        switch (getRawTextDirection()) {
18593            case TEXT_DIRECTION_INHERIT:
18594                if (mParent != null) {
18595                    try {
18596                        return mParent.canResolveTextDirection();
18597                    } catch (AbstractMethodError e) {
18598                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18599                                " does not fully implement ViewParent", e);
18600                    }
18601                }
18602                return false;
18603
18604            default:
18605                return true;
18606        }
18607    }
18608
18609    /**
18610     * Reset resolved text direction. Text direction will be resolved during a call to
18611     * {@link #onMeasure(int, int)}.
18612     *
18613     * @hide
18614     */
18615    public void resetResolvedTextDirection() {
18616        // Reset any previous text direction resolution
18617        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18618        // Set to default value
18619        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18620    }
18621
18622    /**
18623     * @return true if text direction is inherited.
18624     *
18625     * @hide
18626     */
18627    public boolean isTextDirectionInherited() {
18628        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18629    }
18630
18631    /**
18632     * @return true if text direction is resolved.
18633     */
18634    public boolean isTextDirectionResolved() {
18635        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18636    }
18637
18638    /**
18639     * Return the value specifying the text alignment or policy that was set with
18640     * {@link #setTextAlignment(int)}.
18641     *
18642     * @return the defined text alignment. It can be one of:
18643     *
18644     * {@link #TEXT_ALIGNMENT_INHERIT},
18645     * {@link #TEXT_ALIGNMENT_GRAVITY},
18646     * {@link #TEXT_ALIGNMENT_CENTER},
18647     * {@link #TEXT_ALIGNMENT_TEXT_START},
18648     * {@link #TEXT_ALIGNMENT_TEXT_END},
18649     * {@link #TEXT_ALIGNMENT_VIEW_START},
18650     * {@link #TEXT_ALIGNMENT_VIEW_END}
18651     *
18652     * @attr ref android.R.styleable#View_textAlignment
18653     *
18654     * @hide
18655     */
18656    @ViewDebug.ExportedProperty(category = "text", mapping = {
18657            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18658            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18659            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18660            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18661            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18662            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18663            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18664    })
18665    @TextAlignment
18666    public int getRawTextAlignment() {
18667        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18668    }
18669
18670    /**
18671     * Set the text alignment.
18672     *
18673     * @param textAlignment The text alignment to set. Should be one of
18674     *
18675     * {@link #TEXT_ALIGNMENT_INHERIT},
18676     * {@link #TEXT_ALIGNMENT_GRAVITY},
18677     * {@link #TEXT_ALIGNMENT_CENTER},
18678     * {@link #TEXT_ALIGNMENT_TEXT_START},
18679     * {@link #TEXT_ALIGNMENT_TEXT_END},
18680     * {@link #TEXT_ALIGNMENT_VIEW_START},
18681     * {@link #TEXT_ALIGNMENT_VIEW_END}
18682     *
18683     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18684     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18685     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18686     *
18687     * @attr ref android.R.styleable#View_textAlignment
18688     */
18689    public void setTextAlignment(@TextAlignment int textAlignment) {
18690        if (textAlignment != getRawTextAlignment()) {
18691            // Reset the current and resolved text alignment
18692            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18693            resetResolvedTextAlignment();
18694            // Set the new text alignment
18695            mPrivateFlags2 |=
18696                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18697            // Do resolution
18698            resolveTextAlignment();
18699            // Notify change
18700            onRtlPropertiesChanged(getLayoutDirection());
18701            // Refresh
18702            requestLayout();
18703            invalidate(true);
18704        }
18705    }
18706
18707    /**
18708     * Return the resolved text alignment.
18709     *
18710     * @return the resolved text alignment. Returns one of:
18711     *
18712     * {@link #TEXT_ALIGNMENT_GRAVITY},
18713     * {@link #TEXT_ALIGNMENT_CENTER},
18714     * {@link #TEXT_ALIGNMENT_TEXT_START},
18715     * {@link #TEXT_ALIGNMENT_TEXT_END},
18716     * {@link #TEXT_ALIGNMENT_VIEW_START},
18717     * {@link #TEXT_ALIGNMENT_VIEW_END}
18718     *
18719     * @attr ref android.R.styleable#View_textAlignment
18720     */
18721    @ViewDebug.ExportedProperty(category = "text", mapping = {
18722            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18723            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18724            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18725            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18726            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18727            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18728            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18729    })
18730    @TextAlignment
18731    public int getTextAlignment() {
18732        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18733                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18734    }
18735
18736    /**
18737     * Resolve the text alignment.
18738     *
18739     * @return true if resolution has been done, false otherwise.
18740     *
18741     * @hide
18742     */
18743    public boolean resolveTextAlignment() {
18744        // Reset any previous text alignment resolution
18745        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18746
18747        if (hasRtlSupport()) {
18748            // Set resolved text alignment flag depending on text alignment flag
18749            final int textAlignment = getRawTextAlignment();
18750            switch (textAlignment) {
18751                case TEXT_ALIGNMENT_INHERIT:
18752                    // Check if we can resolve the text alignment
18753                    if (!canResolveTextAlignment()) {
18754                        // We cannot do the resolution if there is no parent so use the default
18755                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18756                        // Resolution will need to happen again later
18757                        return false;
18758                    }
18759
18760                    // Parent has not yet resolved, so we still return the default
18761                    try {
18762                        if (!mParent.isTextAlignmentResolved()) {
18763                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18764                            // Resolution will need to happen again later
18765                            return false;
18766                        }
18767                    } catch (AbstractMethodError e) {
18768                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18769                                " does not fully implement ViewParent", e);
18770                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18771                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18772                        return true;
18773                    }
18774
18775                    int parentResolvedTextAlignment;
18776                    try {
18777                        parentResolvedTextAlignment = mParent.getTextAlignment();
18778                    } catch (AbstractMethodError e) {
18779                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18780                                " does not fully implement ViewParent", e);
18781                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18782                    }
18783                    switch (parentResolvedTextAlignment) {
18784                        case TEXT_ALIGNMENT_GRAVITY:
18785                        case TEXT_ALIGNMENT_TEXT_START:
18786                        case TEXT_ALIGNMENT_TEXT_END:
18787                        case TEXT_ALIGNMENT_CENTER:
18788                        case TEXT_ALIGNMENT_VIEW_START:
18789                        case TEXT_ALIGNMENT_VIEW_END:
18790                            // Resolved text alignment is the same as the parent resolved
18791                            // text alignment
18792                            mPrivateFlags2 |=
18793                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18794                            break;
18795                        default:
18796                            // Use default resolved text alignment
18797                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18798                    }
18799                    break;
18800                case TEXT_ALIGNMENT_GRAVITY:
18801                case TEXT_ALIGNMENT_TEXT_START:
18802                case TEXT_ALIGNMENT_TEXT_END:
18803                case TEXT_ALIGNMENT_CENTER:
18804                case TEXT_ALIGNMENT_VIEW_START:
18805                case TEXT_ALIGNMENT_VIEW_END:
18806                    // Resolved text alignment is the same as text alignment
18807                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18808                    break;
18809                default:
18810                    // Use default resolved text alignment
18811                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18812            }
18813        } else {
18814            // Use default resolved text alignment
18815            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18816        }
18817
18818        // Set the resolved
18819        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18820        return true;
18821    }
18822
18823    /**
18824     * Check if text alignment resolution can be done.
18825     *
18826     * @return true if text alignment resolution can be done otherwise return false.
18827     */
18828    public boolean canResolveTextAlignment() {
18829        switch (getRawTextAlignment()) {
18830            case TEXT_DIRECTION_INHERIT:
18831                if (mParent != null) {
18832                    try {
18833                        return mParent.canResolveTextAlignment();
18834                    } catch (AbstractMethodError e) {
18835                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18836                                " does not fully implement ViewParent", e);
18837                    }
18838                }
18839                return false;
18840
18841            default:
18842                return true;
18843        }
18844    }
18845
18846    /**
18847     * Reset resolved text alignment. Text alignment will be resolved during a call to
18848     * {@link #onMeasure(int, int)}.
18849     *
18850     * @hide
18851     */
18852    public void resetResolvedTextAlignment() {
18853        // Reset any previous text alignment resolution
18854        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18855        // Set to default
18856        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18857    }
18858
18859    /**
18860     * @return true if text alignment is inherited.
18861     *
18862     * @hide
18863     */
18864    public boolean isTextAlignmentInherited() {
18865        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18866    }
18867
18868    /**
18869     * @return true if text alignment is resolved.
18870     */
18871    public boolean isTextAlignmentResolved() {
18872        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18873    }
18874
18875    /**
18876     * Generate a value suitable for use in {@link #setId(int)}.
18877     * This value will not collide with ID values generated at build time by aapt for R.id.
18878     *
18879     * @return a generated ID value
18880     */
18881    public static int generateViewId() {
18882        for (;;) {
18883            final int result = sNextGeneratedId.get();
18884            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18885            int newValue = result + 1;
18886            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18887            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18888                return result;
18889            }
18890        }
18891    }
18892
18893    /**
18894     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18895     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18896     *                           a normal View or a ViewGroup with
18897     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18898     * @hide
18899     */
18900    public void captureTransitioningViews(List<View> transitioningViews) {
18901        if (getVisibility() == View.VISIBLE) {
18902            transitioningViews.add(this);
18903        }
18904    }
18905
18906    /**
18907     * Adds all Views that have {@link #getViewName()} non-null to namedElements.
18908     * @param namedElements Will contain all Views in the hierarchy having a view name.
18909     * @hide
18910     */
18911    public void findNamedViews(Map<String, View> namedElements) {
18912        if (getVisibility() == VISIBLE) {
18913            String viewName = getViewName();
18914            if (viewName != null) {
18915                namedElements.put(viewName, this);
18916            }
18917        }
18918    }
18919
18920    //
18921    // Properties
18922    //
18923    /**
18924     * A Property wrapper around the <code>alpha</code> functionality handled by the
18925     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18926     */
18927    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18928        @Override
18929        public void setValue(View object, float value) {
18930            object.setAlpha(value);
18931        }
18932
18933        @Override
18934        public Float get(View object) {
18935            return object.getAlpha();
18936        }
18937    };
18938
18939    /**
18940     * A Property wrapper around the <code>translationX</code> functionality handled by the
18941     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18942     */
18943    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18944        @Override
18945        public void setValue(View object, float value) {
18946            object.setTranslationX(value);
18947        }
18948
18949                @Override
18950        public Float get(View object) {
18951            return object.getTranslationX();
18952        }
18953    };
18954
18955    /**
18956     * A Property wrapper around the <code>translationY</code> functionality handled by the
18957     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18958     */
18959    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18960        @Override
18961        public void setValue(View object, float value) {
18962            object.setTranslationY(value);
18963        }
18964
18965        @Override
18966        public Float get(View object) {
18967            return object.getTranslationY();
18968        }
18969    };
18970
18971    /**
18972     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18973     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18974     */
18975    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18976        @Override
18977        public void setValue(View object, float value) {
18978            object.setTranslationZ(value);
18979        }
18980
18981        @Override
18982        public Float get(View object) {
18983            return object.getTranslationZ();
18984        }
18985    };
18986
18987    /**
18988     * A Property wrapper around the <code>x</code> functionality handled by the
18989     * {@link View#setX(float)} and {@link View#getX()} methods.
18990     */
18991    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18992        @Override
18993        public void setValue(View object, float value) {
18994            object.setX(value);
18995        }
18996
18997        @Override
18998        public Float get(View object) {
18999            return object.getX();
19000        }
19001    };
19002
19003    /**
19004     * A Property wrapper around the <code>y</code> functionality handled by the
19005     * {@link View#setY(float)} and {@link View#getY()} methods.
19006     */
19007    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19008        @Override
19009        public void setValue(View object, float value) {
19010            object.setY(value);
19011        }
19012
19013        @Override
19014        public Float get(View object) {
19015            return object.getY();
19016        }
19017    };
19018
19019    /**
19020     * A Property wrapper around the <code>z</code> functionality handled by the
19021     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19022     */
19023    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19024        @Override
19025        public void setValue(View object, float value) {
19026            object.setZ(value);
19027        }
19028
19029        @Override
19030        public Float get(View object) {
19031            return object.getZ();
19032        }
19033    };
19034
19035    /**
19036     * A Property wrapper around the <code>rotation</code> functionality handled by the
19037     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19038     */
19039    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19040        @Override
19041        public void setValue(View object, float value) {
19042            object.setRotation(value);
19043        }
19044
19045        @Override
19046        public Float get(View object) {
19047            return object.getRotation();
19048        }
19049    };
19050
19051    /**
19052     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19053     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19054     */
19055    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19056        @Override
19057        public void setValue(View object, float value) {
19058            object.setRotationX(value);
19059        }
19060
19061        @Override
19062        public Float get(View object) {
19063            return object.getRotationX();
19064        }
19065    };
19066
19067    /**
19068     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19069     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19070     */
19071    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19072        @Override
19073        public void setValue(View object, float value) {
19074            object.setRotationY(value);
19075        }
19076
19077        @Override
19078        public Float get(View object) {
19079            return object.getRotationY();
19080        }
19081    };
19082
19083    /**
19084     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19085     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19086     */
19087    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19088        @Override
19089        public void setValue(View object, float value) {
19090            object.setScaleX(value);
19091        }
19092
19093        @Override
19094        public Float get(View object) {
19095            return object.getScaleX();
19096        }
19097    };
19098
19099    /**
19100     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19101     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19102     */
19103    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19104        @Override
19105        public void setValue(View object, float value) {
19106            object.setScaleY(value);
19107        }
19108
19109        @Override
19110        public Float get(View object) {
19111            return object.getScaleY();
19112        }
19113    };
19114
19115    /**
19116     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19117     * Each MeasureSpec represents a requirement for either the width or the height.
19118     * A MeasureSpec is comprised of a size and a mode. There are three possible
19119     * modes:
19120     * <dl>
19121     * <dt>UNSPECIFIED</dt>
19122     * <dd>
19123     * The parent has not imposed any constraint on the child. It can be whatever size
19124     * it wants.
19125     * </dd>
19126     *
19127     * <dt>EXACTLY</dt>
19128     * <dd>
19129     * The parent has determined an exact size for the child. The child is going to be
19130     * given those bounds regardless of how big it wants to be.
19131     * </dd>
19132     *
19133     * <dt>AT_MOST</dt>
19134     * <dd>
19135     * The child can be as large as it wants up to the specified size.
19136     * </dd>
19137     * </dl>
19138     *
19139     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19140     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19141     */
19142    public static class MeasureSpec {
19143        private static final int MODE_SHIFT = 30;
19144        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19145
19146        /**
19147         * Measure specification mode: The parent has not imposed any constraint
19148         * on the child. It can be whatever size it wants.
19149         */
19150        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19151
19152        /**
19153         * Measure specification mode: The parent has determined an exact size
19154         * for the child. The child is going to be given those bounds regardless
19155         * of how big it wants to be.
19156         */
19157        public static final int EXACTLY     = 1 << MODE_SHIFT;
19158
19159        /**
19160         * Measure specification mode: The child can be as large as it wants up
19161         * to the specified size.
19162         */
19163        public static final int AT_MOST     = 2 << MODE_SHIFT;
19164
19165        /**
19166         * Creates a measure specification based on the supplied size and mode.
19167         *
19168         * The mode must always be one of the following:
19169         * <ul>
19170         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19171         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19172         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19173         * </ul>
19174         *
19175         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19176         * implementation was such that the order of arguments did not matter
19177         * and overflow in either value could impact the resulting MeasureSpec.
19178         * {@link android.widget.RelativeLayout} was affected by this bug.
19179         * Apps targeting API levels greater than 17 will get the fixed, more strict
19180         * behavior.</p>
19181         *
19182         * @param size the size of the measure specification
19183         * @param mode the mode of the measure specification
19184         * @return the measure specification based on size and mode
19185         */
19186        public static int makeMeasureSpec(int size, int mode) {
19187            if (sUseBrokenMakeMeasureSpec) {
19188                return size + mode;
19189            } else {
19190                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19191            }
19192        }
19193
19194        /**
19195         * Extracts the mode from the supplied measure specification.
19196         *
19197         * @param measureSpec the measure specification to extract the mode from
19198         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19199         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19200         *         {@link android.view.View.MeasureSpec#EXACTLY}
19201         */
19202        public static int getMode(int measureSpec) {
19203            return (measureSpec & MODE_MASK);
19204        }
19205
19206        /**
19207         * Extracts the size from the supplied measure specification.
19208         *
19209         * @param measureSpec the measure specification to extract the size from
19210         * @return the size in pixels defined in the supplied measure specification
19211         */
19212        public static int getSize(int measureSpec) {
19213            return (measureSpec & ~MODE_MASK);
19214        }
19215
19216        static int adjust(int measureSpec, int delta) {
19217            final int mode = getMode(measureSpec);
19218            if (mode == UNSPECIFIED) {
19219                // No need to adjust size for UNSPECIFIED mode.
19220                return makeMeasureSpec(0, UNSPECIFIED);
19221            }
19222            int size = getSize(measureSpec) + delta;
19223            if (size < 0) {
19224                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19225                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19226                size = 0;
19227            }
19228            return makeMeasureSpec(size, mode);
19229        }
19230
19231        /**
19232         * Returns a String representation of the specified measure
19233         * specification.
19234         *
19235         * @param measureSpec the measure specification to convert to a String
19236         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19237         */
19238        public static String toString(int measureSpec) {
19239            int mode = getMode(measureSpec);
19240            int size = getSize(measureSpec);
19241
19242            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19243
19244            if (mode == UNSPECIFIED)
19245                sb.append("UNSPECIFIED ");
19246            else if (mode == EXACTLY)
19247                sb.append("EXACTLY ");
19248            else if (mode == AT_MOST)
19249                sb.append("AT_MOST ");
19250            else
19251                sb.append(mode).append(" ");
19252
19253            sb.append(size);
19254            return sb.toString();
19255        }
19256    }
19257
19258    private final class CheckForLongPress implements Runnable {
19259        private int mOriginalWindowAttachCount;
19260
19261        @Override
19262        public void run() {
19263            if (isPressed() && (mParent != null)
19264                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19265                if (performLongClick()) {
19266                    mHasPerformedLongPress = true;
19267                }
19268            }
19269        }
19270
19271        public void rememberWindowAttachCount() {
19272            mOriginalWindowAttachCount = mWindowAttachCount;
19273        }
19274    }
19275
19276    private final class CheckForTap implements Runnable {
19277        public float x;
19278        public float y;
19279
19280        @Override
19281        public void run() {
19282            mPrivateFlags &= ~PFLAG_PREPRESSED;
19283            setPressed(true, x, y);
19284            checkForLongClick(ViewConfiguration.getTapTimeout());
19285        }
19286    }
19287
19288    private final class PerformClick implements Runnable {
19289        @Override
19290        public void run() {
19291            performClick();
19292        }
19293    }
19294
19295    /** @hide */
19296    public void hackTurnOffWindowResizeAnim(boolean off) {
19297        mAttachInfo.mTurnOffWindowResizeAnim = off;
19298    }
19299
19300    /**
19301     * This method returns a ViewPropertyAnimator object, which can be used to animate
19302     * specific properties on this View.
19303     *
19304     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19305     */
19306    public ViewPropertyAnimator animate() {
19307        if (mAnimator == null) {
19308            mAnimator = new ViewPropertyAnimator(this);
19309        }
19310        return mAnimator;
19311    }
19312
19313    /**
19314     * Sets the name of the View to be used to identify Views in Transitions.
19315     * Names should be unique in the View hierarchy.
19316     *
19317     * @param viewName The name of the View to uniquely identify it for Transitions.
19318     */
19319    public final void setViewName(String viewName) {
19320        mViewName = viewName;
19321    }
19322
19323    /**
19324     * Returns the name of the View to be used to identify Views in Transitions.
19325     * Names should be unique in the View hierarchy.
19326     *
19327     * <p>This returns null if the View has not been given a name.</p>
19328     *
19329     * @return The name used of the View to be used to identify Views in Transitions or null
19330     * if no name has been given.
19331     */
19332    public String getViewName() {
19333        return mViewName;
19334    }
19335
19336    /**
19337     * Interface definition for a callback to be invoked when a hardware key event is
19338     * dispatched to this view. The callback will be invoked before the key event is
19339     * given to the view. This is only useful for hardware keyboards; a software input
19340     * method has no obligation to trigger this listener.
19341     */
19342    public interface OnKeyListener {
19343        /**
19344         * Called when a hardware key is dispatched to a view. This allows listeners to
19345         * get a chance to respond before the target view.
19346         * <p>Key presses in software keyboards will generally NOT trigger this method,
19347         * although some may elect to do so in some situations. Do not assume a
19348         * software input method has to be key-based; even if it is, it may use key presses
19349         * in a different way than you expect, so there is no way to reliably catch soft
19350         * input key presses.
19351         *
19352         * @param v The view the key has been dispatched to.
19353         * @param keyCode The code for the physical key that was pressed
19354         * @param event The KeyEvent object containing full information about
19355         *        the event.
19356         * @return True if the listener has consumed the event, false otherwise.
19357         */
19358        boolean onKey(View v, int keyCode, KeyEvent event);
19359    }
19360
19361    /**
19362     * Interface definition for a callback to be invoked when a touch event is
19363     * dispatched to this view. The callback will be invoked before the touch
19364     * event is given to the view.
19365     */
19366    public interface OnTouchListener {
19367        /**
19368         * Called when a touch event is dispatched to a view. This allows listeners to
19369         * get a chance to respond before the target view.
19370         *
19371         * @param v The view the touch event has been dispatched to.
19372         * @param event The MotionEvent object containing full information about
19373         *        the event.
19374         * @return True if the listener has consumed the event, false otherwise.
19375         */
19376        boolean onTouch(View v, MotionEvent event);
19377    }
19378
19379    /**
19380     * Interface definition for a callback to be invoked when a hover event is
19381     * dispatched to this view. The callback will be invoked before the hover
19382     * event is given to the view.
19383     */
19384    public interface OnHoverListener {
19385        /**
19386         * Called when a hover event is dispatched to a view. This allows listeners to
19387         * get a chance to respond before the target view.
19388         *
19389         * @param v The view the hover event has been dispatched to.
19390         * @param event The MotionEvent object containing full information about
19391         *        the event.
19392         * @return True if the listener has consumed the event, false otherwise.
19393         */
19394        boolean onHover(View v, MotionEvent event);
19395    }
19396
19397    /**
19398     * Interface definition for a callback to be invoked when a generic motion event is
19399     * dispatched to this view. The callback will be invoked before the generic motion
19400     * event is given to the view.
19401     */
19402    public interface OnGenericMotionListener {
19403        /**
19404         * Called when a generic motion event is dispatched to a view. This allows listeners to
19405         * get a chance to respond before the target view.
19406         *
19407         * @param v The view the generic motion event has been dispatched to.
19408         * @param event The MotionEvent object containing full information about
19409         *        the event.
19410         * @return True if the listener has consumed the event, false otherwise.
19411         */
19412        boolean onGenericMotion(View v, MotionEvent event);
19413    }
19414
19415    /**
19416     * Interface definition for a callback to be invoked when a view has been clicked and held.
19417     */
19418    public interface OnLongClickListener {
19419        /**
19420         * Called when a view has been clicked and held.
19421         *
19422         * @param v The view that was clicked and held.
19423         *
19424         * @return true if the callback consumed the long click, false otherwise.
19425         */
19426        boolean onLongClick(View v);
19427    }
19428
19429    /**
19430     * Interface definition for a callback to be invoked when a drag is being dispatched
19431     * to this view.  The callback will be invoked before the hosting view's own
19432     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19433     * onDrag(event) behavior, it should return 'false' from this callback.
19434     *
19435     * <div class="special reference">
19436     * <h3>Developer Guides</h3>
19437     * <p>For a guide to implementing drag and drop features, read the
19438     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19439     * </div>
19440     */
19441    public interface OnDragListener {
19442        /**
19443         * Called when a drag event is dispatched to a view. This allows listeners
19444         * to get a chance to override base View behavior.
19445         *
19446         * @param v The View that received the drag event.
19447         * @param event The {@link android.view.DragEvent} object for the drag event.
19448         * @return {@code true} if the drag event was handled successfully, or {@code false}
19449         * if the drag event was not handled. Note that {@code false} will trigger the View
19450         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19451         */
19452        boolean onDrag(View v, DragEvent event);
19453    }
19454
19455    /**
19456     * Interface definition for a callback to be invoked when the focus state of
19457     * a view changed.
19458     */
19459    public interface OnFocusChangeListener {
19460        /**
19461         * Called when the focus state of a view has changed.
19462         *
19463         * @param v The view whose state has changed.
19464         * @param hasFocus The new focus state of v.
19465         */
19466        void onFocusChange(View v, boolean hasFocus);
19467    }
19468
19469    /**
19470     * Interface definition for a callback to be invoked when a view is clicked.
19471     */
19472    public interface OnClickListener {
19473        /**
19474         * Called when a view has been clicked.
19475         *
19476         * @param v The view that was clicked.
19477         */
19478        void onClick(View v);
19479    }
19480
19481    /**
19482     * Interface definition for a callback to be invoked when the context menu
19483     * for this view is being built.
19484     */
19485    public interface OnCreateContextMenuListener {
19486        /**
19487         * Called when the context menu for this view is being built. It is not
19488         * safe to hold onto the menu after this method returns.
19489         *
19490         * @param menu The context menu that is being built
19491         * @param v The view for which the context menu is being built
19492         * @param menuInfo Extra information about the item for which the
19493         *            context menu should be shown. This information will vary
19494         *            depending on the class of v.
19495         */
19496        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19497    }
19498
19499    /**
19500     * Interface definition for a callback to be invoked when the status bar changes
19501     * visibility.  This reports <strong>global</strong> changes to the system UI
19502     * state, not what the application is requesting.
19503     *
19504     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19505     */
19506    public interface OnSystemUiVisibilityChangeListener {
19507        /**
19508         * Called when the status bar changes visibility because of a call to
19509         * {@link View#setSystemUiVisibility(int)}.
19510         *
19511         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19512         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19513         * This tells you the <strong>global</strong> state of these UI visibility
19514         * flags, not what your app is currently applying.
19515         */
19516        public void onSystemUiVisibilityChange(int visibility);
19517    }
19518
19519    /**
19520     * Interface definition for a callback to be invoked when this view is attached
19521     * or detached from its window.
19522     */
19523    public interface OnAttachStateChangeListener {
19524        /**
19525         * Called when the view is attached to a window.
19526         * @param v The view that was attached
19527         */
19528        public void onViewAttachedToWindow(View v);
19529        /**
19530         * Called when the view is detached from a window.
19531         * @param v The view that was detached
19532         */
19533        public void onViewDetachedFromWindow(View v);
19534    }
19535
19536    /**
19537     * Listener for applying window insets on a view in a custom way.
19538     *
19539     * <p>Apps may choose to implement this interface if they want to apply custom policy
19540     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19541     * is set, its
19542     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19543     * method will be called instead of the View's own
19544     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19545     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19546     * the View's normal behavior as part of its own.</p>
19547     */
19548    public interface OnApplyWindowInsetsListener {
19549        /**
19550         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19551         * on a View, this listener method will be called instead of the view's own
19552         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19553         *
19554         * @param v The view applying window insets
19555         * @param insets The insets to apply
19556         * @return The insets supplied, minus any insets that were consumed
19557         */
19558        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19559    }
19560
19561    private final class UnsetPressedState implements Runnable {
19562        @Override
19563        public void run() {
19564            setPressed(false);
19565        }
19566    }
19567
19568    /**
19569     * Base class for derived classes that want to save and restore their own
19570     * state in {@link android.view.View#onSaveInstanceState()}.
19571     */
19572    public static class BaseSavedState extends AbsSavedState {
19573        /**
19574         * Constructor used when reading from a parcel. Reads the state of the superclass.
19575         *
19576         * @param source
19577         */
19578        public BaseSavedState(Parcel source) {
19579            super(source);
19580        }
19581
19582        /**
19583         * Constructor called by derived classes when creating their SavedState objects
19584         *
19585         * @param superState The state of the superclass of this view
19586         */
19587        public BaseSavedState(Parcelable superState) {
19588            super(superState);
19589        }
19590
19591        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19592                new Parcelable.Creator<BaseSavedState>() {
19593            public BaseSavedState createFromParcel(Parcel in) {
19594                return new BaseSavedState(in);
19595            }
19596
19597            public BaseSavedState[] newArray(int size) {
19598                return new BaseSavedState[size];
19599            }
19600        };
19601    }
19602
19603    /**
19604     * A set of information given to a view when it is attached to its parent
19605     * window.
19606     */
19607    final static class AttachInfo {
19608        interface Callbacks {
19609            void playSoundEffect(int effectId);
19610            boolean performHapticFeedback(int effectId, boolean always);
19611        }
19612
19613        /**
19614         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19615         * to a Handler. This class contains the target (View) to invalidate and
19616         * the coordinates of the dirty rectangle.
19617         *
19618         * For performance purposes, this class also implements a pool of up to
19619         * POOL_LIMIT objects that get reused. This reduces memory allocations
19620         * whenever possible.
19621         */
19622        static class InvalidateInfo {
19623            private static final int POOL_LIMIT = 10;
19624
19625            private static final SynchronizedPool<InvalidateInfo> sPool =
19626                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19627
19628            View target;
19629
19630            int left;
19631            int top;
19632            int right;
19633            int bottom;
19634
19635            public static InvalidateInfo obtain() {
19636                InvalidateInfo instance = sPool.acquire();
19637                return (instance != null) ? instance : new InvalidateInfo();
19638            }
19639
19640            public void recycle() {
19641                target = null;
19642                sPool.release(this);
19643            }
19644        }
19645
19646        final IWindowSession mSession;
19647
19648        final IWindow mWindow;
19649
19650        final IBinder mWindowToken;
19651
19652        final Display mDisplay;
19653
19654        final Callbacks mRootCallbacks;
19655
19656        IWindowId mIWindowId;
19657        WindowId mWindowId;
19658
19659        /**
19660         * The top view of the hierarchy.
19661         */
19662        View mRootView;
19663
19664        IBinder mPanelParentWindowToken;
19665
19666        boolean mHardwareAccelerated;
19667        boolean mHardwareAccelerationRequested;
19668        HardwareRenderer mHardwareRenderer;
19669
19670        /**
19671         * The state of the display to which the window is attached, as reported
19672         * by {@link Display#getState()}.  Note that the display state constants
19673         * declared by {@link Display} do not exactly line up with the screen state
19674         * constants declared by {@link View} (there are more display states than
19675         * screen states).
19676         */
19677        int mDisplayState = Display.STATE_UNKNOWN;
19678
19679        /**
19680         * Scale factor used by the compatibility mode
19681         */
19682        float mApplicationScale;
19683
19684        /**
19685         * Indicates whether the application is in compatibility mode
19686         */
19687        boolean mScalingRequired;
19688
19689        /**
19690         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19691         */
19692        boolean mTurnOffWindowResizeAnim;
19693
19694        /**
19695         * Left position of this view's window
19696         */
19697        int mWindowLeft;
19698
19699        /**
19700         * Top position of this view's window
19701         */
19702        int mWindowTop;
19703
19704        /**
19705         * Indicates whether views need to use 32-bit drawing caches
19706         */
19707        boolean mUse32BitDrawingCache;
19708
19709        /**
19710         * For windows that are full-screen but using insets to layout inside
19711         * of the screen areas, these are the current insets to appear inside
19712         * the overscan area of the display.
19713         */
19714        final Rect mOverscanInsets = new Rect();
19715
19716        /**
19717         * For windows that are full-screen but using insets to layout inside
19718         * of the screen decorations, these are the current insets for the
19719         * content of the window.
19720         */
19721        final Rect mContentInsets = new Rect();
19722
19723        /**
19724         * For windows that are full-screen but using insets to layout inside
19725         * of the screen decorations, these are the current insets for the
19726         * actual visible parts of the window.
19727         */
19728        final Rect mVisibleInsets = new Rect();
19729
19730        /**
19731         * The internal insets given by this window.  This value is
19732         * supplied by the client (through
19733         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19734         * be given to the window manager when changed to be used in laying
19735         * out windows behind it.
19736         */
19737        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19738                = new ViewTreeObserver.InternalInsetsInfo();
19739
19740        /**
19741         * Set to true when mGivenInternalInsets is non-empty.
19742         */
19743        boolean mHasNonEmptyGivenInternalInsets;
19744
19745        /**
19746         * All views in the window's hierarchy that serve as scroll containers,
19747         * used to determine if the window can be resized or must be panned
19748         * to adjust for a soft input area.
19749         */
19750        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19751
19752        final KeyEvent.DispatcherState mKeyDispatchState
19753                = new KeyEvent.DispatcherState();
19754
19755        /**
19756         * Indicates whether the view's window currently has the focus.
19757         */
19758        boolean mHasWindowFocus;
19759
19760        /**
19761         * The current visibility of the window.
19762         */
19763        int mWindowVisibility;
19764
19765        /**
19766         * Indicates the time at which drawing started to occur.
19767         */
19768        long mDrawingTime;
19769
19770        /**
19771         * Indicates whether or not ignoring the DIRTY_MASK flags.
19772         */
19773        boolean mIgnoreDirtyState;
19774
19775        /**
19776         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19777         * to avoid clearing that flag prematurely.
19778         */
19779        boolean mSetIgnoreDirtyState = false;
19780
19781        /**
19782         * Indicates whether the view's window is currently in touch mode.
19783         */
19784        boolean mInTouchMode;
19785
19786        /**
19787         * Indicates whether the view has requested unbuffered input dispatching for the current
19788         * event stream.
19789         */
19790        boolean mUnbufferedDispatchRequested;
19791
19792        /**
19793         * Indicates that ViewAncestor should trigger a global layout change
19794         * the next time it performs a traversal
19795         */
19796        boolean mRecomputeGlobalAttributes;
19797
19798        /**
19799         * Always report new attributes at next traversal.
19800         */
19801        boolean mForceReportNewAttributes;
19802
19803        /**
19804         * Set during a traveral if any views want to keep the screen on.
19805         */
19806        boolean mKeepScreenOn;
19807
19808        /**
19809         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19810         */
19811        int mSystemUiVisibility;
19812
19813        /**
19814         * Hack to force certain system UI visibility flags to be cleared.
19815         */
19816        int mDisabledSystemUiVisibility;
19817
19818        /**
19819         * Last global system UI visibility reported by the window manager.
19820         */
19821        int mGlobalSystemUiVisibility;
19822
19823        /**
19824         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19825         * attached.
19826         */
19827        boolean mHasSystemUiListeners;
19828
19829        /**
19830         * Set if the window has requested to extend into the overscan region
19831         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19832         */
19833        boolean mOverscanRequested;
19834
19835        /**
19836         * Set if the visibility of any views has changed.
19837         */
19838        boolean mViewVisibilityChanged;
19839
19840        /**
19841         * Set to true if a view has been scrolled.
19842         */
19843        boolean mViewScrollChanged;
19844
19845        /**
19846         * Global to the view hierarchy used as a temporary for dealing with
19847         * x/y points in the transparent region computations.
19848         */
19849        final int[] mTransparentLocation = new int[2];
19850
19851        /**
19852         * Global to the view hierarchy used as a temporary for dealing with
19853         * x/y points in the ViewGroup.invalidateChild implementation.
19854         */
19855        final int[] mInvalidateChildLocation = new int[2];
19856
19857
19858        /**
19859         * Global to the view hierarchy used as a temporary for dealing with
19860         * x/y location when view is transformed.
19861         */
19862        final float[] mTmpTransformLocation = new float[2];
19863
19864        /**
19865         * The view tree observer used to dispatch global events like
19866         * layout, pre-draw, touch mode change, etc.
19867         */
19868        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19869
19870        /**
19871         * A Canvas used by the view hierarchy to perform bitmap caching.
19872         */
19873        Canvas mCanvas;
19874
19875        /**
19876         * The view root impl.
19877         */
19878        final ViewRootImpl mViewRootImpl;
19879
19880        /**
19881         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19882         * handler can be used to pump events in the UI events queue.
19883         */
19884        final Handler mHandler;
19885
19886        /**
19887         * Temporary for use in computing invalidate rectangles while
19888         * calling up the hierarchy.
19889         */
19890        final Rect mTmpInvalRect = new Rect();
19891
19892        /**
19893         * Temporary for use in computing hit areas with transformed views
19894         */
19895        final RectF mTmpTransformRect = new RectF();
19896
19897        /**
19898         * Temporary for use in transforming invalidation rect
19899         */
19900        final Matrix mTmpMatrix = new Matrix();
19901
19902        /**
19903         * Temporary for use in transforming invalidation rect
19904         */
19905        final Transformation mTmpTransformation = new Transformation();
19906
19907        /**
19908         * Temporary list for use in collecting focusable descendents of a view.
19909         */
19910        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19911
19912        /**
19913         * The id of the window for accessibility purposes.
19914         */
19915        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
19916
19917        /**
19918         * Flags related to accessibility processing.
19919         *
19920         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19921         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19922         */
19923        int mAccessibilityFetchFlags;
19924
19925        /**
19926         * The drawable for highlighting accessibility focus.
19927         */
19928        Drawable mAccessibilityFocusDrawable;
19929
19930        /**
19931         * Show where the margins, bounds and layout bounds are for each view.
19932         */
19933        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19934
19935        /**
19936         * Point used to compute visible regions.
19937         */
19938        final Point mPoint = new Point();
19939
19940        /**
19941         * Used to track which View originated a requestLayout() call, used when
19942         * requestLayout() is called during layout.
19943         */
19944        View mViewRequestingLayout;
19945
19946        /**
19947         * Creates a new set of attachment information with the specified
19948         * events handler and thread.
19949         *
19950         * @param handler the events handler the view must use
19951         */
19952        AttachInfo(IWindowSession session, IWindow window, Display display,
19953                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19954            mSession = session;
19955            mWindow = window;
19956            mWindowToken = window.asBinder();
19957            mDisplay = display;
19958            mViewRootImpl = viewRootImpl;
19959            mHandler = handler;
19960            mRootCallbacks = effectPlayer;
19961        }
19962    }
19963
19964    /**
19965     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19966     * is supported. This avoids keeping too many unused fields in most
19967     * instances of View.</p>
19968     */
19969    private static class ScrollabilityCache implements Runnable {
19970
19971        /**
19972         * Scrollbars are not visible
19973         */
19974        public static final int OFF = 0;
19975
19976        /**
19977         * Scrollbars are visible
19978         */
19979        public static final int ON = 1;
19980
19981        /**
19982         * Scrollbars are fading away
19983         */
19984        public static final int FADING = 2;
19985
19986        public boolean fadeScrollBars;
19987
19988        public int fadingEdgeLength;
19989        public int scrollBarDefaultDelayBeforeFade;
19990        public int scrollBarFadeDuration;
19991
19992        public int scrollBarSize;
19993        public ScrollBarDrawable scrollBar;
19994        public float[] interpolatorValues;
19995        public View host;
19996
19997        public final Paint paint;
19998        public final Matrix matrix;
19999        public Shader shader;
20000
20001        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20002
20003        private static final float[] OPAQUE = { 255 };
20004        private static final float[] TRANSPARENT = { 0.0f };
20005
20006        /**
20007         * When fading should start. This time moves into the future every time
20008         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20009         */
20010        public long fadeStartTime;
20011
20012
20013        /**
20014         * The current state of the scrollbars: ON, OFF, or FADING
20015         */
20016        public int state = OFF;
20017
20018        private int mLastColor;
20019
20020        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20021            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20022            scrollBarSize = configuration.getScaledScrollBarSize();
20023            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20024            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20025
20026            paint = new Paint();
20027            matrix = new Matrix();
20028            // use use a height of 1, and then wack the matrix each time we
20029            // actually use it.
20030            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20031            paint.setShader(shader);
20032            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20033
20034            this.host = host;
20035        }
20036
20037        public void setFadeColor(int color) {
20038            if (color != mLastColor) {
20039                mLastColor = color;
20040
20041                if (color != 0) {
20042                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20043                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20044                    paint.setShader(shader);
20045                    // Restore the default transfer mode (src_over)
20046                    paint.setXfermode(null);
20047                } else {
20048                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20049                    paint.setShader(shader);
20050                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20051                }
20052            }
20053        }
20054
20055        public void run() {
20056            long now = AnimationUtils.currentAnimationTimeMillis();
20057            if (now >= fadeStartTime) {
20058
20059                // the animation fades the scrollbars out by changing
20060                // the opacity (alpha) from fully opaque to fully
20061                // transparent
20062                int nextFrame = (int) now;
20063                int framesCount = 0;
20064
20065                Interpolator interpolator = scrollBarInterpolator;
20066
20067                // Start opaque
20068                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20069
20070                // End transparent
20071                nextFrame += scrollBarFadeDuration;
20072                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20073
20074                state = FADING;
20075
20076                // Kick off the fade animation
20077                host.invalidate(true);
20078            }
20079        }
20080    }
20081
20082    /**
20083     * Resuable callback for sending
20084     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20085     */
20086    private class SendViewScrolledAccessibilityEvent implements Runnable {
20087        public volatile boolean mIsPending;
20088
20089        public void run() {
20090            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20091            mIsPending = false;
20092        }
20093    }
20094
20095    /**
20096     * <p>
20097     * This class represents a delegate that can be registered in a {@link View}
20098     * to enhance accessibility support via composition rather via inheritance.
20099     * It is specifically targeted to widget developers that extend basic View
20100     * classes i.e. classes in package android.view, that would like their
20101     * applications to be backwards compatible.
20102     * </p>
20103     * <div class="special reference">
20104     * <h3>Developer Guides</h3>
20105     * <p>For more information about making applications accessible, read the
20106     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20107     * developer guide.</p>
20108     * </div>
20109     * <p>
20110     * A scenario in which a developer would like to use an accessibility delegate
20111     * is overriding a method introduced in a later API version then the minimal API
20112     * version supported by the application. For example, the method
20113     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20114     * in API version 4 when the accessibility APIs were first introduced. If a
20115     * developer would like his application to run on API version 4 devices (assuming
20116     * all other APIs used by the application are version 4 or lower) and take advantage
20117     * of this method, instead of overriding the method which would break the application's
20118     * backwards compatibility, he can override the corresponding method in this
20119     * delegate and register the delegate in the target View if the API version of
20120     * the system is high enough i.e. the API version is same or higher to the API
20121     * version that introduced
20122     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20123     * </p>
20124     * <p>
20125     * Here is an example implementation:
20126     * </p>
20127     * <code><pre><p>
20128     * if (Build.VERSION.SDK_INT >= 14) {
20129     *     // If the API version is equal of higher than the version in
20130     *     // which onInitializeAccessibilityNodeInfo was introduced we
20131     *     // register a delegate with a customized implementation.
20132     *     View view = findViewById(R.id.view_id);
20133     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20134     *         public void onInitializeAccessibilityNodeInfo(View host,
20135     *                 AccessibilityNodeInfo info) {
20136     *             // Let the default implementation populate the info.
20137     *             super.onInitializeAccessibilityNodeInfo(host, info);
20138     *             // Set some other information.
20139     *             info.setEnabled(host.isEnabled());
20140     *         }
20141     *     });
20142     * }
20143     * </code></pre></p>
20144     * <p>
20145     * This delegate contains methods that correspond to the accessibility methods
20146     * in View. If a delegate has been specified the implementation in View hands
20147     * off handling to the corresponding method in this delegate. The default
20148     * implementation the delegate methods behaves exactly as the corresponding
20149     * method in View for the case of no accessibility delegate been set. Hence,
20150     * to customize the behavior of a View method, clients can override only the
20151     * corresponding delegate method without altering the behavior of the rest
20152     * accessibility related methods of the host view.
20153     * </p>
20154     */
20155    public static class AccessibilityDelegate {
20156
20157        /**
20158         * Sends an accessibility event of the given type. If accessibility is not
20159         * enabled this method has no effect.
20160         * <p>
20161         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20162         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20163         * been set.
20164         * </p>
20165         *
20166         * @param host The View hosting the delegate.
20167         * @param eventType The type of the event to send.
20168         *
20169         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20170         */
20171        public void sendAccessibilityEvent(View host, int eventType) {
20172            host.sendAccessibilityEventInternal(eventType);
20173        }
20174
20175        /**
20176         * Performs the specified accessibility action on the view. For
20177         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20178         * <p>
20179         * The default implementation behaves as
20180         * {@link View#performAccessibilityAction(int, Bundle)
20181         *  View#performAccessibilityAction(int, Bundle)} for the case of
20182         *  no accessibility delegate been set.
20183         * </p>
20184         *
20185         * @param action The action to perform.
20186         * @return Whether the action was performed.
20187         *
20188         * @see View#performAccessibilityAction(int, Bundle)
20189         *      View#performAccessibilityAction(int, Bundle)
20190         */
20191        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20192            return host.performAccessibilityActionInternal(action, args);
20193        }
20194
20195        /**
20196         * Sends an accessibility event. This method behaves exactly as
20197         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20198         * empty {@link AccessibilityEvent} and does not perform a check whether
20199         * accessibility is enabled.
20200         * <p>
20201         * The default implementation behaves as
20202         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20203         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20204         * the case of no accessibility delegate been set.
20205         * </p>
20206         *
20207         * @param host The View hosting the delegate.
20208         * @param event The event to send.
20209         *
20210         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20211         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20212         */
20213        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20214            host.sendAccessibilityEventUncheckedInternal(event);
20215        }
20216
20217        /**
20218         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20219         * to its children for adding their text content to the event.
20220         * <p>
20221         * The default implementation behaves as
20222         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20223         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20224         * the case of no accessibility delegate been set.
20225         * </p>
20226         *
20227         * @param host The View hosting the delegate.
20228         * @param event The event.
20229         * @return True if the event population was completed.
20230         *
20231         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20232         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20233         */
20234        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20235            return host.dispatchPopulateAccessibilityEventInternal(event);
20236        }
20237
20238        /**
20239         * Gives a chance to the host View to populate the accessibility event with its
20240         * text content.
20241         * <p>
20242         * The default implementation behaves as
20243         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20244         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20245         * the case of no accessibility delegate been set.
20246         * </p>
20247         *
20248         * @param host The View hosting the delegate.
20249         * @param event The accessibility event which to populate.
20250         *
20251         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20252         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20253         */
20254        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20255            host.onPopulateAccessibilityEventInternal(event);
20256        }
20257
20258        /**
20259         * Initializes an {@link AccessibilityEvent} with information about the
20260         * the host View which is the event source.
20261         * <p>
20262         * The default implementation behaves as
20263         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20264         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20265         * the case of no accessibility delegate been set.
20266         * </p>
20267         *
20268         * @param host The View hosting the delegate.
20269         * @param event The event to initialize.
20270         *
20271         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20272         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20273         */
20274        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20275            host.onInitializeAccessibilityEventInternal(event);
20276        }
20277
20278        /**
20279         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20280         * <p>
20281         * The default implementation behaves as
20282         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20283         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20284         * the case of no accessibility delegate been set.
20285         * </p>
20286         *
20287         * @param host The View hosting the delegate.
20288         * @param info The instance to initialize.
20289         *
20290         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20291         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20292         */
20293        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20294            host.onInitializeAccessibilityNodeInfoInternal(info);
20295        }
20296
20297        /**
20298         * Called when a child of the host View has requested sending an
20299         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20300         * to augment the event.
20301         * <p>
20302         * The default implementation behaves as
20303         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20304         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20305         * the case of no accessibility delegate been set.
20306         * </p>
20307         *
20308         * @param host The View hosting the delegate.
20309         * @param child The child which requests sending the event.
20310         * @param event The event to be sent.
20311         * @return True if the event should be sent
20312         *
20313         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20314         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20315         */
20316        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20317                AccessibilityEvent event) {
20318            return host.onRequestSendAccessibilityEventInternal(child, event);
20319        }
20320
20321        /**
20322         * Gets the provider for managing a virtual view hierarchy rooted at this View
20323         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20324         * that explore the window content.
20325         * <p>
20326         * The default implementation behaves as
20327         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20328         * the case of no accessibility delegate been set.
20329         * </p>
20330         *
20331         * @return The provider.
20332         *
20333         * @see AccessibilityNodeProvider
20334         */
20335        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20336            return null;
20337        }
20338
20339        /**
20340         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20341         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20342         * This method is responsible for obtaining an accessibility node info from a
20343         * pool of reusable instances and calling
20344         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20345         * view to initialize the former.
20346         * <p>
20347         * <strong>Note:</strong> The client is responsible for recycling the obtained
20348         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20349         * creation.
20350         * </p>
20351         * <p>
20352         * The default implementation behaves as
20353         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20354         * the case of no accessibility delegate been set.
20355         * </p>
20356         * @return A populated {@link AccessibilityNodeInfo}.
20357         *
20358         * @see AccessibilityNodeInfo
20359         *
20360         * @hide
20361         */
20362        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20363            return host.createAccessibilityNodeInfoInternal();
20364        }
20365    }
20366
20367    private class MatchIdPredicate implements Predicate<View> {
20368        public int mId;
20369
20370        @Override
20371        public boolean apply(View view) {
20372            return (view.mID == mId);
20373        }
20374    }
20375
20376    private class MatchLabelForPredicate implements Predicate<View> {
20377        private int mLabeledId;
20378
20379        @Override
20380        public boolean apply(View view) {
20381            return (view.mLabelForId == mLabeledId);
20382        }
20383    }
20384
20385    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20386        private int mChangeTypes = 0;
20387        private boolean mPosted;
20388        private boolean mPostedWithDelay;
20389        private long mLastEventTimeMillis;
20390
20391        @Override
20392        public void run() {
20393            mPosted = false;
20394            mPostedWithDelay = false;
20395            mLastEventTimeMillis = SystemClock.uptimeMillis();
20396            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20397                final AccessibilityEvent event = AccessibilityEvent.obtain();
20398                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20399                event.setContentChangeTypes(mChangeTypes);
20400                sendAccessibilityEventUnchecked(event);
20401            }
20402            mChangeTypes = 0;
20403        }
20404
20405        public void runOrPost(int changeType) {
20406            mChangeTypes |= changeType;
20407
20408            // If this is a live region or the child of a live region, collect
20409            // all events from this frame and send them on the next frame.
20410            if (inLiveRegion()) {
20411                // If we're already posted with a delay, remove that.
20412                if (mPostedWithDelay) {
20413                    removeCallbacks(this);
20414                    mPostedWithDelay = false;
20415                }
20416                // Only post if we're not already posted.
20417                if (!mPosted) {
20418                    post(this);
20419                    mPosted = true;
20420                }
20421                return;
20422            }
20423
20424            if (mPosted) {
20425                return;
20426            }
20427            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20428            final long minEventIntevalMillis =
20429                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20430            if (timeSinceLastMillis >= minEventIntevalMillis) {
20431                removeCallbacks(this);
20432                run();
20433            } else {
20434                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20435                mPosted = true;
20436                mPostedWithDelay = true;
20437            }
20438        }
20439    }
20440
20441    private boolean inLiveRegion() {
20442        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20443            return true;
20444        }
20445
20446        ViewParent parent = getParent();
20447        while (parent instanceof View) {
20448            if (((View) parent).getAccessibilityLiveRegion()
20449                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20450                return true;
20451            }
20452            parent = parent.getParent();
20453        }
20454
20455        return false;
20456    }
20457
20458    /**
20459     * Dump all private flags in readable format, useful for documentation and
20460     * sanity checking.
20461     */
20462    private static void dumpFlags() {
20463        final HashMap<String, String> found = Maps.newHashMap();
20464        try {
20465            for (Field field : View.class.getDeclaredFields()) {
20466                final int modifiers = field.getModifiers();
20467                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20468                    if (field.getType().equals(int.class)) {
20469                        final int value = field.getInt(null);
20470                        dumpFlag(found, field.getName(), value);
20471                    } else if (field.getType().equals(int[].class)) {
20472                        final int[] values = (int[]) field.get(null);
20473                        for (int i = 0; i < values.length; i++) {
20474                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20475                        }
20476                    }
20477                }
20478            }
20479        } catch (IllegalAccessException e) {
20480            throw new RuntimeException(e);
20481        }
20482
20483        final ArrayList<String> keys = Lists.newArrayList();
20484        keys.addAll(found.keySet());
20485        Collections.sort(keys);
20486        for (String key : keys) {
20487            Log.d(VIEW_LOG_TAG, found.get(key));
20488        }
20489    }
20490
20491    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20492        // Sort flags by prefix, then by bits, always keeping unique keys
20493        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20494        final int prefix = name.indexOf('_');
20495        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20496        final String output = bits + " " + name;
20497        found.put(key, output);
20498    }
20499}
20500