View.java revision 6250c59e0d917fb3641ac499ca69b011aa50a4bd
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.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.content.ClipData;
23import android.content.Context;
24import android.content.res.Configuration;
25import android.content.res.Resources;
26import android.content.res.TypedArray;
27import android.graphics.Bitmap;
28import android.graphics.Camera;
29import android.graphics.Canvas;
30import android.graphics.Insets;
31import android.graphics.Interpolator;
32import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.Path;
36import android.graphics.PixelFormat;
37import android.graphics.Point;
38import android.graphics.PorterDuff;
39import android.graphics.PorterDuffXfermode;
40import android.graphics.Rect;
41import android.graphics.RectF;
42import android.graphics.Region;
43import android.graphics.Shader;
44import android.graphics.drawable.ColorDrawable;
45import android.graphics.drawable.Drawable;
46import android.hardware.display.DisplayManagerGlobal;
47import android.os.Bundle;
48import android.os.Handler;
49import android.os.IBinder;
50import android.os.Parcel;
51import android.os.Parcelable;
52import android.os.RemoteException;
53import android.os.SystemClock;
54import android.os.SystemProperties;
55import android.text.TextUtils;
56import android.util.AttributeSet;
57import android.util.FloatProperty;
58import android.util.LayoutDirection;
59import android.util.Log;
60import android.util.LongSparseLongArray;
61import android.util.Pools.SynchronizedPool;
62import android.util.Property;
63import android.util.SparseArray;
64import android.util.SuperNotCalledException;
65import android.util.TypedValue;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.AccessibilityIterators.TextSegmentIterator;
68import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
69import android.view.AccessibilityIterators.WordTextSegmentIterator;
70import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
71import android.view.accessibility.AccessibilityEvent;
72import android.view.accessibility.AccessibilityEventSource;
73import android.view.accessibility.AccessibilityManager;
74import android.view.accessibility.AccessibilityNodeInfo;
75import android.view.accessibility.AccessibilityNodeProvider;
76import android.view.animation.Animation;
77import android.view.animation.AnimationUtils;
78import android.view.animation.Transformation;
79import android.view.inputmethod.EditorInfo;
80import android.view.inputmethod.InputConnection;
81import android.view.inputmethod.InputMethodManager;
82import android.widget.ScrollBarDrawable;
83
84import static android.os.Build.VERSION_CODES.*;
85import static java.lang.Math.max;
86
87import com.android.internal.R;
88import com.android.internal.util.Predicate;
89import com.android.internal.view.menu.MenuBuilder;
90
91import com.google.android.collect.Lists;
92import com.google.android.collect.Maps;
93
94import java.lang.annotation.Retention;
95import java.lang.annotation.RetentionPolicy;
96import java.lang.ref.WeakReference;
97import java.lang.reflect.Field;
98import java.lang.reflect.InvocationTargetException;
99import java.lang.reflect.Method;
100import java.lang.reflect.Modifier;
101import java.util.ArrayList;
102import java.util.Arrays;
103import java.util.Collections;
104import java.util.HashMap;
105import java.util.Locale;
106import java.util.concurrent.CopyOnWriteArrayList;
107import java.util.concurrent.atomic.AtomicInteger;
108
109/**
110 * <p>
111 * This class represents the basic building block for user interface components. A View
112 * occupies a rectangular area on the screen and is responsible for drawing and
113 * event handling. View is the base class for <em>widgets</em>, which are
114 * used to create interactive UI components (buttons, text fields, etc.). The
115 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
116 * are invisible containers that hold other Views (or other ViewGroups) and define
117 * their layout properties.
118 * </p>
119 *
120 * <div class="special reference">
121 * <h3>Developer Guides</h3>
122 * <p>For information about using this class to develop your application's user interface,
123 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
124 * </div>
125 *
126 * <a name="Using"></a>
127 * <h3>Using Views</h3>
128 * <p>
129 * All of the views in a window are arranged in a single tree. You can add views
130 * either from code or by specifying a tree of views in one or more XML layout
131 * files. There are many specialized subclasses of views that act as controls or
132 * are capable of displaying text, images, or other content.
133 * </p>
134 * <p>
135 * Once you have created a tree of views, there are typically a few types of
136 * common operations you may wish to perform:
137 * <ul>
138 * <li><strong>Set properties:</strong> for example setting the text of a
139 * {@link android.widget.TextView}. The available properties and the methods
140 * that set them will vary among the different subclasses of views. Note that
141 * properties that are known at build time can be set in the XML layout
142 * files.</li>
143 * <li><strong>Set focus:</strong> The framework will handled moving focus in
144 * response to user input. To force focus to a specific view, call
145 * {@link #requestFocus}.</li>
146 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
147 * that will be notified when something interesting happens to the view. For
148 * example, all views will let you set a listener to be notified when the view
149 * gains or loses focus. You can register such a listener using
150 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
151 * Other view subclasses offer more specialized listeners. For example, a Button
152 * exposes a listener to notify clients when the button is clicked.</li>
153 * <li><strong>Set visibility:</strong> You can hide or show views using
154 * {@link #setVisibility(int)}.</li>
155 * </ul>
156 * </p>
157 * <p><em>
158 * Note: The Android framework is responsible for measuring, laying out and
159 * drawing views. You should not call methods that perform these actions on
160 * views yourself unless you are actually implementing a
161 * {@link android.view.ViewGroup}.
162 * </em></p>
163 *
164 * <a name="Lifecycle"></a>
165 * <h3>Implementing a Custom View</h3>
166 *
167 * <p>
168 * To implement a custom view, you will usually begin by providing overrides for
169 * some of the standard methods that the framework calls on all views. You do
170 * not need to override all of these methods. In fact, you can start by just
171 * overriding {@link #onDraw(android.graphics.Canvas)}.
172 * <table border="2" width="85%" align="center" cellpadding="5">
173 *     <thead>
174 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
175 *     </thead>
176 *
177 *     <tbody>
178 *     <tr>
179 *         <td rowspan="2">Creation</td>
180 *         <td>Constructors</td>
181 *         <td>There is a form of the constructor that are called when the view
182 *         is created from code and a form that is called when the view is
183 *         inflated from a layout file. The second form should parse and apply
184 *         any attributes defined in the layout file.
185 *         </td>
186 *     </tr>
187 *     <tr>
188 *         <td><code>{@link #onFinishInflate()}</code></td>
189 *         <td>Called after a view and all of its children has been inflated
190 *         from XML.</td>
191 *     </tr>
192 *
193 *     <tr>
194 *         <td rowspan="3">Layout</td>
195 *         <td><code>{@link #onMeasure(int, int)}</code></td>
196 *         <td>Called to determine the size requirements for this view and all
197 *         of its children.
198 *         </td>
199 *     </tr>
200 *     <tr>
201 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
202 *         <td>Called when this view should assign a size and position to all
203 *         of its children.
204 *         </td>
205 *     </tr>
206 *     <tr>
207 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
208 *         <td>Called when the size of this view has changed.
209 *         </td>
210 *     </tr>
211 *
212 *     <tr>
213 *         <td>Drawing</td>
214 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
215 *         <td>Called when the view should render its content.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td rowspan="4">Event processing</td>
221 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
222 *         <td>Called when a new hardware key event occurs.
223 *         </td>
224 *     </tr>
225 *     <tr>
226 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
227 *         <td>Called when a hardware key up event occurs.
228 *         </td>
229 *     </tr>
230 *     <tr>
231 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
232 *         <td>Called when a trackball motion event occurs.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
237 *         <td>Called when a touch screen motion event occurs.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td rowspan="2">Focus</td>
243 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
244 *         <td>Called when the view gains or loses focus.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
250 *         <td>Called when the window containing the view gains or loses focus.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td rowspan="3">Attaching</td>
256 *         <td><code>{@link #onAttachedToWindow()}</code></td>
257 *         <td>Called when the view is attached to a window.
258 *         </td>
259 *     </tr>
260 *
261 *     <tr>
262 *         <td><code>{@link #onDetachedFromWindow}</code></td>
263 *         <td>Called when the view is detached from its window.
264 *         </td>
265 *     </tr>
266 *
267 *     <tr>
268 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
269 *         <td>Called when the visibility of the window containing the view
270 *         has changed.
271 *         </td>
272 *     </tr>
273 *     </tbody>
274 *
275 * </table>
276 * </p>
277 *
278 * <a name="IDs"></a>
279 * <h3>IDs</h3>
280 * Views may have an integer id associated with them. These ids are typically
281 * assigned in the layout XML files, and are used to find specific views within
282 * the view tree. A common pattern is to:
283 * <ul>
284 * <li>Define a Button in the layout file and assign it a unique ID.
285 * <pre>
286 * &lt;Button
287 *     android:id="@+id/my_button"
288 *     android:layout_width="wrap_content"
289 *     android:layout_height="wrap_content"
290 *     android:text="@string/my_button_text"/&gt;
291 * </pre></li>
292 * <li>From the onCreate method of an Activity, find the Button
293 * <pre class="prettyprint">
294 *      Button myButton = (Button) findViewById(R.id.my_button);
295 * </pre></li>
296 * </ul>
297 * <p>
298 * View IDs need not be unique throughout the tree, but it is good practice to
299 * ensure that they are at least unique within the part of the tree you are
300 * searching.
301 * </p>
302 *
303 * <a name="Position"></a>
304 * <h3>Position</h3>
305 * <p>
306 * The geometry of a view is that of a rectangle. A view has a location,
307 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
308 * two dimensions, expressed as a width and a height. The unit for location
309 * and dimensions is the pixel.
310 * </p>
311 *
312 * <p>
313 * It is possible to retrieve the location of a view by invoking the methods
314 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
315 * coordinate of the rectangle representing the view. The latter returns the
316 * top, or Y, coordinate of the rectangle representing the view. These methods
317 * both return the location of the view relative to its parent. For instance,
318 * when getLeft() returns 20, that means the view is located 20 pixels to the
319 * right of the left edge of its direct parent.
320 * </p>
321 *
322 * <p>
323 * In addition, several convenience methods are offered to avoid unnecessary
324 * computations, namely {@link #getRight()} and {@link #getBottom()}.
325 * These methods return the coordinates of the right and bottom edges of the
326 * rectangle representing the view. For instance, calling {@link #getRight()}
327 * is similar to the following computation: <code>getLeft() + getWidth()</code>
328 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
329 * </p>
330 *
331 * <a name="SizePaddingMargins"></a>
332 * <h3>Size, padding and margins</h3>
333 * <p>
334 * The size of a view is expressed with a width and a height. A view actually
335 * possess two pairs of width and height values.
336 * </p>
337 *
338 * <p>
339 * The first pair is known as <em>measured width</em> and
340 * <em>measured height</em>. These dimensions define how big a view wants to be
341 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
342 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
343 * and {@link #getMeasuredHeight()}.
344 * </p>
345 *
346 * <p>
347 * The second pair is simply known as <em>width</em> and <em>height</em>, or
348 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
349 * dimensions define the actual size of the view on screen, at drawing time and
350 * after layout. These values may, but do not have to, be different from the
351 * measured width and height. The width and height can be obtained by calling
352 * {@link #getWidth()} and {@link #getHeight()}.
353 * </p>
354 *
355 * <p>
356 * To measure its dimensions, a view takes into account its padding. The padding
357 * is expressed in pixels for the left, top, right and bottom parts of the view.
358 * Padding can be used to offset the content of the view by a specific amount of
359 * pixels. For instance, a left padding of 2 will push the view's content by
360 * 2 pixels to the right of the left edge. Padding can be set using the
361 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
362 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
363 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
364 * {@link #getPaddingEnd()}.
365 * </p>
366 *
367 * <p>
368 * Even though a view can define a padding, it does not provide any support for
369 * margins. However, view groups provide such a support. Refer to
370 * {@link android.view.ViewGroup} and
371 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
372 * </p>
373 *
374 * <a name="Layout"></a>
375 * <h3>Layout</h3>
376 * <p>
377 * Layout is a two pass process: a measure pass and a layout pass. The measuring
378 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
379 * of the view tree. Each view pushes dimension specifications down the tree
380 * during the recursion. At the end of the measure pass, every view has stored
381 * its measurements. The second pass happens in
382 * {@link #layout(int,int,int,int)} and is also top-down. During
383 * this pass each parent is responsible for positioning all of its children
384 * using the sizes computed in the measure pass.
385 * </p>
386 *
387 * <p>
388 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
389 * {@link #getMeasuredHeight()} values must be set, along with those for all of
390 * that view's descendants. A view's measured width and measured height values
391 * must respect the constraints imposed by the view's parents. This guarantees
392 * that at the end of the measure pass, all parents accept all of their
393 * children's measurements. A parent view may call measure() more than once on
394 * its children. For example, the parent may measure each child once with
395 * unspecified dimensions to find out how big they want to be, then call
396 * measure() on them again with actual numbers if the sum of all the children's
397 * unconstrained sizes is too big or too small.
398 * </p>
399 *
400 * <p>
401 * The measure pass uses two classes to communicate dimensions. The
402 * {@link MeasureSpec} class is used by views to tell their parents how they
403 * want to be measured and positioned. The base LayoutParams class just
404 * describes how big the view wants to be for both width and height. For each
405 * dimension, it can specify one of:
406 * <ul>
407 * <li> an exact number
408 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
409 * (minus padding)
410 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
411 * enclose its content (plus padding).
412 * </ul>
413 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
414 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
415 * an X and Y value.
416 * </p>
417 *
418 * <p>
419 * MeasureSpecs are used to push requirements down the tree from parent to
420 * child. A MeasureSpec can be in one of three modes:
421 * <ul>
422 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
423 * of a child view. For example, a LinearLayout may call measure() on its child
424 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
425 * tall the child view wants to be given a width of 240 pixels.
426 * <li>EXACTLY: This is used by the parent to impose an exact size on the
427 * child. The child must use this size, and guarantee that all of its
428 * descendants will fit within this size.
429 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
430 * child. The child must gurantee that it and all of its descendants will fit
431 * within this size.
432 * </ul>
433 * </p>
434 *
435 * <p>
436 * To intiate a layout, call {@link #requestLayout}. This method is typically
437 * called by a view on itself when it believes that is can no longer fit within
438 * its current bounds.
439 * </p>
440 *
441 * <a name="Drawing"></a>
442 * <h3>Drawing</h3>
443 * <p>
444 * Drawing is handled by walking the tree and rendering each view that
445 * intersects the invalid region. Because the tree is traversed in-order,
446 * this means that parents will draw before (i.e., behind) their children, with
447 * siblings drawn in the order they appear in the tree.
448 * If you set a background drawable for a View, then the View will draw it for you
449 * before calling back to its <code>onDraw()</code> method.
450 * </p>
451 *
452 * <p>
453 * Note that the framework will not draw views that are not in the invalid region.
454 * </p>
455 *
456 * <p>
457 * To force a view to draw, call {@link #invalidate()}.
458 * </p>
459 *
460 * <a name="EventHandlingThreading"></a>
461 * <h3>Event Handling and Threading</h3>
462 * <p>
463 * The basic cycle of a view is as follows:
464 * <ol>
465 * <li>An event comes in and is dispatched to the appropriate view. The view
466 * handles the event and notifies any listeners.</li>
467 * <li>If in the course of processing the event, the view's bounds may need
468 * to be changed, the view will call {@link #requestLayout()}.</li>
469 * <li>Similarly, if in the course of processing the event the view's appearance
470 * may need to be changed, the view will call {@link #invalidate()}.</li>
471 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
472 * the framework will take care of measuring, laying out, and drawing the tree
473 * as appropriate.</li>
474 * </ol>
475 * </p>
476 *
477 * <p><em>Note: The entire view tree is single threaded. You must always be on
478 * the UI thread when calling any method on any view.</em>
479 * If you are doing work on other threads and want to update the state of a view
480 * from that thread, you should use a {@link Handler}.
481 * </p>
482 *
483 * <a name="FocusHandling"></a>
484 * <h3>Focus Handling</h3>
485 * <p>
486 * The framework will handle routine focus movement in response to user input.
487 * This includes changing the focus as views are removed or hidden, or as new
488 * views become available. Views indicate their willingness to take focus
489 * through the {@link #isFocusable} method. To change whether a view can take
490 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
491 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
492 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
493 * </p>
494 * <p>
495 * Focus movement is based on an algorithm which finds the nearest neighbor in a
496 * given direction. In rare cases, the default algorithm may not match the
497 * intended behavior of the developer. In these situations, you can provide
498 * explicit overrides by using these XML attributes in the layout file:
499 * <pre>
500 * nextFocusDown
501 * nextFocusLeft
502 * nextFocusRight
503 * nextFocusUp
504 * </pre>
505 * </p>
506 *
507 *
508 * <p>
509 * To get a particular view to take focus, call {@link #requestFocus()}.
510 * </p>
511 *
512 * <a name="TouchMode"></a>
513 * <h3>Touch Mode</h3>
514 * <p>
515 * When a user is navigating a user interface via directional keys such as a D-pad, it is
516 * necessary to give focus to actionable items such as buttons so the user can see
517 * what will take input.  If the device has touch capabilities, however, and the user
518 * begins interacting with the interface by touching it, it is no longer necessary to
519 * always highlight, or give focus to, a particular view.  This motivates a mode
520 * for interaction named 'touch mode'.
521 * </p>
522 * <p>
523 * For a touch capable device, once the user touches the screen, the device
524 * will enter touch mode.  From this point onward, only views for which
525 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
526 * Other views that are touchable, like buttons, will not take focus when touched; they will
527 * only fire the on click listeners.
528 * </p>
529 * <p>
530 * Any time a user hits a directional key, such as a D-pad direction, the view device will
531 * exit touch mode, and find a view to take focus, so that the user may resume interacting
532 * with the user interface without touching the screen again.
533 * </p>
534 * <p>
535 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
536 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
537 * </p>
538 *
539 * <a name="Scrolling"></a>
540 * <h3>Scrolling</h3>
541 * <p>
542 * The framework provides basic support for views that wish to internally
543 * scroll their content. This includes keeping track of the X and Y scroll
544 * offset as well as mechanisms for drawing scrollbars. See
545 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
546 * {@link #awakenScrollBars()} for more details.
547 * </p>
548 *
549 * <a name="Tags"></a>
550 * <h3>Tags</h3>
551 * <p>
552 * Unlike IDs, tags are not used to identify views. Tags are essentially an
553 * extra piece of information that can be associated with a view. They are most
554 * often used as a convenience to store data related to views in the views
555 * themselves rather than by putting them in a separate structure.
556 * </p>
557 *
558 * <a name="Properties"></a>
559 * <h3>Properties</h3>
560 * <p>
561 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
562 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
563 * available both in the {@link Property} form as well as in similarly-named setter/getter
564 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
565 * be used to set persistent state associated with these rendering-related properties on the view.
566 * The properties and methods can also be used in conjunction with
567 * {@link android.animation.Animator Animator}-based animations, described more in the
568 * <a href="#Animation">Animation</a> section.
569 * </p>
570 *
571 * <a name="Animation"></a>
572 * <h3>Animation</h3>
573 * <p>
574 * Starting with Android 3.0, the preferred way of animating views is to use the
575 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
576 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
577 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
578 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
579 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
580 * makes animating these View properties particularly easy and efficient.
581 * </p>
582 * <p>
583 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
584 * You can attach an {@link Animation} object to a view using
585 * {@link #setAnimation(Animation)} or
586 * {@link #startAnimation(Animation)}. The animation can alter the scale,
587 * rotation, translation and alpha of a view over time. If the animation is
588 * attached to a view that has children, the animation will affect the entire
589 * subtree rooted by that node. When an animation is started, the framework will
590 * take care of redrawing the appropriate views until the animation completes.
591 * </p>
592 *
593 * <a name="Security"></a>
594 * <h3>Security</h3>
595 * <p>
596 * Sometimes it is essential that an application be able to verify that an action
597 * is being performed with the full knowledge and consent of the user, such as
598 * granting a permission request, making a purchase or clicking on an advertisement.
599 * Unfortunately, a malicious application could try to spoof the user into
600 * performing these actions, unaware, by concealing the intended purpose of the view.
601 * As a remedy, the framework offers a touch filtering mechanism that can be used to
602 * improve the security of views that provide access to sensitive functionality.
603 * </p><p>
604 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
605 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
606 * will discard touches that are received whenever the view's window is obscured by
607 * another visible window.  As a result, the view will not receive touches whenever a
608 * toast, dialog or other window appears above the view's window.
609 * </p><p>
610 * For more fine-grained control over security, consider overriding the
611 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
612 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
613 * </p>
614 *
615 * @attr ref android.R.styleable#View_alpha
616 * @attr ref android.R.styleable#View_background
617 * @attr ref android.R.styleable#View_clickable
618 * @attr ref android.R.styleable#View_contentDescription
619 * @attr ref android.R.styleable#View_drawingCacheQuality
620 * @attr ref android.R.styleable#View_duplicateParentState
621 * @attr ref android.R.styleable#View_id
622 * @attr ref android.R.styleable#View_requiresFadingEdge
623 * @attr ref android.R.styleable#View_fadeScrollbars
624 * @attr ref android.R.styleable#View_fadingEdgeLength
625 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
626 * @attr ref android.R.styleable#View_fitsSystemWindows
627 * @attr ref android.R.styleable#View_isScrollContainer
628 * @attr ref android.R.styleable#View_focusable
629 * @attr ref android.R.styleable#View_focusableInTouchMode
630 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
631 * @attr ref android.R.styleable#View_keepScreenOn
632 * @attr ref android.R.styleable#View_layerType
633 * @attr ref android.R.styleable#View_layoutDirection
634 * @attr ref android.R.styleable#View_longClickable
635 * @attr ref android.R.styleable#View_minHeight
636 * @attr ref android.R.styleable#View_minWidth
637 * @attr ref android.R.styleable#View_nextFocusDown
638 * @attr ref android.R.styleable#View_nextFocusLeft
639 * @attr ref android.R.styleable#View_nextFocusRight
640 * @attr ref android.R.styleable#View_nextFocusUp
641 * @attr ref android.R.styleable#View_onClick
642 * @attr ref android.R.styleable#View_padding
643 * @attr ref android.R.styleable#View_paddingBottom
644 * @attr ref android.R.styleable#View_paddingLeft
645 * @attr ref android.R.styleable#View_paddingRight
646 * @attr ref android.R.styleable#View_paddingTop
647 * @attr ref android.R.styleable#View_paddingStart
648 * @attr ref android.R.styleable#View_paddingEnd
649 * @attr ref android.R.styleable#View_saveEnabled
650 * @attr ref android.R.styleable#View_rotation
651 * @attr ref android.R.styleable#View_rotationX
652 * @attr ref android.R.styleable#View_rotationY
653 * @attr ref android.R.styleable#View_scaleX
654 * @attr ref android.R.styleable#View_scaleY
655 * @attr ref android.R.styleable#View_scrollX
656 * @attr ref android.R.styleable#View_scrollY
657 * @attr ref android.R.styleable#View_scrollbarSize
658 * @attr ref android.R.styleable#View_scrollbarStyle
659 * @attr ref android.R.styleable#View_scrollbars
660 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
661 * @attr ref android.R.styleable#View_scrollbarFadeDuration
662 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
663 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
664 * @attr ref android.R.styleable#View_scrollbarThumbVertical
665 * @attr ref android.R.styleable#View_scrollbarTrackVertical
666 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
667 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
668 * @attr ref android.R.styleable#View_sharedElementName
669 * @attr ref android.R.styleable#View_soundEffectsEnabled
670 * @attr ref android.R.styleable#View_tag
671 * @attr ref android.R.styleable#View_textAlignment
672 * @attr ref android.R.styleable#View_textDirection
673 * @attr ref android.R.styleable#View_transformPivotX
674 * @attr ref android.R.styleable#View_transformPivotY
675 * @attr ref android.R.styleable#View_translationX
676 * @attr ref android.R.styleable#View_translationY
677 * @attr ref android.R.styleable#View_translationZ
678 * @attr ref android.R.styleable#View_visibility
679 *
680 * @see android.view.ViewGroup
681 */
682public class View implements Drawable.Callback, KeyEvent.Callback,
683        AccessibilityEventSource {
684    private static final boolean DBG = false;
685
686    /**
687     * The logging tag used by this class with android.util.Log.
688     */
689    protected static final String VIEW_LOG_TAG = "View";
690
691    /**
692     * When set to true, apps will draw debugging information about their layouts.
693     *
694     * @hide
695     */
696    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
697
698    /**
699     * Used to mark a View that has no ID.
700     */
701    public static final int NO_ID = -1;
702
703    /**
704     * Signals that compatibility booleans have been initialized according to
705     * target SDK versions.
706     */
707    private static boolean sCompatibilityDone = false;
708
709    /**
710     * Use the old (broken) way of building MeasureSpecs.
711     */
712    private static boolean sUseBrokenMakeMeasureSpec = false;
713
714    /**
715     * Ignore any optimizations using the measure cache.
716     */
717    private static boolean sIgnoreMeasureCache = false;
718
719    /**
720     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
721     * calling setFlags.
722     */
723    private static final int NOT_FOCUSABLE = 0x00000000;
724
725    /**
726     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
727     * setFlags.
728     */
729    private static final int FOCUSABLE = 0x00000001;
730
731    /**
732     * Mask for use with setFlags indicating bits used for focus.
733     */
734    private static final int FOCUSABLE_MASK = 0x00000001;
735
736    /**
737     * This view will adjust its padding to fit sytem windows (e.g. status bar)
738     */
739    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
740
741    /** @hide */
742    @IntDef({VISIBLE, INVISIBLE, GONE})
743    @Retention(RetentionPolicy.SOURCE)
744    public @interface Visibility {}
745
746    /**
747     * This view is visible.
748     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
749     * android:visibility}.
750     */
751    public static final int VISIBLE = 0x00000000;
752
753    /**
754     * This view is invisible, but it still takes up space for layout purposes.
755     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
756     * android:visibility}.
757     */
758    public static final int INVISIBLE = 0x00000004;
759
760    /**
761     * This view is invisible, and it doesn't take any space for layout
762     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
763     * android:visibility}.
764     */
765    public static final int GONE = 0x00000008;
766
767    /**
768     * Mask for use with setFlags indicating bits used for visibility.
769     * {@hide}
770     */
771    static final int VISIBILITY_MASK = 0x0000000C;
772
773    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
774
775    /**
776     * This view is enabled. Interpretation varies by subclass.
777     * Use with ENABLED_MASK when calling setFlags.
778     * {@hide}
779     */
780    static final int ENABLED = 0x00000000;
781
782    /**
783     * This view is disabled. Interpretation varies by subclass.
784     * Use with ENABLED_MASK when calling setFlags.
785     * {@hide}
786     */
787    static final int DISABLED = 0x00000020;
788
789   /**
790    * Mask for use with setFlags indicating bits used for indicating whether
791    * this view is enabled
792    * {@hide}
793    */
794    static final int ENABLED_MASK = 0x00000020;
795
796    /**
797     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
798     * called and further optimizations will be performed. It is okay to have
799     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
800     * {@hide}
801     */
802    static final int WILL_NOT_DRAW = 0x00000080;
803
804    /**
805     * Mask for use with setFlags indicating bits used for indicating whether
806     * this view is will draw
807     * {@hide}
808     */
809    static final int DRAW_MASK = 0x00000080;
810
811    /**
812     * <p>This view doesn't show scrollbars.</p>
813     * {@hide}
814     */
815    static final int SCROLLBARS_NONE = 0x00000000;
816
817    /**
818     * <p>This view shows horizontal scrollbars.</p>
819     * {@hide}
820     */
821    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
822
823    /**
824     * <p>This view shows vertical scrollbars.</p>
825     * {@hide}
826     */
827    static final int SCROLLBARS_VERTICAL = 0x00000200;
828
829    /**
830     * <p>Mask for use with setFlags indicating bits used for indicating which
831     * scrollbars are enabled.</p>
832     * {@hide}
833     */
834    static final int SCROLLBARS_MASK = 0x00000300;
835
836    /**
837     * Indicates that the view should filter touches when its window is obscured.
838     * Refer to the class comments for more information about this security feature.
839     * {@hide}
840     */
841    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
842
843    /**
844     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
845     * that they are optional and should be skipped if the window has
846     * requested system UI flags that ignore those insets for layout.
847     */
848    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
849
850    /**
851     * <p>This view doesn't show fading edges.</p>
852     * {@hide}
853     */
854    static final int FADING_EDGE_NONE = 0x00000000;
855
856    /**
857     * <p>This view shows horizontal fading edges.</p>
858     * {@hide}
859     */
860    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
861
862    /**
863     * <p>This view shows vertical fading edges.</p>
864     * {@hide}
865     */
866    static final int FADING_EDGE_VERTICAL = 0x00002000;
867
868    /**
869     * <p>Mask for use with setFlags indicating bits used for indicating which
870     * fading edges are enabled.</p>
871     * {@hide}
872     */
873    static final int FADING_EDGE_MASK = 0x00003000;
874
875    /**
876     * <p>Indicates this view can be clicked. When clickable, a View reacts
877     * to clicks by notifying the OnClickListener.<p>
878     * {@hide}
879     */
880    static final int CLICKABLE = 0x00004000;
881
882    /**
883     * <p>Indicates this view is caching its drawing into a bitmap.</p>
884     * {@hide}
885     */
886    static final int DRAWING_CACHE_ENABLED = 0x00008000;
887
888    /**
889     * <p>Indicates that no icicle should be saved for this view.<p>
890     * {@hide}
891     */
892    static final int SAVE_DISABLED = 0x000010000;
893
894    /**
895     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
896     * property.</p>
897     * {@hide}
898     */
899    static final int SAVE_DISABLED_MASK = 0x000010000;
900
901    /**
902     * <p>Indicates that no drawing cache should ever be created for this view.<p>
903     * {@hide}
904     */
905    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
906
907    /**
908     * <p>Indicates this view can take / keep focus when int touch mode.</p>
909     * {@hide}
910     */
911    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
912
913    /** @hide */
914    @Retention(RetentionPolicy.SOURCE)
915    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
916    public @interface DrawingCacheQuality {}
917
918    /**
919     * <p>Enables low quality mode for the drawing cache.</p>
920     */
921    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
922
923    /**
924     * <p>Enables high quality mode for the drawing cache.</p>
925     */
926    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
927
928    /**
929     * <p>Enables automatic quality mode for the drawing cache.</p>
930     */
931    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
932
933    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
934            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
935    };
936
937    /**
938     * <p>Mask for use with setFlags indicating bits used for the cache
939     * quality property.</p>
940     * {@hide}
941     */
942    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
943
944    /**
945     * <p>
946     * Indicates this view can be long clicked. When long clickable, a View
947     * reacts to long clicks by notifying the OnLongClickListener or showing a
948     * context menu.
949     * </p>
950     * {@hide}
951     */
952    static final int LONG_CLICKABLE = 0x00200000;
953
954    /**
955     * <p>Indicates that this view gets its drawable states from its direct parent
956     * and ignores its original internal states.</p>
957     *
958     * @hide
959     */
960    static final int DUPLICATE_PARENT_STATE = 0x00400000;
961
962    /** @hide */
963    @IntDef({
964        SCROLLBARS_INSIDE_OVERLAY,
965        SCROLLBARS_INSIDE_INSET,
966        SCROLLBARS_OUTSIDE_OVERLAY,
967        SCROLLBARS_OUTSIDE_INSET
968    })
969    @Retention(RetentionPolicy.SOURCE)
970    public @interface ScrollBarStyle {}
971
972    /**
973     * The scrollbar style to display the scrollbars inside the content area,
974     * without increasing the padding. The scrollbars will be overlaid with
975     * translucency on the view's content.
976     */
977    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
978
979    /**
980     * The scrollbar style to display the scrollbars inside the padded area,
981     * increasing the padding of the view. The scrollbars will not overlap the
982     * content area of the view.
983     */
984    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
985
986    /**
987     * The scrollbar style to display the scrollbars at the edge of the view,
988     * without increasing the padding. The scrollbars will be overlaid with
989     * translucency.
990     */
991    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
992
993    /**
994     * The scrollbar style to display the scrollbars at the edge of the view,
995     * increasing the padding of the view. The scrollbars will only overlap the
996     * background, if any.
997     */
998    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
999
1000    /**
1001     * Mask to check if the scrollbar style is overlay or inset.
1002     * {@hide}
1003     */
1004    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1005
1006    /**
1007     * Mask to check if the scrollbar style is inside or outside.
1008     * {@hide}
1009     */
1010    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1011
1012    /**
1013     * Mask for scrollbar style.
1014     * {@hide}
1015     */
1016    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1017
1018    /**
1019     * View flag indicating that the screen should remain on while the
1020     * window containing this view is visible to the user.  This effectively
1021     * takes care of automatically setting the WindowManager's
1022     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1023     */
1024    public static final int KEEP_SCREEN_ON = 0x04000000;
1025
1026    /**
1027     * View flag indicating whether this view should have sound effects enabled
1028     * for events such as clicking and touching.
1029     */
1030    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1031
1032    /**
1033     * View flag indicating whether this view should have haptic feedback
1034     * enabled for events such as long presses.
1035     */
1036    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1037
1038    /**
1039     * <p>Indicates that the view hierarchy should stop saving state when
1040     * it reaches this view.  If state saving is initiated immediately at
1041     * the view, it will be allowed.
1042     * {@hide}
1043     */
1044    static final int PARENT_SAVE_DISABLED = 0x20000000;
1045
1046    /**
1047     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1048     * {@hide}
1049     */
1050    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1051
1052    /** @hide */
1053    @IntDef(flag = true,
1054            value = {
1055                FOCUSABLES_ALL,
1056                FOCUSABLES_TOUCH_MODE
1057            })
1058    @Retention(RetentionPolicy.SOURCE)
1059    public @interface FocusableMode {}
1060
1061    /**
1062     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1063     * should add all focusable Views regardless if they are focusable in touch mode.
1064     */
1065    public static final int FOCUSABLES_ALL = 0x00000000;
1066
1067    /**
1068     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1069     * should add only Views focusable in touch mode.
1070     */
1071    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1072
1073    /** @hide */
1074    @IntDef({
1075            FOCUS_BACKWARD,
1076            FOCUS_FORWARD,
1077            FOCUS_LEFT,
1078            FOCUS_UP,
1079            FOCUS_RIGHT,
1080            FOCUS_DOWN
1081    })
1082    @Retention(RetentionPolicy.SOURCE)
1083    public @interface FocusDirection {}
1084
1085    /** @hide */
1086    @IntDef({
1087            FOCUS_LEFT,
1088            FOCUS_UP,
1089            FOCUS_RIGHT,
1090            FOCUS_DOWN
1091    })
1092    @Retention(RetentionPolicy.SOURCE)
1093    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1094
1095    /**
1096     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1097     * item.
1098     */
1099    public static final int FOCUS_BACKWARD = 0x00000001;
1100
1101    /**
1102     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1103     * item.
1104     */
1105    public static final int FOCUS_FORWARD = 0x00000002;
1106
1107    /**
1108     * Use with {@link #focusSearch(int)}. Move focus to the left.
1109     */
1110    public static final int FOCUS_LEFT = 0x00000011;
1111
1112    /**
1113     * Use with {@link #focusSearch(int)}. Move focus up.
1114     */
1115    public static final int FOCUS_UP = 0x00000021;
1116
1117    /**
1118     * Use with {@link #focusSearch(int)}. Move focus to the right.
1119     */
1120    public static final int FOCUS_RIGHT = 0x00000042;
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus down.
1124     */
1125    public static final int FOCUS_DOWN = 0x00000082;
1126
1127    /**
1128     * Bits of {@link #getMeasuredWidthAndState()} and
1129     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1130     */
1131    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1132
1133    /**
1134     * Bits of {@link #getMeasuredWidthAndState()} and
1135     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1136     */
1137    public static final int MEASURED_STATE_MASK = 0xff000000;
1138
1139    /**
1140     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1141     * for functions that combine both width and height into a single int,
1142     * such as {@link #getMeasuredState()} and the childState argument of
1143     * {@link #resolveSizeAndState(int, int, int)}.
1144     */
1145    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1146
1147    /**
1148     * Bit of {@link #getMeasuredWidthAndState()} and
1149     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1150     * is smaller that the space the view would like to have.
1151     */
1152    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1153
1154    /**
1155     * Base View state sets
1156     */
1157    // Singles
1158    /**
1159     * Indicates the view has no states set. States are used with
1160     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1161     * view depending on its state.
1162     *
1163     * @see android.graphics.drawable.Drawable
1164     * @see #getDrawableState()
1165     */
1166    protected static final int[] EMPTY_STATE_SET;
1167    /**
1168     * Indicates the view is enabled. States are used with
1169     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1170     * view depending on its state.
1171     *
1172     * @see android.graphics.drawable.Drawable
1173     * @see #getDrawableState()
1174     */
1175    protected static final int[] ENABLED_STATE_SET;
1176    /**
1177     * Indicates the view is focused. States are used with
1178     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1179     * view depending on its state.
1180     *
1181     * @see android.graphics.drawable.Drawable
1182     * @see #getDrawableState()
1183     */
1184    protected static final int[] FOCUSED_STATE_SET;
1185    /**
1186     * Indicates the view is selected. States are used with
1187     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1188     * view depending on its state.
1189     *
1190     * @see android.graphics.drawable.Drawable
1191     * @see #getDrawableState()
1192     */
1193    protected static final int[] SELECTED_STATE_SET;
1194    /**
1195     * Indicates the view is pressed. States are used with
1196     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1197     * view depending on its state.
1198     *
1199     * @see android.graphics.drawable.Drawable
1200     * @see #getDrawableState()
1201     */
1202    protected static final int[] PRESSED_STATE_SET;
1203    /**
1204     * Indicates the view's window has focus. States are used with
1205     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1206     * view depending on its state.
1207     *
1208     * @see android.graphics.drawable.Drawable
1209     * @see #getDrawableState()
1210     */
1211    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1212    // Doubles
1213    /**
1214     * Indicates the view is enabled and has the focus.
1215     *
1216     * @see #ENABLED_STATE_SET
1217     * @see #FOCUSED_STATE_SET
1218     */
1219    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1220    /**
1221     * Indicates the view is enabled and selected.
1222     *
1223     * @see #ENABLED_STATE_SET
1224     * @see #SELECTED_STATE_SET
1225     */
1226    protected static final int[] ENABLED_SELECTED_STATE_SET;
1227    /**
1228     * Indicates the view is enabled and that its window has focus.
1229     *
1230     * @see #ENABLED_STATE_SET
1231     * @see #WINDOW_FOCUSED_STATE_SET
1232     */
1233    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1234    /**
1235     * Indicates the view is focused and selected.
1236     *
1237     * @see #FOCUSED_STATE_SET
1238     * @see #SELECTED_STATE_SET
1239     */
1240    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1241    /**
1242     * Indicates the view has the focus and that its window has the focus.
1243     *
1244     * @see #FOCUSED_STATE_SET
1245     * @see #WINDOW_FOCUSED_STATE_SET
1246     */
1247    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1248    /**
1249     * Indicates the view is selected and that its window has the focus.
1250     *
1251     * @see #SELECTED_STATE_SET
1252     * @see #WINDOW_FOCUSED_STATE_SET
1253     */
1254    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1255    // Triples
1256    /**
1257     * Indicates the view is enabled, focused and selected.
1258     *
1259     * @see #ENABLED_STATE_SET
1260     * @see #FOCUSED_STATE_SET
1261     * @see #SELECTED_STATE_SET
1262     */
1263    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1264    /**
1265     * Indicates the view is enabled, focused and its window has the focus.
1266     *
1267     * @see #ENABLED_STATE_SET
1268     * @see #FOCUSED_STATE_SET
1269     * @see #WINDOW_FOCUSED_STATE_SET
1270     */
1271    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1272    /**
1273     * Indicates the view is enabled, selected and its window has the focus.
1274     *
1275     * @see #ENABLED_STATE_SET
1276     * @see #SELECTED_STATE_SET
1277     * @see #WINDOW_FOCUSED_STATE_SET
1278     */
1279    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1280    /**
1281     * Indicates the view is focused, selected and its window has the focus.
1282     *
1283     * @see #FOCUSED_STATE_SET
1284     * @see #SELECTED_STATE_SET
1285     * @see #WINDOW_FOCUSED_STATE_SET
1286     */
1287    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is enabled, focused, selected and its window
1290     * has the focus.
1291     *
1292     * @see #ENABLED_STATE_SET
1293     * @see #FOCUSED_STATE_SET
1294     * @see #SELECTED_STATE_SET
1295     * @see #WINDOW_FOCUSED_STATE_SET
1296     */
1297    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is pressed and its window has the focus.
1300     *
1301     * @see #PRESSED_STATE_SET
1302     * @see #WINDOW_FOCUSED_STATE_SET
1303     */
1304    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1305    /**
1306     * Indicates the view is pressed and selected.
1307     *
1308     * @see #PRESSED_STATE_SET
1309     * @see #SELECTED_STATE_SET
1310     */
1311    protected static final int[] PRESSED_SELECTED_STATE_SET;
1312    /**
1313     * Indicates the view is pressed, selected and its window has the focus.
1314     *
1315     * @see #PRESSED_STATE_SET
1316     * @see #SELECTED_STATE_SET
1317     * @see #WINDOW_FOCUSED_STATE_SET
1318     */
1319    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1320    /**
1321     * Indicates the view is pressed and focused.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #FOCUSED_STATE_SET
1325     */
1326    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1327    /**
1328     * Indicates the view is pressed, focused and its window has the focus.
1329     *
1330     * @see #PRESSED_STATE_SET
1331     * @see #FOCUSED_STATE_SET
1332     * @see #WINDOW_FOCUSED_STATE_SET
1333     */
1334    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1335    /**
1336     * Indicates the view is pressed, focused and selected.
1337     *
1338     * @see #PRESSED_STATE_SET
1339     * @see #SELECTED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     */
1342    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1343    /**
1344     * Indicates the view is pressed, focused, selected and its window has the focus.
1345     *
1346     * @see #PRESSED_STATE_SET
1347     * @see #FOCUSED_STATE_SET
1348     * @see #SELECTED_STATE_SET
1349     * @see #WINDOW_FOCUSED_STATE_SET
1350     */
1351    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1352    /**
1353     * Indicates the view is pressed and enabled.
1354     *
1355     * @see #PRESSED_STATE_SET
1356     * @see #ENABLED_STATE_SET
1357     */
1358    protected static final int[] PRESSED_ENABLED_STATE_SET;
1359    /**
1360     * Indicates the view is pressed, enabled and its window has the focus.
1361     *
1362     * @see #PRESSED_STATE_SET
1363     * @see #ENABLED_STATE_SET
1364     * @see #WINDOW_FOCUSED_STATE_SET
1365     */
1366    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1367    /**
1368     * Indicates the view is pressed, enabled and selected.
1369     *
1370     * @see #PRESSED_STATE_SET
1371     * @see #ENABLED_STATE_SET
1372     * @see #SELECTED_STATE_SET
1373     */
1374    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1375    /**
1376     * Indicates the view is pressed, enabled, selected and its window has the
1377     * focus.
1378     *
1379     * @see #PRESSED_STATE_SET
1380     * @see #ENABLED_STATE_SET
1381     * @see #SELECTED_STATE_SET
1382     * @see #WINDOW_FOCUSED_STATE_SET
1383     */
1384    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1385    /**
1386     * Indicates the view is pressed, enabled and focused.
1387     *
1388     * @see #PRESSED_STATE_SET
1389     * @see #ENABLED_STATE_SET
1390     * @see #FOCUSED_STATE_SET
1391     */
1392    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1393    /**
1394     * Indicates the view is pressed, enabled, focused and its window has the
1395     * focus.
1396     *
1397     * @see #PRESSED_STATE_SET
1398     * @see #ENABLED_STATE_SET
1399     * @see #FOCUSED_STATE_SET
1400     * @see #WINDOW_FOCUSED_STATE_SET
1401     */
1402    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1403    /**
1404     * Indicates the view is pressed, enabled, focused and selected.
1405     *
1406     * @see #PRESSED_STATE_SET
1407     * @see #ENABLED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #FOCUSED_STATE_SET
1410     */
1411    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1412    /**
1413     * Indicates the view is pressed, enabled, focused, selected and its window
1414     * has the focus.
1415     *
1416     * @see #PRESSED_STATE_SET
1417     * @see #ENABLED_STATE_SET
1418     * @see #SELECTED_STATE_SET
1419     * @see #FOCUSED_STATE_SET
1420     * @see #WINDOW_FOCUSED_STATE_SET
1421     */
1422    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1423
1424    /**
1425     * The order here is very important to {@link #getDrawableState()}
1426     */
1427    private static final int[][] VIEW_STATE_SETS;
1428
1429    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1430    static final int VIEW_STATE_SELECTED = 1 << 1;
1431    static final int VIEW_STATE_FOCUSED = 1 << 2;
1432    static final int VIEW_STATE_ENABLED = 1 << 3;
1433    static final int VIEW_STATE_PRESSED = 1 << 4;
1434    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1435    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1436    static final int VIEW_STATE_HOVERED = 1 << 7;
1437    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1438    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1439
1440    static final int[] VIEW_STATE_IDS = new int[] {
1441        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1442        R.attr.state_selected,          VIEW_STATE_SELECTED,
1443        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1444        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1445        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1446        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1447        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1448        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1449        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1450        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1451    };
1452
1453    static {
1454        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1455            throw new IllegalStateException(
1456                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1457        }
1458        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1459        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1460            int viewState = R.styleable.ViewDrawableStates[i];
1461            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1462                if (VIEW_STATE_IDS[j] == viewState) {
1463                    orderedIds[i * 2] = viewState;
1464                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1465                }
1466            }
1467        }
1468        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1469        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1470        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1471            int numBits = Integer.bitCount(i);
1472            int[] set = new int[numBits];
1473            int pos = 0;
1474            for (int j = 0; j < orderedIds.length; j += 2) {
1475                if ((i & orderedIds[j+1]) != 0) {
1476                    set[pos++] = orderedIds[j];
1477                }
1478            }
1479            VIEW_STATE_SETS[i] = set;
1480        }
1481
1482        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1483        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1484        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1485        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1487        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1488        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1490        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1491                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1492        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1494                | VIEW_STATE_FOCUSED];
1495        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1496        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1498        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1499                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1500        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1502                | VIEW_STATE_ENABLED];
1503        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1505        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1507                | VIEW_STATE_ENABLED];
1508        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1510                | VIEW_STATE_ENABLED];
1511        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1512                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1513                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1514
1515        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1516        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1518        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1519                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1520        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1521                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1522                | VIEW_STATE_PRESSED];
1523        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1524                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1525        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1527                | VIEW_STATE_PRESSED];
1528        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1529                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1530                | VIEW_STATE_PRESSED];
1531        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1532                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1533                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1534        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1535                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1536        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1538                | VIEW_STATE_PRESSED];
1539        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1541                | VIEW_STATE_PRESSED];
1542        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1543                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1544                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1545        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1546                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1547                | VIEW_STATE_PRESSED];
1548        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1549                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1550                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1551        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1552                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1553                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1554        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1555                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1556                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1557                | VIEW_STATE_PRESSED];
1558    }
1559
1560    /**
1561     * Accessibility event types that are dispatched for text population.
1562     */
1563    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1564            AccessibilityEvent.TYPE_VIEW_CLICKED
1565            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1566            | AccessibilityEvent.TYPE_VIEW_SELECTED
1567            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1568            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1569            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1570            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1571            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1572            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1573            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1574            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1575
1576    /**
1577     * Temporary Rect currently for use in setBackground().  This will probably
1578     * be extended in the future to hold our own class with more than just
1579     * a Rect. :)
1580     */
1581    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1582
1583    /**
1584     * Map used to store views' tags.
1585     */
1586    private SparseArray<Object> mKeyedTags;
1587
1588    /**
1589     * The next available accessibility id.
1590     */
1591    private static int sNextAccessibilityViewId;
1592
1593    /**
1594     * The animation currently associated with this view.
1595     * @hide
1596     */
1597    protected Animation mCurrentAnimation = null;
1598
1599    /**
1600     * Width as measured during measure pass.
1601     * {@hide}
1602     */
1603    @ViewDebug.ExportedProperty(category = "measurement")
1604    int mMeasuredWidth;
1605
1606    /**
1607     * Height as measured during measure pass.
1608     * {@hide}
1609     */
1610    @ViewDebug.ExportedProperty(category = "measurement")
1611    int mMeasuredHeight;
1612
1613    /**
1614     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1615     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1616     * its display list. This flag, used only when hw accelerated, allows us to clear the
1617     * flag while retaining this information until it's needed (at getDisplayList() time and
1618     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1619     *
1620     * {@hide}
1621     */
1622    boolean mRecreateDisplayList = false;
1623
1624    /**
1625     * The view's identifier.
1626     * {@hide}
1627     *
1628     * @see #setId(int)
1629     * @see #getId()
1630     */
1631    @ViewDebug.ExportedProperty(resolveId = true)
1632    int mID = NO_ID;
1633
1634    /**
1635     * The stable ID of this view for accessibility purposes.
1636     */
1637    int mAccessibilityViewId = NO_ID;
1638
1639    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1640
1641    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1642
1643    /**
1644     * The view's tag.
1645     * {@hide}
1646     *
1647     * @see #setTag(Object)
1648     * @see #getTag()
1649     */
1650    protected Object mTag = null;
1651
1652    // for mPrivateFlags:
1653    /** {@hide} */
1654    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1655    /** {@hide} */
1656    static final int PFLAG_FOCUSED                     = 0x00000002;
1657    /** {@hide} */
1658    static final int PFLAG_SELECTED                    = 0x00000004;
1659    /** {@hide} */
1660    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1661    /** {@hide} */
1662    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1663    /** {@hide} */
1664    static final int PFLAG_DRAWN                       = 0x00000020;
1665    /**
1666     * When this flag is set, this view is running an animation on behalf of its
1667     * children and should therefore not cancel invalidate requests, even if they
1668     * lie outside of this view's bounds.
1669     *
1670     * {@hide}
1671     */
1672    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1673    /** {@hide} */
1674    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1675    /** {@hide} */
1676    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1677    /** {@hide} */
1678    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1679    /** {@hide} */
1680    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1681    /** {@hide} */
1682    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1683    /** {@hide} */
1684    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1685    /** {@hide} */
1686    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1687
1688    private static final int PFLAG_PRESSED             = 0x00004000;
1689
1690    /** {@hide} */
1691    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1692    /**
1693     * Flag used to indicate that this view should be drawn once more (and only once
1694     * more) after its animation has completed.
1695     * {@hide}
1696     */
1697    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1698
1699    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1700
1701    /**
1702     * Indicates that the View returned true when onSetAlpha() was called and that
1703     * the alpha must be restored.
1704     * {@hide}
1705     */
1706    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1707
1708    /**
1709     * Set by {@link #setScrollContainer(boolean)}.
1710     */
1711    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1712
1713    /**
1714     * Set by {@link #setScrollContainer(boolean)}.
1715     */
1716    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1717
1718    /**
1719     * View flag indicating whether this view was invalidated (fully or partially.)
1720     *
1721     * @hide
1722     */
1723    static final int PFLAG_DIRTY                       = 0x00200000;
1724
1725    /**
1726     * View flag indicating whether this view was invalidated by an opaque
1727     * invalidate request.
1728     *
1729     * @hide
1730     */
1731    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1732
1733    /**
1734     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1735     *
1736     * @hide
1737     */
1738    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1739
1740    /**
1741     * Indicates whether the background is opaque.
1742     *
1743     * @hide
1744     */
1745    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1746
1747    /**
1748     * Indicates whether the scrollbars are opaque.
1749     *
1750     * @hide
1751     */
1752    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1753
1754    /**
1755     * Indicates whether the view is opaque.
1756     *
1757     * @hide
1758     */
1759    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1760
1761    /**
1762     * Indicates a prepressed state;
1763     * the short time between ACTION_DOWN and recognizing
1764     * a 'real' press. Prepressed is used to recognize quick taps
1765     * even when they are shorter than ViewConfiguration.getTapTimeout().
1766     *
1767     * @hide
1768     */
1769    private static final int PFLAG_PREPRESSED          = 0x02000000;
1770
1771    /**
1772     * Indicates whether the view is temporarily detached.
1773     *
1774     * @hide
1775     */
1776    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1777
1778    /**
1779     * Indicates that we should awaken scroll bars once attached
1780     *
1781     * @hide
1782     */
1783    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1784
1785    /**
1786     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1787     * @hide
1788     */
1789    private static final int PFLAG_HOVERED             = 0x10000000;
1790
1791    /**
1792     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1793     * for transform operations
1794     *
1795     * @hide
1796     */
1797    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1798
1799    /** {@hide} */
1800    static final int PFLAG_ACTIVATED                   = 0x40000000;
1801
1802    /**
1803     * Indicates that this view was specifically invalidated, not just dirtied because some
1804     * child view was invalidated. The flag is used to determine when we need to recreate
1805     * a view's display list (as opposed to just returning a reference to its existing
1806     * display list).
1807     *
1808     * @hide
1809     */
1810    static final int PFLAG_INVALIDATED                 = 0x80000000;
1811
1812    /**
1813     * Masks for mPrivateFlags2, as generated by dumpFlags():
1814     *
1815     * |-------|-------|-------|-------|
1816     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1817     *                                1  PFLAG2_DRAG_HOVERED
1818     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1819     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1820     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1821     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1822     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1823     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1824     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1825     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1826     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1827     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1828     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1829     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1830     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1831     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1832     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1833     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1834     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1835     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1836     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1837     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1838     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1839     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1840     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1841     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1842     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1843     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1844     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1845     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1846     *    1                              PFLAG2_PADDING_RESOLVED
1847     *   1                               PFLAG2_DRAWABLE_RESOLVED
1848     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1849     * |-------|-------|-------|-------|
1850     */
1851
1852    /**
1853     * Indicates that this view has reported that it can accept the current drag's content.
1854     * Cleared when the drag operation concludes.
1855     * @hide
1856     */
1857    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1858
1859    /**
1860     * Indicates that this view is currently directly under the drag location in a
1861     * drag-and-drop operation involving content that it can accept.  Cleared when
1862     * the drag exits the view, or when the drag operation concludes.
1863     * @hide
1864     */
1865    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1866
1867    /** @hide */
1868    @IntDef({
1869        LAYOUT_DIRECTION_LTR,
1870        LAYOUT_DIRECTION_RTL,
1871        LAYOUT_DIRECTION_INHERIT,
1872        LAYOUT_DIRECTION_LOCALE
1873    })
1874    @Retention(RetentionPolicy.SOURCE)
1875    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1876    public @interface LayoutDir {}
1877
1878    /** @hide */
1879    @IntDef({
1880        LAYOUT_DIRECTION_LTR,
1881        LAYOUT_DIRECTION_RTL
1882    })
1883    @Retention(RetentionPolicy.SOURCE)
1884    public @interface ResolvedLayoutDir {}
1885
1886    /**
1887     * Horizontal layout direction of this view is from Left to Right.
1888     * Use with {@link #setLayoutDirection}.
1889     */
1890    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1891
1892    /**
1893     * Horizontal layout direction of this view is from Right to Left.
1894     * Use with {@link #setLayoutDirection}.
1895     */
1896    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1897
1898    /**
1899     * Horizontal layout direction of this view is inherited from its parent.
1900     * Use with {@link #setLayoutDirection}.
1901     */
1902    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1903
1904    /**
1905     * Horizontal layout direction of this view is from deduced from the default language
1906     * script for the locale. Use with {@link #setLayoutDirection}.
1907     */
1908    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1909
1910    /**
1911     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1912     * @hide
1913     */
1914    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1915
1916    /**
1917     * Mask for use with private flags indicating bits used for horizontal layout direction.
1918     * @hide
1919     */
1920    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1921
1922    /**
1923     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1924     * right-to-left direction.
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1928
1929    /**
1930     * Indicates whether the view horizontal layout direction has been resolved.
1931     * @hide
1932     */
1933    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1934
1935    /**
1936     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1937     * @hide
1938     */
1939    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1940            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1941
1942    /*
1943     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1944     * flag value.
1945     * @hide
1946     */
1947    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1948            LAYOUT_DIRECTION_LTR,
1949            LAYOUT_DIRECTION_RTL,
1950            LAYOUT_DIRECTION_INHERIT,
1951            LAYOUT_DIRECTION_LOCALE
1952    };
1953
1954    /**
1955     * Default horizontal layout direction.
1956     */
1957    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1958
1959    /**
1960     * Default horizontal layout direction.
1961     * @hide
1962     */
1963    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1964
1965    /**
1966     * Text direction is inherited thru {@link ViewGroup}
1967     */
1968    public static final int TEXT_DIRECTION_INHERIT = 0;
1969
1970    /**
1971     * Text direction is using "first strong algorithm". The first strong directional character
1972     * determines the paragraph direction. If there is no strong directional character, the
1973     * paragraph direction is the view's resolved layout direction.
1974     */
1975    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1976
1977    /**
1978     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1979     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1980     * If there are neither, the paragraph direction is the view's resolved layout direction.
1981     */
1982    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1983
1984    /**
1985     * Text direction is forced to LTR.
1986     */
1987    public static final int TEXT_DIRECTION_LTR = 3;
1988
1989    /**
1990     * Text direction is forced to RTL.
1991     */
1992    public static final int TEXT_DIRECTION_RTL = 4;
1993
1994    /**
1995     * Text direction is coming from the system Locale.
1996     */
1997    public static final int TEXT_DIRECTION_LOCALE = 5;
1998
1999    /**
2000     * Default text direction is inherited
2001     */
2002    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2003
2004    /**
2005     * Default resolved text direction
2006     * @hide
2007     */
2008    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2009
2010    /**
2011     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2012     * @hide
2013     */
2014    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2015
2016    /**
2017     * Mask for use with private flags indicating bits used for text direction.
2018     * @hide
2019     */
2020    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2021            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2022
2023    /**
2024     * Array of text direction flags for mapping attribute "textDirection" to correct
2025     * flag value.
2026     * @hide
2027     */
2028    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2029            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2030            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2031            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2035    };
2036
2037    /**
2038     * Indicates whether the view text direction has been resolved.
2039     * @hide
2040     */
2041    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2042            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2043
2044    /**
2045     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2046     * @hide
2047     */
2048    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2049
2050    /**
2051     * Mask for use with private flags indicating bits used for resolved text direction.
2052     * @hide
2053     */
2054    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2055            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2056
2057    /**
2058     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2059     * @hide
2060     */
2061    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2062            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2063
2064    /** @hide */
2065    @IntDef({
2066        TEXT_ALIGNMENT_INHERIT,
2067        TEXT_ALIGNMENT_GRAVITY,
2068        TEXT_ALIGNMENT_CENTER,
2069        TEXT_ALIGNMENT_TEXT_START,
2070        TEXT_ALIGNMENT_TEXT_END,
2071        TEXT_ALIGNMENT_VIEW_START,
2072        TEXT_ALIGNMENT_VIEW_END
2073    })
2074    @Retention(RetentionPolicy.SOURCE)
2075    public @interface TextAlignment {}
2076
2077    /**
2078     * Default text alignment. The text alignment of this View is inherited from its parent.
2079     * Use with {@link #setTextAlignment(int)}
2080     */
2081    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2082
2083    /**
2084     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2085     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2086     *
2087     * Use with {@link #setTextAlignment(int)}
2088     */
2089    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2090
2091    /**
2092     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2093     *
2094     * Use with {@link #setTextAlignment(int)}
2095     */
2096    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2097
2098    /**
2099     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2100     *
2101     * Use with {@link #setTextAlignment(int)}
2102     */
2103    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2104
2105    /**
2106     * Center the paragraph, e.g. ALIGN_CENTER.
2107     *
2108     * Use with {@link #setTextAlignment(int)}
2109     */
2110    public static final int TEXT_ALIGNMENT_CENTER = 4;
2111
2112    /**
2113     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2114     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2115     *
2116     * Use with {@link #setTextAlignment(int)}
2117     */
2118    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2119
2120    /**
2121     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2122     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2123     *
2124     * Use with {@link #setTextAlignment(int)}
2125     */
2126    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2127
2128    /**
2129     * Default text alignment is inherited
2130     */
2131    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2132
2133    /**
2134     * Default resolved text alignment
2135     * @hide
2136     */
2137    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2138
2139    /**
2140      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2141      * @hide
2142      */
2143    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2144
2145    /**
2146      * Mask for use with private flags indicating bits used for text alignment.
2147      * @hide
2148      */
2149    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2150
2151    /**
2152     * Array of text direction flags for mapping attribute "textAlignment" to correct
2153     * flag value.
2154     * @hide
2155     */
2156    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2157            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2158            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2159            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2164    };
2165
2166    /**
2167     * Indicates whether the view text alignment has been resolved.
2168     * @hide
2169     */
2170    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2171
2172    /**
2173     * Bit shift to get the resolved text alignment.
2174     * @hide
2175     */
2176    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2177
2178    /**
2179     * Mask for use with private flags indicating bits used for text alignment.
2180     * @hide
2181     */
2182    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2183            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2184
2185    /**
2186     * Indicates whether if the view text alignment has been resolved to gravity
2187     */
2188    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2189            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2190
2191    // Accessiblity constants for mPrivateFlags2
2192
2193    /**
2194     * Shift for the bits in {@link #mPrivateFlags2} related to the
2195     * "importantForAccessibility" attribute.
2196     */
2197    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2198
2199    /**
2200     * Automatically determine whether a view is important for accessibility.
2201     */
2202    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2203
2204    /**
2205     * The view is important for accessibility.
2206     */
2207    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2208
2209    /**
2210     * The view is not important for accessibility.
2211     */
2212    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2213
2214    /**
2215     * The view is not important for accessibility, nor are any of its
2216     * descendant views.
2217     */
2218    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2219
2220    /**
2221     * The default whether the view is important for accessibility.
2222     */
2223    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2224
2225    /**
2226     * Mask for obtainig the bits which specify how to determine
2227     * whether a view is important for accessibility.
2228     */
2229    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2230        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2231        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2232        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2233
2234    /**
2235     * Shift for the bits in {@link #mPrivateFlags2} related to the
2236     * "accessibilityLiveRegion" attribute.
2237     */
2238    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2239
2240    /**
2241     * Live region mode specifying that accessibility services should not
2242     * automatically announce changes to this view. This is the default live
2243     * region mode for most views.
2244     * <p>
2245     * Use with {@link #setAccessibilityLiveRegion(int)}.
2246     */
2247    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2248
2249    /**
2250     * Live region mode specifying that accessibility services should announce
2251     * changes to this view.
2252     * <p>
2253     * Use with {@link #setAccessibilityLiveRegion(int)}.
2254     */
2255    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2256
2257    /**
2258     * Live region mode specifying that accessibility services should interrupt
2259     * ongoing speech to immediately announce changes to this view.
2260     * <p>
2261     * Use with {@link #setAccessibilityLiveRegion(int)}.
2262     */
2263    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2264
2265    /**
2266     * The default whether the view is important for accessibility.
2267     */
2268    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2269
2270    /**
2271     * Mask for obtaining the bits which specify a view's accessibility live
2272     * region mode.
2273     */
2274    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2275            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2276            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2277
2278    /**
2279     * Flag indicating whether a view has accessibility focus.
2280     */
2281    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2282
2283    /**
2284     * Flag whether the accessibility state of the subtree rooted at this view changed.
2285     */
2286    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2287
2288    /**
2289     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2290     * is used to check whether later changes to the view's transform should invalidate the
2291     * view to force the quickReject test to run again.
2292     */
2293    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2294
2295    /**
2296     * Flag indicating that start/end padding has been resolved into left/right padding
2297     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2298     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2299     * during measurement. In some special cases this is required such as when an adapter-based
2300     * view measures prospective children without attaching them to a window.
2301     */
2302    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2303
2304    /**
2305     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2306     */
2307    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2308
2309    /**
2310     * Indicates that the view is tracking some sort of transient state
2311     * that the app should not need to be aware of, but that the framework
2312     * should take special care to preserve.
2313     */
2314    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2315
2316    /**
2317     * Group of bits indicating that RTL properties resolution is done.
2318     */
2319    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2320            PFLAG2_TEXT_DIRECTION_RESOLVED |
2321            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2322            PFLAG2_PADDING_RESOLVED |
2323            PFLAG2_DRAWABLE_RESOLVED;
2324
2325    // There are a couple of flags left in mPrivateFlags2
2326
2327    /* End of masks for mPrivateFlags2 */
2328
2329    /**
2330     * Masks for mPrivateFlags3, as generated by dumpFlags():
2331     *
2332     * |-------|-------|-------|-------|
2333     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2334     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2335     *                               1   PFLAG3_IS_LAID_OUT
2336     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2337     *                             1     PFLAG3_CALLED_SUPER
2338     *                            1      PFLAG3_PROJECT_BACKGROUND
2339     * |-------|-------|-------|-------|
2340     */
2341
2342    /**
2343     * Flag indicating that view has a transform animation set on it. This is used to track whether
2344     * an animation is cleared between successive frames, in order to tell the associated
2345     * DisplayList to clear its animation matrix.
2346     */
2347    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2348
2349    /**
2350     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2351     * animation is cleared between successive frames, in order to tell the associated
2352     * DisplayList to restore its alpha value.
2353     */
2354    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2355
2356    /**
2357     * Flag indicating that the view has been through at least one layout since it
2358     * was last attached to a window.
2359     */
2360    static final int PFLAG3_IS_LAID_OUT = 0x4;
2361
2362    /**
2363     * Flag indicating that a call to measure() was skipped and should be done
2364     * instead when layout() is invoked.
2365     */
2366    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2367
2368    /**
2369     * Flag indicating that an overridden method correctly  called down to
2370     * the superclass implementation as required by the API spec.
2371     */
2372    static final int PFLAG3_CALLED_SUPER = 0x10;
2373
2374    /**
2375     * Flag indicating that the background of this view will be drawn into a
2376     * display list and projected onto the closest parent projection surface.
2377     */
2378    static final int PFLAG3_PROJECT_BACKGROUND = 0x20;
2379
2380    /**
2381     * Flag indicating that we're in the process of applying window insets.
2382     */
2383    static final int PFLAG3_APPLYING_INSETS = 0x40;
2384
2385    /**
2386     * Flag indicating that we're in the process of fitting system windows using the old method.
2387     */
2388    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2389
2390    /* End of masks for mPrivateFlags3 */
2391
2392    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2393
2394    /**
2395     * Always allow a user to over-scroll this view, provided it is a
2396     * view that can scroll.
2397     *
2398     * @see #getOverScrollMode()
2399     * @see #setOverScrollMode(int)
2400     */
2401    public static final int OVER_SCROLL_ALWAYS = 0;
2402
2403    /**
2404     * Allow a user to over-scroll this view only if the content is large
2405     * enough to meaningfully scroll, provided it is a view that can scroll.
2406     *
2407     * @see #getOverScrollMode()
2408     * @see #setOverScrollMode(int)
2409     */
2410    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2411
2412    /**
2413     * Never allow a user to over-scroll this view.
2414     *
2415     * @see #getOverScrollMode()
2416     * @see #setOverScrollMode(int)
2417     */
2418    public static final int OVER_SCROLL_NEVER = 2;
2419
2420    /**
2421     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2422     * requested the system UI (status bar) to be visible (the default).
2423     *
2424     * @see #setSystemUiVisibility(int)
2425     */
2426    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2427
2428    /**
2429     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2430     * system UI to enter an unobtrusive "low profile" mode.
2431     *
2432     * <p>This is for use in games, book readers, video players, or any other
2433     * "immersive" application where the usual system chrome is deemed too distracting.
2434     *
2435     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2436     *
2437     * @see #setSystemUiVisibility(int)
2438     */
2439    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2440
2441    /**
2442     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2443     * system navigation be temporarily hidden.
2444     *
2445     * <p>This is an even less obtrusive state than that called for by
2446     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2447     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2448     * those to disappear. This is useful (in conjunction with the
2449     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2450     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2451     * window flags) for displaying content using every last pixel on the display.
2452     *
2453     * <p>There is a limitation: because navigation controls are so important, the least user
2454     * interaction will cause them to reappear immediately.  When this happens, both
2455     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2456     * so that both elements reappear at the same time.
2457     *
2458     * @see #setSystemUiVisibility(int)
2459     */
2460    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2461
2462    /**
2463     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2464     * into the normal fullscreen mode so that its content can take over the screen
2465     * while still allowing the user to interact with the application.
2466     *
2467     * <p>This has the same visual effect as
2468     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2469     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2470     * meaning that non-critical screen decorations (such as the status bar) will be
2471     * hidden while the user is in the View's window, focusing the experience on
2472     * that content.  Unlike the window flag, if you are using ActionBar in
2473     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2474     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2475     * hide the action bar.
2476     *
2477     * <p>This approach to going fullscreen is best used over the window flag when
2478     * it is a transient state -- that is, the application does this at certain
2479     * points in its user interaction where it wants to allow the user to focus
2480     * on content, but not as a continuous state.  For situations where the application
2481     * would like to simply stay full screen the entire time (such as a game that
2482     * wants to take over the screen), the
2483     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2484     * is usually a better approach.  The state set here will be removed by the system
2485     * in various situations (such as the user moving to another application) like
2486     * the other system UI states.
2487     *
2488     * <p>When using this flag, the application should provide some easy facility
2489     * for the user to go out of it.  A common example would be in an e-book
2490     * reader, where tapping on the screen brings back whatever screen and UI
2491     * decorations that had been hidden while the user was immersed in reading
2492     * the book.
2493     *
2494     * @see #setSystemUiVisibility(int)
2495     */
2496    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2497
2498    /**
2499     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2500     * flags, we would like a stable view of the content insets given to
2501     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2502     * will always represent the worst case that the application can expect
2503     * as a continuous state.  In the stock Android UI this is the space for
2504     * the system bar, nav bar, and status bar, but not more transient elements
2505     * such as an input method.
2506     *
2507     * The stable layout your UI sees is based on the system UI modes you can
2508     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2509     * then you will get a stable layout for changes of the
2510     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2511     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2512     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2513     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2514     * with a stable layout.  (Note that you should avoid using
2515     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2516     *
2517     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2518     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2519     * then a hidden status bar will be considered a "stable" state for purposes
2520     * here.  This allows your UI to continually hide the status bar, while still
2521     * using the system UI flags to hide the action bar while still retaining
2522     * a stable layout.  Note that changing the window fullscreen flag will never
2523     * provide a stable layout for a clean transition.
2524     *
2525     * <p>If you are using ActionBar in
2526     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2527     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2528     * insets it adds to those given to the application.
2529     */
2530    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2531
2532    /**
2533     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2534     * to be layed out as if it has requested
2535     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2536     * allows it to avoid artifacts when switching in and out of that mode, at
2537     * the expense that some of its user interface may be covered by screen
2538     * decorations when they are shown.  You can perform layout of your inner
2539     * UI elements to account for the navigation system UI through the
2540     * {@link #fitSystemWindows(Rect)} method.
2541     */
2542    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
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_FULLSCREEN}, 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 non-fullscreen system UI through the
2552     * {@link #fitSystemWindows(Rect)} method.
2553     */
2554    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2555
2556    /**
2557     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2558     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2559     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2560     * user interaction.
2561     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2562     * has an effect when used in combination with that flag.</p>
2563     */
2564    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2565
2566    /**
2567     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2568     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2569     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2570     * experience while also hiding the system bars.  If this flag is not set,
2571     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2572     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2573     * if the user swipes from the top of the screen.
2574     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2575     * system gestures, such as swiping from the top of the screen.  These transient system bars
2576     * will overlay app’s content, may have some degree of transparency, and will automatically
2577     * hide after a short timeout.
2578     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2579     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2580     * with one or both of those flags.</p>
2581     */
2582    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2583
2584    /**
2585     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2586     */
2587    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2588
2589    /**
2590     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2591     */
2592    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2593
2594    /**
2595     * @hide
2596     *
2597     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2598     * out of the public fields to keep the undefined bits out of the developer's way.
2599     *
2600     * Flag to make the status bar not expandable.  Unless you also
2601     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2602     */
2603    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2604
2605    /**
2606     * @hide
2607     *
2608     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2609     * out of the public fields to keep the undefined bits out of the developer's way.
2610     *
2611     * Flag to hide notification icons and scrolling ticker text.
2612     */
2613    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2614
2615    /**
2616     * @hide
2617     *
2618     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2619     * out of the public fields to keep the undefined bits out of the developer's way.
2620     *
2621     * Flag to disable incoming notification alerts.  This will not block
2622     * icons, but it will block sound, vibrating and other visual or aural notifications.
2623     */
2624    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2625
2626    /**
2627     * @hide
2628     *
2629     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2630     * out of the public fields to keep the undefined bits out of the developer's way.
2631     *
2632     * Flag to hide only the scrolling ticker.  Note that
2633     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2634     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2635     */
2636    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
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 the center system info area.
2645     */
2646    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2647
2648    /**
2649     * @hide
2650     *
2651     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2652     * out of the public fields to keep the undefined bits out of the developer's way.
2653     *
2654     * Flag to hide only the home button.  Don't use this
2655     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2656     */
2657    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2658
2659    /**
2660     * @hide
2661     *
2662     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2663     * out of the public fields to keep the undefined bits out of the developer's way.
2664     *
2665     * Flag to hide only the back button. Don't use this
2666     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2667     */
2668    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2669
2670    /**
2671     * @hide
2672     *
2673     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2674     * out of the public fields to keep the undefined bits out of the developer's way.
2675     *
2676     * Flag to hide only the clock.  You might use this if your activity has
2677     * its own clock making the status bar's clock redundant.
2678     */
2679    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2680
2681    /**
2682     * @hide
2683     *
2684     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2685     * out of the public fields to keep the undefined bits out of the developer's way.
2686     *
2687     * Flag to hide only the recent apps button. Don't use this
2688     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2689     */
2690    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2691
2692    /**
2693     * @hide
2694     *
2695     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2696     * out of the public fields to keep the undefined bits out of the developer's way.
2697     *
2698     * Flag to disable the global search gesture. Don't use this
2699     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2700     */
2701    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2702
2703    /**
2704     * @hide
2705     *
2706     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2707     * out of the public fields to keep the undefined bits out of the developer's way.
2708     *
2709     * Flag to specify that the status bar is displayed in transient mode.
2710     */
2711    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2712
2713    /**
2714     * @hide
2715     *
2716     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2717     * out of the public fields to keep the undefined bits out of the developer's way.
2718     *
2719     * Flag to specify that the navigation bar is displayed in transient mode.
2720     */
2721    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2722
2723    /**
2724     * @hide
2725     *
2726     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2727     * out of the public fields to keep the undefined bits out of the developer's way.
2728     *
2729     * Flag to specify that the hidden status bar would like to be shown.
2730     */
2731    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2732
2733    /**
2734     * @hide
2735     *
2736     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2737     * out of the public fields to keep the undefined bits out of the developer's way.
2738     *
2739     * Flag to specify that the hidden navigation bar would like to be shown.
2740     */
2741    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2742
2743    /**
2744     * @hide
2745     *
2746     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2747     * out of the public fields to keep the undefined bits out of the developer's way.
2748     *
2749     * Flag to specify that the status bar is displayed in translucent mode.
2750     */
2751    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2752
2753    /**
2754     * @hide
2755     *
2756     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2757     * out of the public fields to keep the undefined bits out of the developer's way.
2758     *
2759     * Flag to specify that the navigation bar is displayed in translucent mode.
2760     */
2761    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2762
2763    /**
2764     * @hide
2765     */
2766    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2767
2768    /**
2769     * These are the system UI flags that can be cleared by events outside
2770     * of an application.  Currently this is just the ability to tap on the
2771     * screen while hiding the navigation bar to have it return.
2772     * @hide
2773     */
2774    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2775            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2776            | SYSTEM_UI_FLAG_FULLSCREEN;
2777
2778    /**
2779     * Flags that can impact the layout in relation to system UI.
2780     */
2781    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2782            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2783            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2784
2785    /** @hide */
2786    @IntDef(flag = true,
2787            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2788    @Retention(RetentionPolicy.SOURCE)
2789    public @interface FindViewFlags {}
2790
2791    /**
2792     * Find views that render the specified text.
2793     *
2794     * @see #findViewsWithText(ArrayList, CharSequence, int)
2795     */
2796    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2797
2798    /**
2799     * Find find views that contain the specified content description.
2800     *
2801     * @see #findViewsWithText(ArrayList, CharSequence, int)
2802     */
2803    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2804
2805    /**
2806     * Find views that contain {@link AccessibilityNodeProvider}. Such
2807     * a View is a root of virtual view hierarchy and may contain the searched
2808     * text. If this flag is set Views with providers are automatically
2809     * added and it is a responsibility of the client to call the APIs of
2810     * the provider to determine whether the virtual tree rooted at this View
2811     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2812     * representing the virtual views with this text.
2813     *
2814     * @see #findViewsWithText(ArrayList, CharSequence, int)
2815     *
2816     * @hide
2817     */
2818    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2819
2820    /**
2821     * The undefined cursor position.
2822     *
2823     * @hide
2824     */
2825    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2826
2827    /**
2828     * Indicates that the screen has changed state and is now off.
2829     *
2830     * @see #onScreenStateChanged(int)
2831     */
2832    public static final int SCREEN_STATE_OFF = 0x0;
2833
2834    /**
2835     * Indicates that the screen has changed state and is now on.
2836     *
2837     * @see #onScreenStateChanged(int)
2838     */
2839    public static final int SCREEN_STATE_ON = 0x1;
2840
2841    /**
2842     * Controls the over-scroll mode for this view.
2843     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2844     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2845     * and {@link #OVER_SCROLL_NEVER}.
2846     */
2847    private int mOverScrollMode;
2848
2849    /**
2850     * The parent this view is attached to.
2851     * {@hide}
2852     *
2853     * @see #getParent()
2854     */
2855    protected ViewParent mParent;
2856
2857    /**
2858     * {@hide}
2859     */
2860    AttachInfo mAttachInfo;
2861
2862    /**
2863     * {@hide}
2864     */
2865    @ViewDebug.ExportedProperty(flagMapping = {
2866        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2867                name = "FORCE_LAYOUT"),
2868        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2869                name = "LAYOUT_REQUIRED"),
2870        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2871            name = "DRAWING_CACHE_INVALID", outputIf = false),
2872        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2873        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2874        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2875        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2876    })
2877    int mPrivateFlags;
2878    int mPrivateFlags2;
2879    int mPrivateFlags3;
2880
2881    /**
2882     * This view's request for the visibility of the status bar.
2883     * @hide
2884     */
2885    @ViewDebug.ExportedProperty(flagMapping = {
2886        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2887                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2888                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2889        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2890                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2891                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2892        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2893                                equals = SYSTEM_UI_FLAG_VISIBLE,
2894                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2895    })
2896    int mSystemUiVisibility;
2897
2898    /**
2899     * Reference count for transient state.
2900     * @see #setHasTransientState(boolean)
2901     */
2902    int mTransientStateCount = 0;
2903
2904    /**
2905     * Count of how many windows this view has been attached to.
2906     */
2907    int mWindowAttachCount;
2908
2909    /**
2910     * The layout parameters associated with this view and used by the parent
2911     * {@link android.view.ViewGroup} to determine how this view should be
2912     * laid out.
2913     * {@hide}
2914     */
2915    protected ViewGroup.LayoutParams mLayoutParams;
2916
2917    /**
2918     * The view flags hold various views states.
2919     * {@hide}
2920     */
2921    @ViewDebug.ExportedProperty
2922    int mViewFlags;
2923
2924    static class TransformationInfo {
2925        /**
2926         * The transform matrix for the View. This transform is calculated internally
2927         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2928         * is used by default. Do *not* use this variable directly; instead call
2929         * getMatrix(), which will automatically recalculate the matrix if necessary
2930         * to get the correct matrix based on the latest rotation and scale properties.
2931         */
2932        private final Matrix mMatrix = new Matrix();
2933
2934        /**
2935         * The transform matrix for the View. This transform is calculated internally
2936         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2937         * is used by default. Do *not* use this variable directly; instead call
2938         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2939         * to get the correct matrix based on the latest rotation and scale properties.
2940         */
2941        private Matrix mInverseMatrix;
2942
2943        /**
2944         * An internal variable that tracks whether we need to recalculate the
2945         * transform matrix, based on whether the rotation or scaleX/Y properties
2946         * have changed since the matrix was last calculated.
2947         */
2948        boolean mMatrixDirty = false;
2949
2950        /**
2951         * An internal variable that tracks whether we need to recalculate the
2952         * transform matrix, based on whether the rotation or scaleX/Y properties
2953         * have changed since the matrix was last calculated.
2954         */
2955        private boolean mInverseMatrixDirty = true;
2956
2957        /**
2958         * A variable that tracks whether we need to recalculate the
2959         * transform matrix, based on whether the rotation or scaleX/Y properties
2960         * have changed since the matrix was last calculated. This variable
2961         * is only valid after a call to updateMatrix() or to a function that
2962         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2963         */
2964        private boolean mMatrixIsIdentity = true;
2965
2966        /**
2967         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2968         */
2969        private Camera mCamera = null;
2970
2971        /**
2972         * This matrix is used when computing the matrix for 3D rotations.
2973         */
2974        private Matrix matrix3D = null;
2975
2976        /**
2977         * These prev values are used to recalculate a centered pivot point when necessary. The
2978         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2979         * set), so thes values are only used then as well.
2980         */
2981        private int mPrevWidth = -1;
2982        private int mPrevHeight = -1;
2983
2984        /**
2985         * The degrees rotation around the vertical axis through the pivot point.
2986         */
2987        @ViewDebug.ExportedProperty
2988        float mRotationY = 0f;
2989
2990        /**
2991         * The degrees rotation around the horizontal axis through the pivot point.
2992         */
2993        @ViewDebug.ExportedProperty
2994        float mRotationX = 0f;
2995
2996        /**
2997         * The degrees rotation around the pivot point.
2998         */
2999        @ViewDebug.ExportedProperty
3000        float mRotation = 0f;
3001
3002        /**
3003         * The amount of translation of the object away from its left property (post-layout).
3004         */
3005        @ViewDebug.ExportedProperty
3006        float mTranslationX = 0f;
3007
3008        /**
3009         * The amount of translation of the object away from its top property (post-layout).
3010         */
3011        @ViewDebug.ExportedProperty
3012        float mTranslationY = 0f;
3013
3014        @ViewDebug.ExportedProperty
3015        float mTranslationZ = 0f;
3016
3017        /**
3018         * The amount of scale in the x direction around the pivot point. A
3019         * value of 1 means no scaling is applied.
3020         */
3021        @ViewDebug.ExportedProperty
3022        float mScaleX = 1f;
3023
3024        /**
3025         * The amount of scale in the y direction around the pivot point. A
3026         * value of 1 means no scaling is applied.
3027         */
3028        @ViewDebug.ExportedProperty
3029        float mScaleY = 1f;
3030
3031        /**
3032         * The x location of the point around which the view is rotated and scaled.
3033         */
3034        @ViewDebug.ExportedProperty
3035        float mPivotX = 0f;
3036
3037        /**
3038         * The y location of the point around which the view is rotated and scaled.
3039         */
3040        @ViewDebug.ExportedProperty
3041        float mPivotY = 0f;
3042
3043        /**
3044         * The opacity of the View. This is a value from 0 to 1, where 0 means
3045         * completely transparent and 1 means completely opaque.
3046         */
3047        @ViewDebug.ExportedProperty
3048        float mAlpha = 1f;
3049
3050        /**
3051         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3052         * property only used by transitions, which is composited with the other alpha
3053         * values to calculate the final visual alpha value.
3054         */
3055        float mTransitionAlpha = 1f;
3056    }
3057
3058    TransformationInfo mTransformationInfo;
3059
3060    /**
3061     * Current clip bounds. to which all drawing of this view are constrained.
3062     */
3063    private Rect mClipBounds = null;
3064
3065    private boolean mLastIsOpaque;
3066
3067    /**
3068     * Convenience value to check for float values that are close enough to zero to be considered
3069     * zero.
3070     */
3071    private static final float NONZERO_EPSILON = .001f;
3072
3073    /**
3074     * The distance in pixels from the left edge of this view's parent
3075     * to the left edge of this view.
3076     * {@hide}
3077     */
3078    @ViewDebug.ExportedProperty(category = "layout")
3079    protected int mLeft;
3080    /**
3081     * The distance in pixels from the left edge of this view's parent
3082     * to the right edge of this view.
3083     * {@hide}
3084     */
3085    @ViewDebug.ExportedProperty(category = "layout")
3086    protected int mRight;
3087    /**
3088     * The distance in pixels from the top edge of this view's parent
3089     * to the top edge of this view.
3090     * {@hide}
3091     */
3092    @ViewDebug.ExportedProperty(category = "layout")
3093    protected int mTop;
3094    /**
3095     * The distance in pixels from the top edge of this view's parent
3096     * to the bottom edge of this view.
3097     * {@hide}
3098     */
3099    @ViewDebug.ExportedProperty(category = "layout")
3100    protected int mBottom;
3101
3102    /**
3103     * The offset, in pixels, by which the content of this view is scrolled
3104     * horizontally.
3105     * {@hide}
3106     */
3107    @ViewDebug.ExportedProperty(category = "scrolling")
3108    protected int mScrollX;
3109    /**
3110     * The offset, in pixels, by which the content of this view is scrolled
3111     * vertically.
3112     * {@hide}
3113     */
3114    @ViewDebug.ExportedProperty(category = "scrolling")
3115    protected int mScrollY;
3116
3117    /**
3118     * The left padding in pixels, that is the distance in pixels between the
3119     * left edge of this view and the left edge of its content.
3120     * {@hide}
3121     */
3122    @ViewDebug.ExportedProperty(category = "padding")
3123    protected int mPaddingLeft = 0;
3124    /**
3125     * The right padding in pixels, that is the distance in pixels between the
3126     * right edge of this view and the right edge of its content.
3127     * {@hide}
3128     */
3129    @ViewDebug.ExportedProperty(category = "padding")
3130    protected int mPaddingRight = 0;
3131    /**
3132     * The top padding in pixels, that is the distance in pixels between the
3133     * top edge of this view and the top edge of its content.
3134     * {@hide}
3135     */
3136    @ViewDebug.ExportedProperty(category = "padding")
3137    protected int mPaddingTop;
3138    /**
3139     * The bottom padding in pixels, that is the distance in pixels between the
3140     * bottom edge of this view and the bottom edge of its content.
3141     * {@hide}
3142     */
3143    @ViewDebug.ExportedProperty(category = "padding")
3144    protected int mPaddingBottom;
3145
3146    /**
3147     * The layout insets in pixels, that is the distance in pixels between the
3148     * visible edges of this view its bounds.
3149     */
3150    private Insets mLayoutInsets;
3151
3152    /**
3153     * Briefly describes the view and is primarily used for accessibility support.
3154     */
3155    private CharSequence mContentDescription;
3156
3157    /**
3158     * Specifies the id of a view for which this view serves as a label for
3159     * accessibility purposes.
3160     */
3161    private int mLabelForId = View.NO_ID;
3162
3163    /**
3164     * Predicate for matching labeled view id with its label for
3165     * accessibility purposes.
3166     */
3167    private MatchLabelForPredicate mMatchLabelForPredicate;
3168
3169    /**
3170     * Predicate for matching a view by its id.
3171     */
3172    private MatchIdPredicate mMatchIdPredicate;
3173
3174    /**
3175     * Cache the paddingRight set by the user to append to the scrollbar's size.
3176     *
3177     * @hide
3178     */
3179    @ViewDebug.ExportedProperty(category = "padding")
3180    protected int mUserPaddingRight;
3181
3182    /**
3183     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3184     *
3185     * @hide
3186     */
3187    @ViewDebug.ExportedProperty(category = "padding")
3188    protected int mUserPaddingBottom;
3189
3190    /**
3191     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3192     *
3193     * @hide
3194     */
3195    @ViewDebug.ExportedProperty(category = "padding")
3196    protected int mUserPaddingLeft;
3197
3198    /**
3199     * Cache the paddingStart set by the user to append to the scrollbar's size.
3200     *
3201     */
3202    @ViewDebug.ExportedProperty(category = "padding")
3203    int mUserPaddingStart;
3204
3205    /**
3206     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3207     *
3208     */
3209    @ViewDebug.ExportedProperty(category = "padding")
3210    int mUserPaddingEnd;
3211
3212    /**
3213     * Cache initial left padding.
3214     *
3215     * @hide
3216     */
3217    int mUserPaddingLeftInitial;
3218
3219    /**
3220     * Cache initial right padding.
3221     *
3222     * @hide
3223     */
3224    int mUserPaddingRightInitial;
3225
3226    /**
3227     * Default undefined padding
3228     */
3229    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3230
3231    /**
3232     * Cache if a left padding has been defined
3233     */
3234    private boolean mLeftPaddingDefined = false;
3235
3236    /**
3237     * Cache if a right padding has been defined
3238     */
3239    private boolean mRightPaddingDefined = false;
3240
3241    /**
3242     * @hide
3243     */
3244    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3245    /**
3246     * @hide
3247     */
3248    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3249
3250    private LongSparseLongArray mMeasureCache;
3251
3252    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3253    private Drawable mBackground;
3254
3255    /**
3256     * Display list used for backgrounds.
3257     * <p>
3258     * When non-null and valid, this is expected to contain an up-to-date copy
3259     * of the background drawable. It is cleared on temporary detach and reset
3260     * on cleanup.
3261     */
3262    private DisplayList mBackgroundDisplayList;
3263
3264    private int mBackgroundResource;
3265    private boolean mBackgroundSizeChanged;
3266
3267    static class ListenerInfo {
3268        /**
3269         * Listener used to dispatch focus change events.
3270         * This field should be made private, so it is hidden from the SDK.
3271         * {@hide}
3272         */
3273        protected OnFocusChangeListener mOnFocusChangeListener;
3274
3275        /**
3276         * Listeners for layout change events.
3277         */
3278        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3279
3280        /**
3281         * Listeners for attach events.
3282         */
3283        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3284
3285        /**
3286         * Listener used to dispatch click events.
3287         * This field should be made private, so it is hidden from the SDK.
3288         * {@hide}
3289         */
3290        public OnClickListener mOnClickListener;
3291
3292        /**
3293         * Listener used to dispatch long click events.
3294         * This field should be made private, so it is hidden from the SDK.
3295         * {@hide}
3296         */
3297        protected OnLongClickListener mOnLongClickListener;
3298
3299        /**
3300         * Listener used to build the context menu.
3301         * This field should be made private, so it is hidden from the SDK.
3302         * {@hide}
3303         */
3304        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3305
3306        private OnKeyListener mOnKeyListener;
3307
3308        private OnTouchListener mOnTouchListener;
3309
3310        private OnHoverListener mOnHoverListener;
3311
3312        private OnGenericMotionListener mOnGenericMotionListener;
3313
3314        private OnDragListener mOnDragListener;
3315
3316        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3317
3318        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3319    }
3320
3321    ListenerInfo mListenerInfo;
3322
3323    /**
3324     * The application environment this view lives in.
3325     * This field should be made private, so it is hidden from the SDK.
3326     * {@hide}
3327     */
3328    protected Context mContext;
3329
3330    private final Resources mResources;
3331
3332    private ScrollabilityCache mScrollCache;
3333
3334    private int[] mDrawableState = null;
3335
3336    /**
3337     * Stores the outline of the view, passed down to the DisplayList level for shadow shape.
3338     */
3339    private Path mOutline;
3340
3341    /**
3342     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3343     * the user may specify which view to go to next.
3344     */
3345    private int mNextFocusLeftId = View.NO_ID;
3346
3347    /**
3348     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3349     * the user may specify which view to go to next.
3350     */
3351    private int mNextFocusRightId = View.NO_ID;
3352
3353    /**
3354     * When this view has focus and the next focus is {@link #FOCUS_UP},
3355     * the user may specify which view to go to next.
3356     */
3357    private int mNextFocusUpId = View.NO_ID;
3358
3359    /**
3360     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3361     * the user may specify which view to go to next.
3362     */
3363    private int mNextFocusDownId = View.NO_ID;
3364
3365    /**
3366     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3367     * the user may specify which view to go to next.
3368     */
3369    int mNextFocusForwardId = View.NO_ID;
3370
3371    private CheckForLongPress mPendingCheckForLongPress;
3372    private CheckForTap mPendingCheckForTap = null;
3373    private PerformClick mPerformClick;
3374    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3375
3376    private UnsetPressedState mUnsetPressedState;
3377
3378    /**
3379     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3380     * up event while a long press is invoked as soon as the long press duration is reached, so
3381     * a long press could be performed before the tap is checked, in which case the tap's action
3382     * should not be invoked.
3383     */
3384    private boolean mHasPerformedLongPress;
3385
3386    /**
3387     * The minimum height of the view. We'll try our best to have the height
3388     * of this view to at least this amount.
3389     */
3390    @ViewDebug.ExportedProperty(category = "measurement")
3391    private int mMinHeight;
3392
3393    /**
3394     * The minimum width of the view. We'll try our best to have the width
3395     * of this view to at least this amount.
3396     */
3397    @ViewDebug.ExportedProperty(category = "measurement")
3398    private int mMinWidth;
3399
3400    /**
3401     * The delegate to handle touch events that are physically in this view
3402     * but should be handled by another view.
3403     */
3404    private TouchDelegate mTouchDelegate = null;
3405
3406    /**
3407     * Solid color to use as a background when creating the drawing cache. Enables
3408     * the cache to use 16 bit bitmaps instead of 32 bit.
3409     */
3410    private int mDrawingCacheBackgroundColor = 0;
3411
3412    /**
3413     * Special tree observer used when mAttachInfo is null.
3414     */
3415    private ViewTreeObserver mFloatingTreeObserver;
3416
3417    /**
3418     * Cache the touch slop from the context that created the view.
3419     */
3420    private int mTouchSlop;
3421
3422    /**
3423     * Object that handles automatic animation of view properties.
3424     */
3425    private ViewPropertyAnimator mAnimator = null;
3426
3427    /**
3428     * Flag indicating that a drag can cross window boundaries.  When
3429     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3430     * with this flag set, all visible applications will be able to participate
3431     * in the drag operation and receive the dragged content.
3432     *
3433     * @hide
3434     */
3435    public static final int DRAG_FLAG_GLOBAL = 1;
3436
3437    /**
3438     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3439     */
3440    private float mVerticalScrollFactor;
3441
3442    /**
3443     * Position of the vertical scroll bar.
3444     */
3445    private int mVerticalScrollbarPosition;
3446
3447    /**
3448     * Position the scroll bar at the default position as determined by the system.
3449     */
3450    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3451
3452    /**
3453     * Position the scroll bar along the left edge.
3454     */
3455    public static final int SCROLLBAR_POSITION_LEFT = 1;
3456
3457    /**
3458     * Position the scroll bar along the right edge.
3459     */
3460    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3461
3462    /**
3463     * Indicates that the view does not have a layer.
3464     *
3465     * @see #getLayerType()
3466     * @see #setLayerType(int, android.graphics.Paint)
3467     * @see #LAYER_TYPE_SOFTWARE
3468     * @see #LAYER_TYPE_HARDWARE
3469     */
3470    public static final int LAYER_TYPE_NONE = 0;
3471
3472    /**
3473     * <p>Indicates that the view has a software layer. A software layer is backed
3474     * by a bitmap and causes the view to be rendered using Android's software
3475     * rendering pipeline, even if hardware acceleration is enabled.</p>
3476     *
3477     * <p>Software layers have various usages:</p>
3478     * <p>When the application is not using hardware acceleration, a software layer
3479     * is useful to apply a specific color filter and/or blending mode and/or
3480     * translucency to a view and all its children.</p>
3481     * <p>When the application is using hardware acceleration, a software layer
3482     * is useful to render drawing primitives not supported by the hardware
3483     * accelerated pipeline. It can also be used to cache a complex view tree
3484     * into a texture and reduce the complexity of drawing operations. For instance,
3485     * when animating a complex view tree with a translation, a software layer can
3486     * be used to render the view tree only once.</p>
3487     * <p>Software layers should be avoided when the affected view tree updates
3488     * often. Every update will require to re-render the software layer, which can
3489     * potentially be slow (particularly when hardware acceleration is turned on
3490     * since the layer will have to be uploaded into a hardware texture after every
3491     * update.)</p>
3492     *
3493     * @see #getLayerType()
3494     * @see #setLayerType(int, android.graphics.Paint)
3495     * @see #LAYER_TYPE_NONE
3496     * @see #LAYER_TYPE_HARDWARE
3497     */
3498    public static final int LAYER_TYPE_SOFTWARE = 1;
3499
3500    /**
3501     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3502     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3503     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3504     * rendering pipeline, but only if hardware acceleration is turned on for the
3505     * view hierarchy. When hardware acceleration is turned off, hardware layers
3506     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3507     *
3508     * <p>A hardware layer is useful to apply a specific color filter and/or
3509     * blending mode and/or translucency to a view and all its children.</p>
3510     * <p>A hardware layer can be used to cache a complex view tree into a
3511     * texture and reduce the complexity of drawing operations. For instance,
3512     * when animating a complex view tree with a translation, a hardware layer can
3513     * be used to render the view tree only once.</p>
3514     * <p>A hardware layer can also be used to increase the rendering quality when
3515     * rotation transformations are applied on a view. It can also be used to
3516     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3517     *
3518     * @see #getLayerType()
3519     * @see #setLayerType(int, android.graphics.Paint)
3520     * @see #LAYER_TYPE_NONE
3521     * @see #LAYER_TYPE_SOFTWARE
3522     */
3523    public static final int LAYER_TYPE_HARDWARE = 2;
3524
3525    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3526            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3527            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3528            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3529    })
3530    int mLayerType = LAYER_TYPE_NONE;
3531    Paint mLayerPaint;
3532    Rect mLocalDirtyRect;
3533    private HardwareLayer mHardwareLayer;
3534
3535    /**
3536     * Set to true when drawing cache is enabled and cannot be created.
3537     *
3538     * @hide
3539     */
3540    public boolean mCachingFailed;
3541    private Bitmap mDrawingCache;
3542    private Bitmap mUnscaledDrawingCache;
3543
3544    /**
3545     * Display list used for the View content.
3546     * <p>
3547     * When non-null and valid, this is expected to contain an up-to-date copy
3548     * of the View content. It is cleared on temporary detach and reset on
3549     * cleanup.
3550     */
3551    DisplayList mDisplayList;
3552
3553    /**
3554     * Set to true when the view is sending hover accessibility events because it
3555     * is the innermost hovered view.
3556     */
3557    private boolean mSendingHoverAccessibilityEvents;
3558
3559    /**
3560     * Delegate for injecting accessibility functionality.
3561     */
3562    AccessibilityDelegate mAccessibilityDelegate;
3563
3564    /**
3565     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3566     * and add/remove objects to/from the overlay directly through the Overlay methods.
3567     */
3568    ViewOverlay mOverlay;
3569
3570    /**
3571     * Consistency verifier for debugging purposes.
3572     * @hide
3573     */
3574    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3575            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3576                    new InputEventConsistencyVerifier(this, 0) : null;
3577
3578    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3579
3580    /**
3581     * Simple constructor to use when creating a view from code.
3582     *
3583     * @param context The Context the view is running in, through which it can
3584     *        access the current theme, resources, etc.
3585     */
3586    public View(Context context) {
3587        mContext = context;
3588        mResources = context != null ? context.getResources() : null;
3589        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3590        // Set some flags defaults
3591        mPrivateFlags2 =
3592                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3593                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3594                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3595                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3596                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3597                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3598        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3599        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3600        mUserPaddingStart = UNDEFINED_PADDING;
3601        mUserPaddingEnd = UNDEFINED_PADDING;
3602
3603        if (!sCompatibilityDone && context != null) {
3604            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3605
3606            // Older apps may need this compatibility hack for measurement.
3607            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3608
3609            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3610            // of whether a layout was requested on that View.
3611            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3612
3613            sCompatibilityDone = true;
3614        }
3615    }
3616
3617    /**
3618     * Constructor that is called when inflating a view from XML. This is called
3619     * when a view is being constructed from an XML file, supplying attributes
3620     * that were specified in the XML file. This version uses a default style of
3621     * 0, so the only attribute values applied are those in the Context's Theme
3622     * and the given AttributeSet.
3623     *
3624     * <p>
3625     * The method onFinishInflate() will be called after all children have been
3626     * added.
3627     *
3628     * @param context The Context the view is running in, through which it can
3629     *        access the current theme, resources, etc.
3630     * @param attrs The attributes of the XML tag that is inflating the view.
3631     * @see #View(Context, AttributeSet, int)
3632     */
3633    public View(Context context, AttributeSet attrs) {
3634        this(context, attrs, 0);
3635    }
3636
3637    /**
3638     * Perform inflation from XML and apply a class-specific base style from a
3639     * theme attribute. This constructor of View allows subclasses to use their
3640     * own base style when they are inflating. For example, a Button class's
3641     * constructor would call this version of the super class constructor and
3642     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3643     * allows the theme's button style to modify all of the base view attributes
3644     * (in particular its background) as well as the Button class's attributes.
3645     *
3646     * @param context The Context the view is running in, through which it can
3647     *        access the current theme, resources, etc.
3648     * @param attrs The attributes of the XML tag that is inflating the view.
3649     * @param defStyleAttr An attribute in the current theme that contains a
3650     *        reference to a style resource that supplies default values for
3651     *        the view. Can be 0 to not look for defaults.
3652     * @see #View(Context, AttributeSet)
3653     */
3654    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3655        this(context, attrs, defStyleAttr, 0);
3656    }
3657
3658    /**
3659     * Perform inflation from XML and apply a class-specific base style from a
3660     * theme attribute or style resource. This constructor of View allows
3661     * subclasses to use their own base style when they are inflating.
3662     * <p>
3663     * When determining the final value of a particular attribute, there are
3664     * four inputs that come into play:
3665     * <ol>
3666     * <li>Any attribute values in the given AttributeSet.
3667     * <li>The style resource specified in the AttributeSet (named "style").
3668     * <li>The default style specified by <var>defStyleAttr</var>.
3669     * <li>The default style specified by <var>defStyleRes</var>.
3670     * <li>The base values in this theme.
3671     * </ol>
3672     * <p>
3673     * Each of these inputs is considered in-order, with the first listed taking
3674     * precedence over the following ones. In other words, if in the
3675     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3676     * , then the button's text will <em>always</em> be black, regardless of
3677     * what is specified in any of the styles.
3678     *
3679     * @param context The Context the view is running in, through which it can
3680     *        access the current theme, resources, etc.
3681     * @param attrs The attributes of the XML tag that is inflating the view.
3682     * @param defStyleAttr An attribute in the current theme that contains a
3683     *        reference to a style resource that supplies default values for
3684     *        the view. Can be 0 to not look for defaults.
3685     * @param defStyleRes A resource identifier of a style resource that
3686     *        supplies default values for the view, used only if
3687     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3688     *        to not look for defaults.
3689     * @see #View(Context, AttributeSet, int)
3690     */
3691    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3692        this(context);
3693
3694        final TypedArray a = context.obtainStyledAttributes(
3695                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3696
3697        Drawable background = null;
3698
3699        int leftPadding = -1;
3700        int topPadding = -1;
3701        int rightPadding = -1;
3702        int bottomPadding = -1;
3703        int startPadding = UNDEFINED_PADDING;
3704        int endPadding = UNDEFINED_PADDING;
3705
3706        int padding = -1;
3707
3708        int viewFlagValues = 0;
3709        int viewFlagMasks = 0;
3710
3711        boolean setScrollContainer = false;
3712
3713        int x = 0;
3714        int y = 0;
3715
3716        float tx = 0;
3717        float ty = 0;
3718        float tz = 0;
3719        float rotation = 0;
3720        float rotationX = 0;
3721        float rotationY = 0;
3722        float sx = 1f;
3723        float sy = 1f;
3724        boolean transformSet = false;
3725
3726        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3727        int overScrollMode = mOverScrollMode;
3728        boolean initializeScrollbars = false;
3729
3730        boolean startPaddingDefined = false;
3731        boolean endPaddingDefined = false;
3732        boolean leftPaddingDefined = false;
3733        boolean rightPaddingDefined = false;
3734
3735        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3736
3737        final int N = a.getIndexCount();
3738        for (int i = 0; i < N; i++) {
3739            int attr = a.getIndex(i);
3740            switch (attr) {
3741                case com.android.internal.R.styleable.View_background:
3742                    background = a.getDrawable(attr);
3743                    break;
3744                case com.android.internal.R.styleable.View_padding:
3745                    padding = a.getDimensionPixelSize(attr, -1);
3746                    mUserPaddingLeftInitial = padding;
3747                    mUserPaddingRightInitial = padding;
3748                    leftPaddingDefined = true;
3749                    rightPaddingDefined = true;
3750                    break;
3751                 case com.android.internal.R.styleable.View_paddingLeft:
3752                    leftPadding = a.getDimensionPixelSize(attr, -1);
3753                    mUserPaddingLeftInitial = leftPadding;
3754                    leftPaddingDefined = true;
3755                    break;
3756                case com.android.internal.R.styleable.View_paddingTop:
3757                    topPadding = a.getDimensionPixelSize(attr, -1);
3758                    break;
3759                case com.android.internal.R.styleable.View_paddingRight:
3760                    rightPadding = a.getDimensionPixelSize(attr, -1);
3761                    mUserPaddingRightInitial = rightPadding;
3762                    rightPaddingDefined = true;
3763                    break;
3764                case com.android.internal.R.styleable.View_paddingBottom:
3765                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3766                    break;
3767                case com.android.internal.R.styleable.View_paddingStart:
3768                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3769                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3770                    break;
3771                case com.android.internal.R.styleable.View_paddingEnd:
3772                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3773                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3774                    break;
3775                case com.android.internal.R.styleable.View_scrollX:
3776                    x = a.getDimensionPixelOffset(attr, 0);
3777                    break;
3778                case com.android.internal.R.styleable.View_scrollY:
3779                    y = a.getDimensionPixelOffset(attr, 0);
3780                    break;
3781                case com.android.internal.R.styleable.View_alpha:
3782                    setAlpha(a.getFloat(attr, 1f));
3783                    break;
3784                case com.android.internal.R.styleable.View_transformPivotX:
3785                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3786                    break;
3787                case com.android.internal.R.styleable.View_transformPivotY:
3788                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3789                    break;
3790                case com.android.internal.R.styleable.View_translationX:
3791                    tx = a.getDimensionPixelOffset(attr, 0);
3792                    transformSet = true;
3793                    break;
3794                case com.android.internal.R.styleable.View_translationY:
3795                    ty = a.getDimensionPixelOffset(attr, 0);
3796                    transformSet = true;
3797                    break;
3798                case com.android.internal.R.styleable.View_translationZ:
3799                    tz = a.getDimensionPixelOffset(attr, 0);
3800                    transformSet = true;
3801                    break;
3802                case com.android.internal.R.styleable.View_rotation:
3803                    rotation = a.getFloat(attr, 0);
3804                    transformSet = true;
3805                    break;
3806                case com.android.internal.R.styleable.View_rotationX:
3807                    rotationX = a.getFloat(attr, 0);
3808                    transformSet = true;
3809                    break;
3810                case com.android.internal.R.styleable.View_rotationY:
3811                    rotationY = a.getFloat(attr, 0);
3812                    transformSet = true;
3813                    break;
3814                case com.android.internal.R.styleable.View_scaleX:
3815                    sx = a.getFloat(attr, 1f);
3816                    transformSet = true;
3817                    break;
3818                case com.android.internal.R.styleable.View_scaleY:
3819                    sy = a.getFloat(attr, 1f);
3820                    transformSet = true;
3821                    break;
3822                case com.android.internal.R.styleable.View_id:
3823                    mID = a.getResourceId(attr, NO_ID);
3824                    break;
3825                case com.android.internal.R.styleable.View_tag:
3826                    mTag = a.getText(attr);
3827                    break;
3828                case com.android.internal.R.styleable.View_fitsSystemWindows:
3829                    if (a.getBoolean(attr, false)) {
3830                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3831                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3832                    }
3833                    break;
3834                case com.android.internal.R.styleable.View_focusable:
3835                    if (a.getBoolean(attr, false)) {
3836                        viewFlagValues |= FOCUSABLE;
3837                        viewFlagMasks |= FOCUSABLE_MASK;
3838                    }
3839                    break;
3840                case com.android.internal.R.styleable.View_focusableInTouchMode:
3841                    if (a.getBoolean(attr, false)) {
3842                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3843                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3844                    }
3845                    break;
3846                case com.android.internal.R.styleable.View_clickable:
3847                    if (a.getBoolean(attr, false)) {
3848                        viewFlagValues |= CLICKABLE;
3849                        viewFlagMasks |= CLICKABLE;
3850                    }
3851                    break;
3852                case com.android.internal.R.styleable.View_longClickable:
3853                    if (a.getBoolean(attr, false)) {
3854                        viewFlagValues |= LONG_CLICKABLE;
3855                        viewFlagMasks |= LONG_CLICKABLE;
3856                    }
3857                    break;
3858                case com.android.internal.R.styleable.View_saveEnabled:
3859                    if (!a.getBoolean(attr, true)) {
3860                        viewFlagValues |= SAVE_DISABLED;
3861                        viewFlagMasks |= SAVE_DISABLED_MASK;
3862                    }
3863                    break;
3864                case com.android.internal.R.styleable.View_duplicateParentState:
3865                    if (a.getBoolean(attr, false)) {
3866                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3867                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3868                    }
3869                    break;
3870                case com.android.internal.R.styleable.View_visibility:
3871                    final int visibility = a.getInt(attr, 0);
3872                    if (visibility != 0) {
3873                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3874                        viewFlagMasks |= VISIBILITY_MASK;
3875                    }
3876                    break;
3877                case com.android.internal.R.styleable.View_layoutDirection:
3878                    // Clear any layout direction flags (included resolved bits) already set
3879                    mPrivateFlags2 &=
3880                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3881                    // Set the layout direction flags depending on the value of the attribute
3882                    final int layoutDirection = a.getInt(attr, -1);
3883                    final int value = (layoutDirection != -1) ?
3884                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3885                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3886                    break;
3887                case com.android.internal.R.styleable.View_drawingCacheQuality:
3888                    final int cacheQuality = a.getInt(attr, 0);
3889                    if (cacheQuality != 0) {
3890                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3891                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3892                    }
3893                    break;
3894                case com.android.internal.R.styleable.View_contentDescription:
3895                    setContentDescription(a.getString(attr));
3896                    break;
3897                case com.android.internal.R.styleable.View_labelFor:
3898                    setLabelFor(a.getResourceId(attr, NO_ID));
3899                    break;
3900                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3901                    if (!a.getBoolean(attr, true)) {
3902                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3903                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3904                    }
3905                    break;
3906                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3907                    if (!a.getBoolean(attr, true)) {
3908                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3909                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3910                    }
3911                    break;
3912                case R.styleable.View_scrollbars:
3913                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3914                    if (scrollbars != SCROLLBARS_NONE) {
3915                        viewFlagValues |= scrollbars;
3916                        viewFlagMasks |= SCROLLBARS_MASK;
3917                        initializeScrollbars = true;
3918                    }
3919                    break;
3920                //noinspection deprecation
3921                case R.styleable.View_fadingEdge:
3922                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3923                        // Ignore the attribute starting with ICS
3924                        break;
3925                    }
3926                    // With builds < ICS, fall through and apply fading edges
3927                case R.styleable.View_requiresFadingEdge:
3928                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3929                    if (fadingEdge != FADING_EDGE_NONE) {
3930                        viewFlagValues |= fadingEdge;
3931                        viewFlagMasks |= FADING_EDGE_MASK;
3932                        initializeFadingEdge(a);
3933                    }
3934                    break;
3935                case R.styleable.View_scrollbarStyle:
3936                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3937                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3938                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3939                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3940                    }
3941                    break;
3942                case R.styleable.View_isScrollContainer:
3943                    setScrollContainer = true;
3944                    if (a.getBoolean(attr, false)) {
3945                        setScrollContainer(true);
3946                    }
3947                    break;
3948                case com.android.internal.R.styleable.View_keepScreenOn:
3949                    if (a.getBoolean(attr, false)) {
3950                        viewFlagValues |= KEEP_SCREEN_ON;
3951                        viewFlagMasks |= KEEP_SCREEN_ON;
3952                    }
3953                    break;
3954                case R.styleable.View_filterTouchesWhenObscured:
3955                    if (a.getBoolean(attr, false)) {
3956                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3957                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3958                    }
3959                    break;
3960                case R.styleable.View_nextFocusLeft:
3961                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3962                    break;
3963                case R.styleable.View_nextFocusRight:
3964                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3965                    break;
3966                case R.styleable.View_nextFocusUp:
3967                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3968                    break;
3969                case R.styleable.View_nextFocusDown:
3970                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3971                    break;
3972                case R.styleable.View_nextFocusForward:
3973                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3974                    break;
3975                case R.styleable.View_minWidth:
3976                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3977                    break;
3978                case R.styleable.View_minHeight:
3979                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3980                    break;
3981                case R.styleable.View_onClick:
3982                    if (context.isRestricted()) {
3983                        throw new IllegalStateException("The android:onClick attribute cannot "
3984                                + "be used within a restricted context");
3985                    }
3986
3987                    final String handlerName = a.getString(attr);
3988                    if (handlerName != null) {
3989                        setOnClickListener(new OnClickListener() {
3990                            private Method mHandler;
3991
3992                            public void onClick(View v) {
3993                                if (mHandler == null) {
3994                                    try {
3995                                        mHandler = getContext().getClass().getMethod(handlerName,
3996                                                View.class);
3997                                    } catch (NoSuchMethodException e) {
3998                                        int id = getId();
3999                                        String idText = id == NO_ID ? "" : " with id '"
4000                                                + getContext().getResources().getResourceEntryName(
4001                                                    id) + "'";
4002                                        throw new IllegalStateException("Could not find a method " +
4003                                                handlerName + "(View) in the activity "
4004                                                + getContext().getClass() + " for onClick handler"
4005                                                + " on view " + View.this.getClass() + idText, e);
4006                                    }
4007                                }
4008
4009                                try {
4010                                    mHandler.invoke(getContext(), View.this);
4011                                } catch (IllegalAccessException e) {
4012                                    throw new IllegalStateException("Could not execute non "
4013                                            + "public method of the activity", e);
4014                                } catch (InvocationTargetException e) {
4015                                    throw new IllegalStateException("Could not execute "
4016                                            + "method of the activity", e);
4017                                }
4018                            }
4019                        });
4020                    }
4021                    break;
4022                case R.styleable.View_overScrollMode:
4023                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4024                    break;
4025                case R.styleable.View_verticalScrollbarPosition:
4026                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4027                    break;
4028                case R.styleable.View_layerType:
4029                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4030                    break;
4031                case R.styleable.View_textDirection:
4032                    // Clear any text direction flag already set
4033                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4034                    // Set the text direction flags depending on the value of the attribute
4035                    final int textDirection = a.getInt(attr, -1);
4036                    if (textDirection != -1) {
4037                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4038                    }
4039                    break;
4040                case R.styleable.View_textAlignment:
4041                    // Clear any text alignment flag already set
4042                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4043                    // Set the text alignment flag depending on the value of the attribute
4044                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4045                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4046                    break;
4047                case R.styleable.View_importantForAccessibility:
4048                    setImportantForAccessibility(a.getInt(attr,
4049                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4050                    break;
4051                case R.styleable.View_accessibilityLiveRegion:
4052                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4053                    break;
4054                case R.styleable.View_sharedElementName:
4055                    setSharedElementName(a.getString(attr));
4056                    break;
4057            }
4058        }
4059
4060        setOverScrollMode(overScrollMode);
4061
4062        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4063        // the resolved layout direction). Those cached values will be used later during padding
4064        // resolution.
4065        mUserPaddingStart = startPadding;
4066        mUserPaddingEnd = endPadding;
4067
4068        if (background != null) {
4069            setBackground(background);
4070        }
4071
4072        // setBackground above will record that padding is currently provided by the background.
4073        // If we have padding specified via xml, record that here instead and use it.
4074        mLeftPaddingDefined = leftPaddingDefined;
4075        mRightPaddingDefined = rightPaddingDefined;
4076
4077        if (padding >= 0) {
4078            leftPadding = padding;
4079            topPadding = padding;
4080            rightPadding = padding;
4081            bottomPadding = padding;
4082            mUserPaddingLeftInitial = padding;
4083            mUserPaddingRightInitial = padding;
4084        }
4085
4086        if (isRtlCompatibilityMode()) {
4087            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4088            // left / right padding are used if defined (meaning here nothing to do). If they are not
4089            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4090            // start / end and resolve them as left / right (layout direction is not taken into account).
4091            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4092            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4093            // defined.
4094            if (!mLeftPaddingDefined && startPaddingDefined) {
4095                leftPadding = startPadding;
4096            }
4097            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4098            if (!mRightPaddingDefined && endPaddingDefined) {
4099                rightPadding = endPadding;
4100            }
4101            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4102        } else {
4103            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4104            // values defined. Otherwise, left /right values are used.
4105            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4106            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4107            // defined.
4108            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4109
4110            if (mLeftPaddingDefined && !hasRelativePadding) {
4111                mUserPaddingLeftInitial = leftPadding;
4112            }
4113            if (mRightPaddingDefined && !hasRelativePadding) {
4114                mUserPaddingRightInitial = rightPadding;
4115            }
4116        }
4117
4118        internalSetPadding(
4119                mUserPaddingLeftInitial,
4120                topPadding >= 0 ? topPadding : mPaddingTop,
4121                mUserPaddingRightInitial,
4122                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4123
4124        if (viewFlagMasks != 0) {
4125            setFlags(viewFlagValues, viewFlagMasks);
4126        }
4127
4128        if (initializeScrollbars) {
4129            initializeScrollbars(a);
4130        }
4131
4132        a.recycle();
4133
4134        // Needs to be called after mViewFlags is set
4135        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4136            recomputePadding();
4137        }
4138
4139        if (x != 0 || y != 0) {
4140            scrollTo(x, y);
4141        }
4142
4143        if (transformSet) {
4144            setTranslationX(tx);
4145            setTranslationY(ty);
4146            setTranslationZ(tz);
4147            setRotation(rotation);
4148            setRotationX(rotationX);
4149            setRotationY(rotationY);
4150            setScaleX(sx);
4151            setScaleY(sy);
4152        }
4153
4154        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4155            setScrollContainer(true);
4156        }
4157
4158        computeOpaqueFlags();
4159    }
4160
4161    /**
4162     * Non-public constructor for use in testing
4163     */
4164    View() {
4165        mResources = null;
4166    }
4167
4168    public String toString() {
4169        StringBuilder out = new StringBuilder(128);
4170        out.append(getClass().getName());
4171        out.append('{');
4172        out.append(Integer.toHexString(System.identityHashCode(this)));
4173        out.append(' ');
4174        switch (mViewFlags&VISIBILITY_MASK) {
4175            case VISIBLE: out.append('V'); break;
4176            case INVISIBLE: out.append('I'); break;
4177            case GONE: out.append('G'); break;
4178            default: out.append('.'); break;
4179        }
4180        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4181        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4182        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4183        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4184        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4185        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4186        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4187        out.append(' ');
4188        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4189        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4190        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4191        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4192            out.append('p');
4193        } else {
4194            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4195        }
4196        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4197        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4198        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4199        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4200        out.append(' ');
4201        out.append(mLeft);
4202        out.append(',');
4203        out.append(mTop);
4204        out.append('-');
4205        out.append(mRight);
4206        out.append(',');
4207        out.append(mBottom);
4208        final int id = getId();
4209        if (id != NO_ID) {
4210            out.append(" #");
4211            out.append(Integer.toHexString(id));
4212            final Resources r = mResources;
4213            if (id != 0 && r != null) {
4214                try {
4215                    String pkgname;
4216                    switch (id&0xff000000) {
4217                        case 0x7f000000:
4218                            pkgname="app";
4219                            break;
4220                        case 0x01000000:
4221                            pkgname="android";
4222                            break;
4223                        default:
4224                            pkgname = r.getResourcePackageName(id);
4225                            break;
4226                    }
4227                    String typename = r.getResourceTypeName(id);
4228                    String entryname = r.getResourceEntryName(id);
4229                    out.append(" ");
4230                    out.append(pkgname);
4231                    out.append(":");
4232                    out.append(typename);
4233                    out.append("/");
4234                    out.append(entryname);
4235                } catch (Resources.NotFoundException e) {
4236                }
4237            }
4238        }
4239        out.append("}");
4240        return out.toString();
4241    }
4242
4243    /**
4244     * <p>
4245     * Initializes the fading edges from a given set of styled attributes. This
4246     * method should be called by subclasses that need fading edges and when an
4247     * instance of these subclasses is created programmatically rather than
4248     * being inflated from XML. This method is automatically called when the XML
4249     * is inflated.
4250     * </p>
4251     *
4252     * @param a the styled attributes set to initialize the fading edges from
4253     */
4254    protected void initializeFadingEdge(TypedArray a) {
4255        initScrollCache();
4256
4257        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4258                R.styleable.View_fadingEdgeLength,
4259                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4260    }
4261
4262    /**
4263     * Returns the size of the vertical faded edges used to indicate that more
4264     * content in this view is visible.
4265     *
4266     * @return The size in pixels of the vertical faded edge or 0 if vertical
4267     *         faded edges are not enabled for this view.
4268     * @attr ref android.R.styleable#View_fadingEdgeLength
4269     */
4270    public int getVerticalFadingEdgeLength() {
4271        if (isVerticalFadingEdgeEnabled()) {
4272            ScrollabilityCache cache = mScrollCache;
4273            if (cache != null) {
4274                return cache.fadingEdgeLength;
4275            }
4276        }
4277        return 0;
4278    }
4279
4280    /**
4281     * Set the size of the faded edge used to indicate that more content in this
4282     * view is available.  Will not change whether the fading edge is enabled; use
4283     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4284     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4285     * for the vertical or horizontal fading edges.
4286     *
4287     * @param length The size in pixels of the faded edge used to indicate that more
4288     *        content in this view is visible.
4289     */
4290    public void setFadingEdgeLength(int length) {
4291        initScrollCache();
4292        mScrollCache.fadingEdgeLength = length;
4293    }
4294
4295    /**
4296     * Returns the size of the horizontal faded edges used to indicate that more
4297     * content in this view is visible.
4298     *
4299     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4300     *         faded edges are not enabled for this view.
4301     * @attr ref android.R.styleable#View_fadingEdgeLength
4302     */
4303    public int getHorizontalFadingEdgeLength() {
4304        if (isHorizontalFadingEdgeEnabled()) {
4305            ScrollabilityCache cache = mScrollCache;
4306            if (cache != null) {
4307                return cache.fadingEdgeLength;
4308            }
4309        }
4310        return 0;
4311    }
4312
4313    /**
4314     * Returns the width of the vertical scrollbar.
4315     *
4316     * @return The width in pixels of the vertical scrollbar or 0 if there
4317     *         is no vertical scrollbar.
4318     */
4319    public int getVerticalScrollbarWidth() {
4320        ScrollabilityCache cache = mScrollCache;
4321        if (cache != null) {
4322            ScrollBarDrawable scrollBar = cache.scrollBar;
4323            if (scrollBar != null) {
4324                int size = scrollBar.getSize(true);
4325                if (size <= 0) {
4326                    size = cache.scrollBarSize;
4327                }
4328                return size;
4329            }
4330            return 0;
4331        }
4332        return 0;
4333    }
4334
4335    /**
4336     * Returns the height of the horizontal scrollbar.
4337     *
4338     * @return The height in pixels of the horizontal scrollbar or 0 if
4339     *         there is no horizontal scrollbar.
4340     */
4341    protected int getHorizontalScrollbarHeight() {
4342        ScrollabilityCache cache = mScrollCache;
4343        if (cache != null) {
4344            ScrollBarDrawable scrollBar = cache.scrollBar;
4345            if (scrollBar != null) {
4346                int size = scrollBar.getSize(false);
4347                if (size <= 0) {
4348                    size = cache.scrollBarSize;
4349                }
4350                return size;
4351            }
4352            return 0;
4353        }
4354        return 0;
4355    }
4356
4357    /**
4358     * <p>
4359     * Initializes the scrollbars from a given set of styled attributes. This
4360     * method should be called by subclasses that need scrollbars and when an
4361     * instance of these subclasses is created programmatically rather than
4362     * being inflated from XML. This method is automatically called when the XML
4363     * is inflated.
4364     * </p>
4365     *
4366     * @param a the styled attributes set to initialize the scrollbars from
4367     */
4368    protected void initializeScrollbars(TypedArray a) {
4369        initScrollCache();
4370
4371        final ScrollabilityCache scrollabilityCache = mScrollCache;
4372
4373        if (scrollabilityCache.scrollBar == null) {
4374            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4375        }
4376
4377        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4378
4379        if (!fadeScrollbars) {
4380            scrollabilityCache.state = ScrollabilityCache.ON;
4381        }
4382        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4383
4384
4385        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4386                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4387                        .getScrollBarFadeDuration());
4388        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4389                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4390                ViewConfiguration.getScrollDefaultDelay());
4391
4392
4393        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4394                com.android.internal.R.styleable.View_scrollbarSize,
4395                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4396
4397        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4398        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4399
4400        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4401        if (thumb != null) {
4402            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4403        }
4404
4405        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4406                false);
4407        if (alwaysDraw) {
4408            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4409        }
4410
4411        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4412        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4413
4414        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4415        if (thumb != null) {
4416            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4417        }
4418
4419        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4420                false);
4421        if (alwaysDraw) {
4422            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4423        }
4424
4425        // Apply layout direction to the new Drawables if needed
4426        final int layoutDirection = getLayoutDirection();
4427        if (track != null) {
4428            track.setLayoutDirection(layoutDirection);
4429        }
4430        if (thumb != null) {
4431            thumb.setLayoutDirection(layoutDirection);
4432        }
4433
4434        // Re-apply user/background padding so that scrollbar(s) get added
4435        resolvePadding();
4436    }
4437
4438    /**
4439     * <p>
4440     * Initalizes the scrollability cache if necessary.
4441     * </p>
4442     */
4443    private void initScrollCache() {
4444        if (mScrollCache == null) {
4445            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4446        }
4447    }
4448
4449    private ScrollabilityCache getScrollCache() {
4450        initScrollCache();
4451        return mScrollCache;
4452    }
4453
4454    /**
4455     * Set the position of the vertical scroll bar. Should be one of
4456     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4457     * {@link #SCROLLBAR_POSITION_RIGHT}.
4458     *
4459     * @param position Where the vertical scroll bar should be positioned.
4460     */
4461    public void setVerticalScrollbarPosition(int position) {
4462        if (mVerticalScrollbarPosition != position) {
4463            mVerticalScrollbarPosition = position;
4464            computeOpaqueFlags();
4465            resolvePadding();
4466        }
4467    }
4468
4469    /**
4470     * @return The position where the vertical scroll bar will show, if applicable.
4471     * @see #setVerticalScrollbarPosition(int)
4472     */
4473    public int getVerticalScrollbarPosition() {
4474        return mVerticalScrollbarPosition;
4475    }
4476
4477    ListenerInfo getListenerInfo() {
4478        if (mListenerInfo != null) {
4479            return mListenerInfo;
4480        }
4481        mListenerInfo = new ListenerInfo();
4482        return mListenerInfo;
4483    }
4484
4485    /**
4486     * Register a callback to be invoked when focus of this view changed.
4487     *
4488     * @param l The callback that will run.
4489     */
4490    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4491        getListenerInfo().mOnFocusChangeListener = l;
4492    }
4493
4494    /**
4495     * Add a listener that will be called when the bounds of the view change due to
4496     * layout processing.
4497     *
4498     * @param listener The listener that will be called when layout bounds change.
4499     */
4500    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4501        ListenerInfo li = getListenerInfo();
4502        if (li.mOnLayoutChangeListeners == null) {
4503            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4504        }
4505        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4506            li.mOnLayoutChangeListeners.add(listener);
4507        }
4508    }
4509
4510    /**
4511     * Remove a listener for layout changes.
4512     *
4513     * @param listener The listener for layout bounds change.
4514     */
4515    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4516        ListenerInfo li = mListenerInfo;
4517        if (li == null || li.mOnLayoutChangeListeners == null) {
4518            return;
4519        }
4520        li.mOnLayoutChangeListeners.remove(listener);
4521    }
4522
4523    /**
4524     * Add a listener for attach state changes.
4525     *
4526     * This listener will be called whenever this view is attached or detached
4527     * from a window. Remove the listener using
4528     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4529     *
4530     * @param listener Listener to attach
4531     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4532     */
4533    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4534        ListenerInfo li = getListenerInfo();
4535        if (li.mOnAttachStateChangeListeners == null) {
4536            li.mOnAttachStateChangeListeners
4537                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4538        }
4539        li.mOnAttachStateChangeListeners.add(listener);
4540    }
4541
4542    /**
4543     * Remove a listener for attach state changes. The listener will receive no further
4544     * notification of window attach/detach events.
4545     *
4546     * @param listener Listener to remove
4547     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4548     */
4549    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4550        ListenerInfo li = mListenerInfo;
4551        if (li == null || li.mOnAttachStateChangeListeners == null) {
4552            return;
4553        }
4554        li.mOnAttachStateChangeListeners.remove(listener);
4555    }
4556
4557    /**
4558     * Returns the focus-change callback registered for this view.
4559     *
4560     * @return The callback, or null if one is not registered.
4561     */
4562    public OnFocusChangeListener getOnFocusChangeListener() {
4563        ListenerInfo li = mListenerInfo;
4564        return li != null ? li.mOnFocusChangeListener : null;
4565    }
4566
4567    /**
4568     * Register a callback to be invoked when this view is clicked. If this view is not
4569     * clickable, it becomes clickable.
4570     *
4571     * @param l The callback that will run
4572     *
4573     * @see #setClickable(boolean)
4574     */
4575    public void setOnClickListener(OnClickListener l) {
4576        if (!isClickable()) {
4577            setClickable(true);
4578        }
4579        getListenerInfo().mOnClickListener = l;
4580    }
4581
4582    /**
4583     * Return whether this view has an attached OnClickListener.  Returns
4584     * true if there is a listener, false if there is none.
4585     */
4586    public boolean hasOnClickListeners() {
4587        ListenerInfo li = mListenerInfo;
4588        return (li != null && li.mOnClickListener != null);
4589    }
4590
4591    /**
4592     * Register a callback to be invoked when this view is clicked and held. If this view is not
4593     * long clickable, it becomes long clickable.
4594     *
4595     * @param l The callback that will run
4596     *
4597     * @see #setLongClickable(boolean)
4598     */
4599    public void setOnLongClickListener(OnLongClickListener l) {
4600        if (!isLongClickable()) {
4601            setLongClickable(true);
4602        }
4603        getListenerInfo().mOnLongClickListener = l;
4604    }
4605
4606    /**
4607     * Register a callback to be invoked when the context menu for this view is
4608     * being built. If this view is not long clickable, it becomes long clickable.
4609     *
4610     * @param l The callback that will run
4611     *
4612     */
4613    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4614        if (!isLongClickable()) {
4615            setLongClickable(true);
4616        }
4617        getListenerInfo().mOnCreateContextMenuListener = l;
4618    }
4619
4620    /**
4621     * Call this view's OnClickListener, if it is defined.  Performs all normal
4622     * actions associated with clicking: reporting accessibility event, playing
4623     * a sound, etc.
4624     *
4625     * @return True there was an assigned OnClickListener that was called, false
4626     *         otherwise is returned.
4627     */
4628    public boolean performClick() {
4629        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4630
4631        ListenerInfo li = mListenerInfo;
4632        if (li != null && li.mOnClickListener != null) {
4633            playSoundEffect(SoundEffectConstants.CLICK);
4634            li.mOnClickListener.onClick(this);
4635            return true;
4636        }
4637
4638        return false;
4639    }
4640
4641    /**
4642     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4643     * this only calls the listener, and does not do any associated clicking
4644     * actions like reporting an accessibility event.
4645     *
4646     * @return True there was an assigned OnClickListener that was called, false
4647     *         otherwise is returned.
4648     */
4649    public boolean callOnClick() {
4650        ListenerInfo li = mListenerInfo;
4651        if (li != null && li.mOnClickListener != null) {
4652            li.mOnClickListener.onClick(this);
4653            return true;
4654        }
4655        return false;
4656    }
4657
4658    /**
4659     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4660     * OnLongClickListener did not consume the event.
4661     *
4662     * @return True if one of the above receivers consumed the event, false otherwise.
4663     */
4664    public boolean performLongClick() {
4665        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4666
4667        boolean handled = false;
4668        ListenerInfo li = mListenerInfo;
4669        if (li != null && li.mOnLongClickListener != null) {
4670            handled = li.mOnLongClickListener.onLongClick(View.this);
4671        }
4672        if (!handled) {
4673            handled = showContextMenu();
4674        }
4675        if (handled) {
4676            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4677        }
4678        return handled;
4679    }
4680
4681    /**
4682     * Performs button-related actions during a touch down event.
4683     *
4684     * @param event The event.
4685     * @return True if the down was consumed.
4686     *
4687     * @hide
4688     */
4689    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4690        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4691            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4692                return true;
4693            }
4694        }
4695        return false;
4696    }
4697
4698    /**
4699     * Bring up the context menu for this view.
4700     *
4701     * @return Whether a context menu was displayed.
4702     */
4703    public boolean showContextMenu() {
4704        return getParent().showContextMenuForChild(this);
4705    }
4706
4707    /**
4708     * Bring up the context menu for this view, referring to the item under the specified point.
4709     *
4710     * @param x The referenced x coordinate.
4711     * @param y The referenced y coordinate.
4712     * @param metaState The keyboard modifiers that were pressed.
4713     * @return Whether a context menu was displayed.
4714     *
4715     * @hide
4716     */
4717    public boolean showContextMenu(float x, float y, int metaState) {
4718        return showContextMenu();
4719    }
4720
4721    /**
4722     * Start an action mode.
4723     *
4724     * @param callback Callback that will control the lifecycle of the action mode
4725     * @return The new action mode if it is started, null otherwise
4726     *
4727     * @see ActionMode
4728     */
4729    public ActionMode startActionMode(ActionMode.Callback callback) {
4730        ViewParent parent = getParent();
4731        if (parent == null) return null;
4732        return parent.startActionModeForChild(this, callback);
4733    }
4734
4735    /**
4736     * Register a callback to be invoked when a hardware key is pressed in this view.
4737     * Key presses in software input methods will generally not trigger the methods of
4738     * this listener.
4739     * @param l the key listener to attach to this view
4740     */
4741    public void setOnKeyListener(OnKeyListener l) {
4742        getListenerInfo().mOnKeyListener = l;
4743    }
4744
4745    /**
4746     * Register a callback to be invoked when a touch event is sent to this view.
4747     * @param l the touch listener to attach to this view
4748     */
4749    public void setOnTouchListener(OnTouchListener l) {
4750        getListenerInfo().mOnTouchListener = l;
4751    }
4752
4753    /**
4754     * Register a callback to be invoked when a generic motion event is sent to this view.
4755     * @param l the generic motion listener to attach to this view
4756     */
4757    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4758        getListenerInfo().mOnGenericMotionListener = l;
4759    }
4760
4761    /**
4762     * Register a callback to be invoked when a hover event is sent to this view.
4763     * @param l the hover listener to attach to this view
4764     */
4765    public void setOnHoverListener(OnHoverListener l) {
4766        getListenerInfo().mOnHoverListener = l;
4767    }
4768
4769    /**
4770     * Register a drag event listener callback object for this View. The parameter is
4771     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4772     * View, the system calls the
4773     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4774     * @param l An implementation of {@link android.view.View.OnDragListener}.
4775     */
4776    public void setOnDragListener(OnDragListener l) {
4777        getListenerInfo().mOnDragListener = l;
4778    }
4779
4780    /**
4781     * Give this view focus. This will cause
4782     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4783     *
4784     * Note: this does not check whether this {@link View} should get focus, it just
4785     * gives it focus no matter what.  It should only be called internally by framework
4786     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4787     *
4788     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4789     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4790     *        focus moved when requestFocus() is called. It may not always
4791     *        apply, in which case use the default View.FOCUS_DOWN.
4792     * @param previouslyFocusedRect The rectangle of the view that had focus
4793     *        prior in this View's coordinate system.
4794     */
4795    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4796        if (DBG) {
4797            System.out.println(this + " requestFocus()");
4798        }
4799
4800        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4801            mPrivateFlags |= PFLAG_FOCUSED;
4802
4803            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4804
4805            if (mParent != null) {
4806                mParent.requestChildFocus(this, this);
4807            }
4808
4809            if (mAttachInfo != null) {
4810                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4811            }
4812
4813            manageFocusHotspot(true, oldFocus);
4814            onFocusChanged(true, direction, previouslyFocusedRect);
4815            refreshDrawableState();
4816        }
4817    }
4818
4819    /**
4820     * Forwards focus information to the background drawable, if necessary. When
4821     * the view is gaining focus, <code>v</code> is the previous focus holder.
4822     * When the view is losing focus, <code>v</code> is the next focus holder.
4823     *
4824     * @param focused whether this view is focused
4825     * @param v previous or the next focus holder, or null if none
4826     */
4827    private void manageFocusHotspot(boolean focused, View v) {
4828        if (mBackground != null && mBackground.supportsHotspots()) {
4829            final Rect r = new Rect();
4830            if (v != null) {
4831                v.getBoundsOnScreen(r);
4832                final int[] location = new int[2];
4833                getLocationOnScreen(location);
4834                r.offset(-location[0], -location[1]);
4835            } else {
4836                r.set(mLeft, mTop, mRight, mBottom);
4837            }
4838
4839            final float x = r.exactCenterX();
4840            final float y = r.exactCenterY();
4841            mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y);
4842
4843            if (!focused) {
4844                mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS);
4845            }
4846        }
4847    }
4848
4849    /**
4850     * Request that a rectangle of this view be visible on the screen,
4851     * scrolling if necessary just enough.
4852     *
4853     * <p>A View should call this if it maintains some notion of which part
4854     * of its content is interesting.  For example, a text editing view
4855     * should call this when its cursor moves.
4856     *
4857     * @param rectangle The rectangle.
4858     * @return Whether any parent scrolled.
4859     */
4860    public boolean requestRectangleOnScreen(Rect rectangle) {
4861        return requestRectangleOnScreen(rectangle, false);
4862    }
4863
4864    /**
4865     * Request that a rectangle of this view be visible on the screen,
4866     * scrolling if necessary just enough.
4867     *
4868     * <p>A View should call this if it maintains some notion of which part
4869     * of its content is interesting.  For example, a text editing view
4870     * should call this when its cursor moves.
4871     *
4872     * <p>When <code>immediate</code> is set to true, scrolling will not be
4873     * animated.
4874     *
4875     * @param rectangle The rectangle.
4876     * @param immediate True to forbid animated scrolling, false otherwise
4877     * @return Whether any parent scrolled.
4878     */
4879    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4880        if (mParent == null) {
4881            return false;
4882        }
4883
4884        View child = this;
4885
4886        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4887        position.set(rectangle);
4888
4889        ViewParent parent = mParent;
4890        boolean scrolled = false;
4891        while (parent != null) {
4892            rectangle.set((int) position.left, (int) position.top,
4893                    (int) position.right, (int) position.bottom);
4894
4895            scrolled |= parent.requestChildRectangleOnScreen(child,
4896                    rectangle, immediate);
4897
4898            if (!child.hasIdentityMatrix()) {
4899                child.getMatrix().mapRect(position);
4900            }
4901
4902            position.offset(child.mLeft, child.mTop);
4903
4904            if (!(parent instanceof View)) {
4905                break;
4906            }
4907
4908            View parentView = (View) parent;
4909
4910            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4911
4912            child = parentView;
4913            parent = child.getParent();
4914        }
4915
4916        return scrolled;
4917    }
4918
4919    /**
4920     * Called when this view wants to give up focus. If focus is cleared
4921     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4922     * <p>
4923     * <strong>Note:</strong> When a View clears focus the framework is trying
4924     * to give focus to the first focusable View from the top. Hence, if this
4925     * View is the first from the top that can take focus, then all callbacks
4926     * related to clearing focus will be invoked after wich the framework will
4927     * give focus to this view.
4928     * </p>
4929     */
4930    public void clearFocus() {
4931        if (DBG) {
4932            System.out.println(this + " clearFocus()");
4933        }
4934
4935        clearFocusInternal(null, true, true);
4936    }
4937
4938    /**
4939     * Clears focus from the view, optionally propagating the change up through
4940     * the parent hierarchy and requesting that the root view place new focus.
4941     *
4942     * @param propagate whether to propagate the change up through the parent
4943     *            hierarchy
4944     * @param refocus when propagate is true, specifies whether to request the
4945     *            root view place new focus
4946     */
4947    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4948        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4949            mPrivateFlags &= ~PFLAG_FOCUSED;
4950
4951            if (hasFocus()) {
4952                manageFocusHotspot(false, focused);
4953            }
4954
4955            if (propagate && mParent != null) {
4956                mParent.clearChildFocus(this);
4957            }
4958
4959            onFocusChanged(false, 0, null);
4960
4961            refreshDrawableState();
4962
4963            if (propagate && (!refocus || !rootViewRequestFocus())) {
4964                notifyGlobalFocusCleared(this);
4965            }
4966        }
4967    }
4968
4969    void notifyGlobalFocusCleared(View oldFocus) {
4970        if (oldFocus != null && mAttachInfo != null) {
4971            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4972        }
4973    }
4974
4975    boolean rootViewRequestFocus() {
4976        final View root = getRootView();
4977        return root != null && root.requestFocus();
4978    }
4979
4980    /**
4981     * Called internally by the view system when a new view is getting focus.
4982     * This is what clears the old focus.
4983     * <p>
4984     * <b>NOTE:</b> The parent view's focused child must be updated manually
4985     * after calling this method. Otherwise, the view hierarchy may be left in
4986     * an inconstent state.
4987     */
4988    void unFocus(View focused) {
4989        if (DBG) {
4990            System.out.println(this + " unFocus()");
4991        }
4992
4993        clearFocusInternal(focused, false, false);
4994    }
4995
4996    /**
4997     * Returns true if this view has focus iteself, or is the ancestor of the
4998     * view that has focus.
4999     *
5000     * @return True if this view has or contains focus, false otherwise.
5001     */
5002    @ViewDebug.ExportedProperty(category = "focus")
5003    public boolean hasFocus() {
5004        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5005    }
5006
5007    /**
5008     * Returns true if this view is focusable or if it contains a reachable View
5009     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5010     * is a View whose parents do not block descendants focus.
5011     *
5012     * Only {@link #VISIBLE} views are considered focusable.
5013     *
5014     * @return True if the view is focusable or if the view contains a focusable
5015     *         View, false otherwise.
5016     *
5017     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5018     */
5019    public boolean hasFocusable() {
5020        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5021    }
5022
5023    /**
5024     * Called by the view system when the focus state of this view changes.
5025     * When the focus change event is caused by directional navigation, direction
5026     * and previouslyFocusedRect provide insight into where the focus is coming from.
5027     * When overriding, be sure to call up through to the super class so that
5028     * the standard focus handling will occur.
5029     *
5030     * @param gainFocus True if the View has focus; false otherwise.
5031     * @param direction The direction focus has moved when requestFocus()
5032     *                  is called to give this view focus. Values are
5033     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5034     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5035     *                  It may not always apply, in which case use the default.
5036     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5037     *        system, of the previously focused view.  If applicable, this will be
5038     *        passed in as finer grained information about where the focus is coming
5039     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5040     */
5041    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5042            @Nullable Rect previouslyFocusedRect) {
5043        if (gainFocus) {
5044            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5045        } else {
5046            notifyViewAccessibilityStateChangedIfNeeded(
5047                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5048        }
5049
5050        InputMethodManager imm = InputMethodManager.peekInstance();
5051        if (!gainFocus) {
5052            if (isPressed()) {
5053                setPressed(false);
5054            }
5055            if (imm != null && mAttachInfo != null
5056                    && mAttachInfo.mHasWindowFocus) {
5057                imm.focusOut(this);
5058            }
5059            onFocusLost();
5060        } else if (imm != null && mAttachInfo != null
5061                && mAttachInfo.mHasWindowFocus) {
5062            imm.focusIn(this);
5063        }
5064
5065        invalidate(true);
5066        ListenerInfo li = mListenerInfo;
5067        if (li != null && li.mOnFocusChangeListener != null) {
5068            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5069        }
5070
5071        if (mAttachInfo != null) {
5072            mAttachInfo.mKeyDispatchState.reset(this);
5073        }
5074    }
5075
5076    /**
5077     * Sends an accessibility event of the given type. If accessibility is
5078     * not enabled this method has no effect. The default implementation calls
5079     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5080     * to populate information about the event source (this View), then calls
5081     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5082     * populate the text content of the event source including its descendants,
5083     * and last calls
5084     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5085     * on its parent to resuest sending of the event to interested parties.
5086     * <p>
5087     * If an {@link AccessibilityDelegate} has been specified via calling
5088     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5089     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5090     * responsible for handling this call.
5091     * </p>
5092     *
5093     * @param eventType The type of the event to send, as defined by several types from
5094     * {@link android.view.accessibility.AccessibilityEvent}, such as
5095     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5096     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5097     *
5098     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5099     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5100     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5101     * @see AccessibilityDelegate
5102     */
5103    public void sendAccessibilityEvent(int eventType) {
5104        // Excluded views do not send accessibility events.
5105        if (!includeForAccessibility()) {
5106            return;
5107        }
5108        if (mAccessibilityDelegate != null) {
5109            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5110        } else {
5111            sendAccessibilityEventInternal(eventType);
5112        }
5113    }
5114
5115    /**
5116     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5117     * {@link AccessibilityEvent} to make an announcement which is related to some
5118     * sort of a context change for which none of the events representing UI transitions
5119     * is a good fit. For example, announcing a new page in a book. If accessibility
5120     * is not enabled this method does nothing.
5121     *
5122     * @param text The announcement text.
5123     */
5124    public void announceForAccessibility(CharSequence text) {
5125        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null
5126                && isImportantForAccessibility()) {
5127            AccessibilityEvent event = AccessibilityEvent.obtain(
5128                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5129            onInitializeAccessibilityEvent(event);
5130            event.getText().add(text);
5131            event.setContentDescription(null);
5132            mParent.requestSendAccessibilityEvent(this, event);
5133        }
5134    }
5135
5136    /**
5137     * @see #sendAccessibilityEvent(int)
5138     *
5139     * Note: Called from the default {@link AccessibilityDelegate}.
5140     */
5141    void sendAccessibilityEventInternal(int eventType) {
5142        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5143            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5144        }
5145    }
5146
5147    /**
5148     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5149     * takes as an argument an empty {@link AccessibilityEvent} and does not
5150     * perform a check whether accessibility is enabled.
5151     * <p>
5152     * If an {@link AccessibilityDelegate} has been specified via calling
5153     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5154     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5155     * is responsible for handling this call.
5156     * </p>
5157     *
5158     * @param event The event to send.
5159     *
5160     * @see #sendAccessibilityEvent(int)
5161     */
5162    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5163        if (mAccessibilityDelegate != null) {
5164            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5165        } else {
5166            sendAccessibilityEventUncheckedInternal(event);
5167        }
5168    }
5169
5170    /**
5171     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5172     *
5173     * Note: Called from the default {@link AccessibilityDelegate}.
5174     */
5175    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5176        if (!isShown() || !isImportantForAccessibility()) {
5177            return;
5178        }
5179        onInitializeAccessibilityEvent(event);
5180        // Only a subset of accessibility events populates text content.
5181        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5182            dispatchPopulateAccessibilityEvent(event);
5183        }
5184        // In the beginning we called #isShown(), so we know that getParent() is not null.
5185        getParent().requestSendAccessibilityEvent(this, event);
5186    }
5187
5188    /**
5189     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5190     * to its children for adding their text content to the event. Note that the
5191     * event text is populated in a separate dispatch path since we add to the
5192     * event not only the text of the source but also the text of all its descendants.
5193     * A typical implementation will call
5194     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5195     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5196     * on each child. Override this method if custom population of the event text
5197     * content is required.
5198     * <p>
5199     * If an {@link AccessibilityDelegate} has been specified via calling
5200     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5201     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5202     * is responsible for handling this call.
5203     * </p>
5204     * <p>
5205     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5206     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5207     * </p>
5208     *
5209     * @param event The event.
5210     *
5211     * @return True if the event population was completed.
5212     */
5213    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5214        if (mAccessibilityDelegate != null) {
5215            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5216        } else {
5217            return dispatchPopulateAccessibilityEventInternal(event);
5218        }
5219    }
5220
5221    /**
5222     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5223     *
5224     * Note: Called from the default {@link AccessibilityDelegate}.
5225     */
5226    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5227        onPopulateAccessibilityEvent(event);
5228        return false;
5229    }
5230
5231    /**
5232     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5233     * giving a chance to this View to populate the accessibility event with its
5234     * text content. While this method is free to modify event
5235     * attributes other than text content, doing so should normally be performed in
5236     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5237     * <p>
5238     * Example: Adding formatted date string to an accessibility event in addition
5239     *          to the text added by the super implementation:
5240     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5241     *     super.onPopulateAccessibilityEvent(event);
5242     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5243     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5244     *         mCurrentDate.getTimeInMillis(), flags);
5245     *     event.getText().add(selectedDateUtterance);
5246     * }</pre>
5247     * <p>
5248     * If an {@link AccessibilityDelegate} has been specified via calling
5249     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5250     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5251     * is responsible for handling this call.
5252     * </p>
5253     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5254     * information to the event, in case the default implementation has basic information to add.
5255     * </p>
5256     *
5257     * @param event The accessibility event which to populate.
5258     *
5259     * @see #sendAccessibilityEvent(int)
5260     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5261     */
5262    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5263        if (mAccessibilityDelegate != null) {
5264            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5265        } else {
5266            onPopulateAccessibilityEventInternal(event);
5267        }
5268    }
5269
5270    /**
5271     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5272     *
5273     * Note: Called from the default {@link AccessibilityDelegate}.
5274     */
5275    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5276    }
5277
5278    /**
5279     * Initializes an {@link AccessibilityEvent} with information about
5280     * this View which is the event source. In other words, the source of
5281     * an accessibility event is the view whose state change triggered firing
5282     * the event.
5283     * <p>
5284     * Example: Setting the password property of an event in addition
5285     *          to properties set by the super implementation:
5286     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5287     *     super.onInitializeAccessibilityEvent(event);
5288     *     event.setPassword(true);
5289     * }</pre>
5290     * <p>
5291     * If an {@link AccessibilityDelegate} has been specified via calling
5292     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5293     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5294     * is responsible for handling this call.
5295     * </p>
5296     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5297     * information to the event, in case the default implementation has basic information to add.
5298     * </p>
5299     * @param event The event to initialize.
5300     *
5301     * @see #sendAccessibilityEvent(int)
5302     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5303     */
5304    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5305        if (mAccessibilityDelegate != null) {
5306            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5307        } else {
5308            onInitializeAccessibilityEventInternal(event);
5309        }
5310    }
5311
5312    /**
5313     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5314     *
5315     * Note: Called from the default {@link AccessibilityDelegate}.
5316     */
5317    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5318        event.setSource(this);
5319        event.setClassName(View.class.getName());
5320        event.setPackageName(getContext().getPackageName());
5321        event.setEnabled(isEnabled());
5322        event.setContentDescription(mContentDescription);
5323
5324        switch (event.getEventType()) {
5325            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5326                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5327                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5328                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5329                event.setItemCount(focusablesTempList.size());
5330                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5331                if (mAttachInfo != null) {
5332                    focusablesTempList.clear();
5333                }
5334            } break;
5335            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5336                CharSequence text = getIterableTextForAccessibility();
5337                if (text != null && text.length() > 0) {
5338                    event.setFromIndex(getAccessibilitySelectionStart());
5339                    event.setToIndex(getAccessibilitySelectionEnd());
5340                    event.setItemCount(text.length());
5341                }
5342            } break;
5343        }
5344    }
5345
5346    /**
5347     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5348     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5349     * This method is responsible for obtaining an accessibility node info from a
5350     * pool of reusable instances and calling
5351     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5352     * initialize the former.
5353     * <p>
5354     * Note: The client is responsible for recycling the obtained instance by calling
5355     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5356     * </p>
5357     *
5358     * @return A populated {@link AccessibilityNodeInfo}.
5359     *
5360     * @see AccessibilityNodeInfo
5361     */
5362    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5363        if (mAccessibilityDelegate != null) {
5364            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5365        } else {
5366            return createAccessibilityNodeInfoInternal();
5367        }
5368    }
5369
5370    /**
5371     * @see #createAccessibilityNodeInfo()
5372     */
5373    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5374        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5375        if (provider != null) {
5376            return provider.createAccessibilityNodeInfo(View.NO_ID);
5377        } else {
5378            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5379            onInitializeAccessibilityNodeInfo(info);
5380            return info;
5381        }
5382    }
5383
5384    /**
5385     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5386     * The base implementation sets:
5387     * <ul>
5388     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5389     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5390     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5391     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5392     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5393     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5394     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5395     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5396     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5397     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5398     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5399     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5400     * </ul>
5401     * <p>
5402     * Subclasses should override this method, call the super implementation,
5403     * and set additional attributes.
5404     * </p>
5405     * <p>
5406     * If an {@link AccessibilityDelegate} has been specified via calling
5407     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5408     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5409     * is responsible for handling this call.
5410     * </p>
5411     *
5412     * @param info The instance to initialize.
5413     */
5414    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5415        if (mAccessibilityDelegate != null) {
5416            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5417        } else {
5418            onInitializeAccessibilityNodeInfoInternal(info);
5419        }
5420    }
5421
5422    /**
5423     * Gets the location of this view in screen coordintates.
5424     *
5425     * @param outRect The output location
5426     */
5427    void getBoundsOnScreen(Rect outRect) {
5428        if (mAttachInfo == null) {
5429            return;
5430        }
5431
5432        RectF position = mAttachInfo.mTmpTransformRect;
5433        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5434
5435        if (!hasIdentityMatrix()) {
5436            getMatrix().mapRect(position);
5437        }
5438
5439        position.offset(mLeft, mTop);
5440
5441        ViewParent parent = mParent;
5442        while (parent instanceof View) {
5443            View parentView = (View) parent;
5444
5445            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5446
5447            if (!parentView.hasIdentityMatrix()) {
5448                parentView.getMatrix().mapRect(position);
5449            }
5450
5451            position.offset(parentView.mLeft, parentView.mTop);
5452
5453            parent = parentView.mParent;
5454        }
5455
5456        if (parent instanceof ViewRootImpl) {
5457            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5458            position.offset(0, -viewRootImpl.mCurScrollY);
5459        }
5460
5461        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5462
5463        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5464                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5465    }
5466
5467    /**
5468     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5469     *
5470     * Note: Called from the default {@link AccessibilityDelegate}.
5471     */
5472    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5473        Rect bounds = mAttachInfo.mTmpInvalRect;
5474
5475        getDrawingRect(bounds);
5476        info.setBoundsInParent(bounds);
5477
5478        getBoundsOnScreen(bounds);
5479        info.setBoundsInScreen(bounds);
5480
5481        ViewParent parent = getParentForAccessibility();
5482        if (parent instanceof View) {
5483            info.setParent((View) parent);
5484        }
5485
5486        if (mID != View.NO_ID) {
5487            View rootView = getRootView();
5488            if (rootView == null) {
5489                rootView = this;
5490            }
5491            View label = rootView.findLabelForView(this, mID);
5492            if (label != null) {
5493                info.setLabeledBy(label);
5494            }
5495
5496            if ((mAttachInfo.mAccessibilityFetchFlags
5497                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5498                    && Resources.resourceHasPackage(mID)) {
5499                try {
5500                    String viewId = getResources().getResourceName(mID);
5501                    info.setViewIdResourceName(viewId);
5502                } catch (Resources.NotFoundException nfe) {
5503                    /* ignore */
5504                }
5505            }
5506        }
5507
5508        if (mLabelForId != View.NO_ID) {
5509            View rootView = getRootView();
5510            if (rootView == null) {
5511                rootView = this;
5512            }
5513            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5514            if (labeled != null) {
5515                info.setLabelFor(labeled);
5516            }
5517        }
5518
5519        info.setVisibleToUser(isVisibleToUser());
5520
5521        info.setPackageName(mContext.getPackageName());
5522        info.setClassName(View.class.getName());
5523        info.setContentDescription(getContentDescription());
5524
5525        info.setEnabled(isEnabled());
5526        info.setClickable(isClickable());
5527        info.setFocusable(isFocusable());
5528        info.setFocused(isFocused());
5529        info.setAccessibilityFocused(isAccessibilityFocused());
5530        info.setSelected(isSelected());
5531        info.setLongClickable(isLongClickable());
5532        info.setLiveRegion(getAccessibilityLiveRegion());
5533
5534        // TODO: These make sense only if we are in an AdapterView but all
5535        // views can be selected. Maybe from accessibility perspective
5536        // we should report as selectable view in an AdapterView.
5537        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5538        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5539
5540        if (isFocusable()) {
5541            if (isFocused()) {
5542                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5543            } else {
5544                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5545            }
5546        }
5547
5548        if (!isAccessibilityFocused()) {
5549            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5550        } else {
5551            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5552        }
5553
5554        if (isClickable() && isEnabled()) {
5555            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5556        }
5557
5558        if (isLongClickable() && isEnabled()) {
5559            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5560        }
5561
5562        CharSequence text = getIterableTextForAccessibility();
5563        if (text != null && text.length() > 0) {
5564            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5565
5566            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5567            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5568            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5569            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5570                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5571                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5572        }
5573    }
5574
5575    private View findLabelForView(View view, int labeledId) {
5576        if (mMatchLabelForPredicate == null) {
5577            mMatchLabelForPredicate = new MatchLabelForPredicate();
5578        }
5579        mMatchLabelForPredicate.mLabeledId = labeledId;
5580        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5581    }
5582
5583    /**
5584     * Computes whether this view is visible to the user. Such a view is
5585     * attached, visible, all its predecessors are visible, it is not clipped
5586     * entirely by its predecessors, and has an alpha greater than zero.
5587     *
5588     * @return Whether the view is visible on the screen.
5589     *
5590     * @hide
5591     */
5592    protected boolean isVisibleToUser() {
5593        return isVisibleToUser(null);
5594    }
5595
5596    /**
5597     * Computes whether the given portion of this view is visible to the user.
5598     * Such a view is attached, visible, all its predecessors are visible,
5599     * has an alpha greater than zero, and the specified portion is not
5600     * clipped entirely by its predecessors.
5601     *
5602     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5603     *                    <code>null</code>, and the entire view will be tested in this case.
5604     *                    When <code>true</code> is returned by the function, the actual visible
5605     *                    region will be stored in this parameter; that is, if boundInView is fully
5606     *                    contained within the view, no modification will be made, otherwise regions
5607     *                    outside of the visible area of the view will be clipped.
5608     *
5609     * @return Whether the specified portion of the view is visible on the screen.
5610     *
5611     * @hide
5612     */
5613    protected boolean isVisibleToUser(Rect boundInView) {
5614        if (mAttachInfo != null) {
5615            // Attached to invisible window means this view is not visible.
5616            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5617                return false;
5618            }
5619            // An invisible predecessor or one with alpha zero means
5620            // that this view is not visible to the user.
5621            Object current = this;
5622            while (current instanceof View) {
5623                View view = (View) current;
5624                // We have attach info so this view is attached and there is no
5625                // need to check whether we reach to ViewRootImpl on the way up.
5626                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5627                        view.getVisibility() != VISIBLE) {
5628                    return false;
5629                }
5630                current = view.mParent;
5631            }
5632            // Check if the view is entirely covered by its predecessors.
5633            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5634            Point offset = mAttachInfo.mPoint;
5635            if (!getGlobalVisibleRect(visibleRect, offset)) {
5636                return false;
5637            }
5638            // Check if the visible portion intersects the rectangle of interest.
5639            if (boundInView != null) {
5640                visibleRect.offset(-offset.x, -offset.y);
5641                return boundInView.intersect(visibleRect);
5642            }
5643            return true;
5644        }
5645        return false;
5646    }
5647
5648    /**
5649     * Returns the delegate for implementing accessibility support via
5650     * composition. For more details see {@link AccessibilityDelegate}.
5651     *
5652     * @return The delegate, or null if none set.
5653     *
5654     * @hide
5655     */
5656    public AccessibilityDelegate getAccessibilityDelegate() {
5657        return mAccessibilityDelegate;
5658    }
5659
5660    /**
5661     * Sets a delegate for implementing accessibility support via composition as
5662     * opposed to inheritance. The delegate's primary use is for implementing
5663     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5664     *
5665     * @param delegate The delegate instance.
5666     *
5667     * @see AccessibilityDelegate
5668     */
5669    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5670        mAccessibilityDelegate = delegate;
5671    }
5672
5673    /**
5674     * Gets the provider for managing a virtual view hierarchy rooted at this View
5675     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5676     * that explore the window content.
5677     * <p>
5678     * If this method returns an instance, this instance is responsible for managing
5679     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5680     * View including the one representing the View itself. Similarly the returned
5681     * instance is responsible for performing accessibility actions on any virtual
5682     * view or the root view itself.
5683     * </p>
5684     * <p>
5685     * If an {@link AccessibilityDelegate} has been specified via calling
5686     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5687     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5688     * is responsible for handling this call.
5689     * </p>
5690     *
5691     * @return The provider.
5692     *
5693     * @see AccessibilityNodeProvider
5694     */
5695    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5696        if (mAccessibilityDelegate != null) {
5697            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5698        } else {
5699            return null;
5700        }
5701    }
5702
5703    /**
5704     * Gets the unique identifier of this view on the screen for accessibility purposes.
5705     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5706     *
5707     * @return The view accessibility id.
5708     *
5709     * @hide
5710     */
5711    public int getAccessibilityViewId() {
5712        if (mAccessibilityViewId == NO_ID) {
5713            mAccessibilityViewId = sNextAccessibilityViewId++;
5714        }
5715        return mAccessibilityViewId;
5716    }
5717
5718    /**
5719     * Gets the unique identifier of the window in which this View reseides.
5720     *
5721     * @return The window accessibility id.
5722     *
5723     * @hide
5724     */
5725    public int getAccessibilityWindowId() {
5726        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5727    }
5728
5729    /**
5730     * Gets the {@link View} description. It briefly describes the view and is
5731     * primarily used for accessibility support. Set this property to enable
5732     * better accessibility support for your application. This is especially
5733     * true for views that do not have textual representation (For example,
5734     * ImageButton).
5735     *
5736     * @return The content description.
5737     *
5738     * @attr ref android.R.styleable#View_contentDescription
5739     */
5740    @ViewDebug.ExportedProperty(category = "accessibility")
5741    public CharSequence getContentDescription() {
5742        return mContentDescription;
5743    }
5744
5745    /**
5746     * Sets the {@link View} description. It briefly describes the view and is
5747     * primarily used for accessibility support. Set this property to enable
5748     * better accessibility support for your application. This is especially
5749     * true for views that do not have textual representation (For example,
5750     * ImageButton).
5751     *
5752     * @param contentDescription The content description.
5753     *
5754     * @attr ref android.R.styleable#View_contentDescription
5755     */
5756    @RemotableViewMethod
5757    public void setContentDescription(CharSequence contentDescription) {
5758        if (mContentDescription == null) {
5759            if (contentDescription == null) {
5760                return;
5761            }
5762        } else if (mContentDescription.equals(contentDescription)) {
5763            return;
5764        }
5765        mContentDescription = contentDescription;
5766        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5767        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5768            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5769            notifySubtreeAccessibilityStateChangedIfNeeded();
5770        } else {
5771            notifyViewAccessibilityStateChangedIfNeeded(
5772                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5773        }
5774    }
5775
5776    /**
5777     * Gets the id of a view for which this view serves as a label for
5778     * accessibility purposes.
5779     *
5780     * @return The labeled view id.
5781     */
5782    @ViewDebug.ExportedProperty(category = "accessibility")
5783    public int getLabelFor() {
5784        return mLabelForId;
5785    }
5786
5787    /**
5788     * Sets the id of a view for which this view serves as a label for
5789     * accessibility purposes.
5790     *
5791     * @param id The labeled view id.
5792     */
5793    @RemotableViewMethod
5794    public void setLabelFor(int id) {
5795        mLabelForId = id;
5796        if (mLabelForId != View.NO_ID
5797                && mID == View.NO_ID) {
5798            mID = generateViewId();
5799        }
5800    }
5801
5802    /**
5803     * Invoked whenever this view loses focus, either by losing window focus or by losing
5804     * focus within its window. This method can be used to clear any state tied to the
5805     * focus. For instance, if a button is held pressed with the trackball and the window
5806     * loses focus, this method can be used to cancel the press.
5807     *
5808     * Subclasses of View overriding this method should always call super.onFocusLost().
5809     *
5810     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5811     * @see #onWindowFocusChanged(boolean)
5812     *
5813     * @hide pending API council approval
5814     */
5815    protected void onFocusLost() {
5816        resetPressedState();
5817    }
5818
5819    private void resetPressedState() {
5820        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5821            return;
5822        }
5823
5824        if (isPressed()) {
5825            setPressed(false);
5826
5827            if (!mHasPerformedLongPress) {
5828                removeLongPressCallback();
5829            }
5830        }
5831    }
5832
5833    /**
5834     * Returns true if this view has focus
5835     *
5836     * @return True if this view has focus, false otherwise.
5837     */
5838    @ViewDebug.ExportedProperty(category = "focus")
5839    public boolean isFocused() {
5840        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5841    }
5842
5843    /**
5844     * Find the view in the hierarchy rooted at this view that currently has
5845     * focus.
5846     *
5847     * @return The view that currently has focus, or null if no focused view can
5848     *         be found.
5849     */
5850    public View findFocus() {
5851        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5852    }
5853
5854    /**
5855     * Indicates whether this view is one of the set of scrollable containers in
5856     * its window.
5857     *
5858     * @return whether this view is one of the set of scrollable containers in
5859     * its window
5860     *
5861     * @attr ref android.R.styleable#View_isScrollContainer
5862     */
5863    public boolean isScrollContainer() {
5864        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5865    }
5866
5867    /**
5868     * Change whether this view is one of the set of scrollable containers in
5869     * its window.  This will be used to determine whether the window can
5870     * resize or must pan when a soft input area is open -- scrollable
5871     * containers allow the window to use resize mode since the container
5872     * will appropriately shrink.
5873     *
5874     * @attr ref android.R.styleable#View_isScrollContainer
5875     */
5876    public void setScrollContainer(boolean isScrollContainer) {
5877        if (isScrollContainer) {
5878            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5879                mAttachInfo.mScrollContainers.add(this);
5880                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5881            }
5882            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5883        } else {
5884            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5885                mAttachInfo.mScrollContainers.remove(this);
5886            }
5887            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5888        }
5889    }
5890
5891    /**
5892     * Returns the quality of the drawing cache.
5893     *
5894     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5895     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5896     *
5897     * @see #setDrawingCacheQuality(int)
5898     * @see #setDrawingCacheEnabled(boolean)
5899     * @see #isDrawingCacheEnabled()
5900     *
5901     * @attr ref android.R.styleable#View_drawingCacheQuality
5902     */
5903    @DrawingCacheQuality
5904    public int getDrawingCacheQuality() {
5905        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5906    }
5907
5908    /**
5909     * Set the drawing cache quality of this view. This value is used only when the
5910     * drawing cache is enabled
5911     *
5912     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5913     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5914     *
5915     * @see #getDrawingCacheQuality()
5916     * @see #setDrawingCacheEnabled(boolean)
5917     * @see #isDrawingCacheEnabled()
5918     *
5919     * @attr ref android.R.styleable#View_drawingCacheQuality
5920     */
5921    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5922        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5923    }
5924
5925    /**
5926     * Returns whether the screen should remain on, corresponding to the current
5927     * value of {@link #KEEP_SCREEN_ON}.
5928     *
5929     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5930     *
5931     * @see #setKeepScreenOn(boolean)
5932     *
5933     * @attr ref android.R.styleable#View_keepScreenOn
5934     */
5935    public boolean getKeepScreenOn() {
5936        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5937    }
5938
5939    /**
5940     * Controls whether the screen should remain on, modifying the
5941     * value of {@link #KEEP_SCREEN_ON}.
5942     *
5943     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5944     *
5945     * @see #getKeepScreenOn()
5946     *
5947     * @attr ref android.R.styleable#View_keepScreenOn
5948     */
5949    public void setKeepScreenOn(boolean keepScreenOn) {
5950        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5951    }
5952
5953    /**
5954     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5955     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5956     *
5957     * @attr ref android.R.styleable#View_nextFocusLeft
5958     */
5959    public int getNextFocusLeftId() {
5960        return mNextFocusLeftId;
5961    }
5962
5963    /**
5964     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5965     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5966     * decide automatically.
5967     *
5968     * @attr ref android.R.styleable#View_nextFocusLeft
5969     */
5970    public void setNextFocusLeftId(int nextFocusLeftId) {
5971        mNextFocusLeftId = nextFocusLeftId;
5972    }
5973
5974    /**
5975     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5976     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5977     *
5978     * @attr ref android.R.styleable#View_nextFocusRight
5979     */
5980    public int getNextFocusRightId() {
5981        return mNextFocusRightId;
5982    }
5983
5984    /**
5985     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5986     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5987     * decide automatically.
5988     *
5989     * @attr ref android.R.styleable#View_nextFocusRight
5990     */
5991    public void setNextFocusRightId(int nextFocusRightId) {
5992        mNextFocusRightId = nextFocusRightId;
5993    }
5994
5995    /**
5996     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5997     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5998     *
5999     * @attr ref android.R.styleable#View_nextFocusUp
6000     */
6001    public int getNextFocusUpId() {
6002        return mNextFocusUpId;
6003    }
6004
6005    /**
6006     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6007     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6008     * decide automatically.
6009     *
6010     * @attr ref android.R.styleable#View_nextFocusUp
6011     */
6012    public void setNextFocusUpId(int nextFocusUpId) {
6013        mNextFocusUpId = nextFocusUpId;
6014    }
6015
6016    /**
6017     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6018     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6019     *
6020     * @attr ref android.R.styleable#View_nextFocusDown
6021     */
6022    public int getNextFocusDownId() {
6023        return mNextFocusDownId;
6024    }
6025
6026    /**
6027     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6028     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6029     * decide automatically.
6030     *
6031     * @attr ref android.R.styleable#View_nextFocusDown
6032     */
6033    public void setNextFocusDownId(int nextFocusDownId) {
6034        mNextFocusDownId = nextFocusDownId;
6035    }
6036
6037    /**
6038     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6039     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6040     *
6041     * @attr ref android.R.styleable#View_nextFocusForward
6042     */
6043    public int getNextFocusForwardId() {
6044        return mNextFocusForwardId;
6045    }
6046
6047    /**
6048     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6049     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6050     * decide automatically.
6051     *
6052     * @attr ref android.R.styleable#View_nextFocusForward
6053     */
6054    public void setNextFocusForwardId(int nextFocusForwardId) {
6055        mNextFocusForwardId = nextFocusForwardId;
6056    }
6057
6058    /**
6059     * Returns the visibility of this view and all of its ancestors
6060     *
6061     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6062     */
6063    public boolean isShown() {
6064        View current = this;
6065        //noinspection ConstantConditions
6066        do {
6067            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6068                return false;
6069            }
6070            ViewParent parent = current.mParent;
6071            if (parent == null) {
6072                return false; // We are not attached to the view root
6073            }
6074            if (!(parent instanceof View)) {
6075                return true;
6076            }
6077            current = (View) parent;
6078        } while (current != null);
6079
6080        return false;
6081    }
6082
6083    /**
6084     * Called by the view hierarchy when the content insets for a window have
6085     * changed, to allow it to adjust its content to fit within those windows.
6086     * The content insets tell you the space that the status bar, input method,
6087     * and other system windows infringe on the application's window.
6088     *
6089     * <p>You do not normally need to deal with this function, since the default
6090     * window decoration given to applications takes care of applying it to the
6091     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6092     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6093     * and your content can be placed under those system elements.  You can then
6094     * use this method within your view hierarchy if you have parts of your UI
6095     * which you would like to ensure are not being covered.
6096     *
6097     * <p>The default implementation of this method simply applies the content
6098     * insets to the view's padding, consuming that content (modifying the
6099     * insets to be 0), and returning true.  This behavior is off by default, but can
6100     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6101     *
6102     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6103     * insets object is propagated down the hierarchy, so any changes made to it will
6104     * be seen by all following views (including potentially ones above in
6105     * the hierarchy since this is a depth-first traversal).  The first view
6106     * that returns true will abort the entire traversal.
6107     *
6108     * <p>The default implementation works well for a situation where it is
6109     * used with a container that covers the entire window, allowing it to
6110     * apply the appropriate insets to its content on all edges.  If you need
6111     * a more complicated layout (such as two different views fitting system
6112     * windows, one on the top of the window, and one on the bottom),
6113     * you can override the method and handle the insets however you would like.
6114     * Note that the insets provided by the framework are always relative to the
6115     * far edges of the window, not accounting for the location of the called view
6116     * within that window.  (In fact when this method is called you do not yet know
6117     * where the layout will place the view, as it is done before layout happens.)
6118     *
6119     * <p>Note: unlike many View methods, there is no dispatch phase to this
6120     * call.  If you are overriding it in a ViewGroup and want to allow the
6121     * call to continue to your children, you must be sure to call the super
6122     * implementation.
6123     *
6124     * <p>Here is a sample layout that makes use of fitting system windows
6125     * to have controls for a video view placed inside of the window decorations
6126     * that it hides and shows.  This can be used with code like the second
6127     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6128     *
6129     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6130     *
6131     * @param insets Current content insets of the window.  Prior to
6132     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6133     * the insets or else you and Android will be unhappy.
6134     *
6135     * @return {@code true} if this view applied the insets and it should not
6136     * continue propagating further down the hierarchy, {@code false} otherwise.
6137     * @see #getFitsSystemWindows()
6138     * @see #setFitsSystemWindows(boolean)
6139     * @see #setSystemUiVisibility(int)
6140     *
6141     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6142     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6143     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6144     * to implement handling their own insets.
6145     */
6146    protected boolean fitSystemWindows(Rect insets) {
6147        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6148            // If we're not in the process of dispatching the newer apply insets call,
6149            // that means we're not in the compatibility path. Dispatch into the newer
6150            // apply insets path and take things from there.
6151            try {
6152                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6153                return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets();
6154            } finally {
6155                mPrivateFlags3 &= PFLAG3_FITTING_SYSTEM_WINDOWS;
6156            }
6157        } else {
6158            // We're being called from the newer apply insets path.
6159            // Perform the standard fallback behavior.
6160            return fitSystemWindowsInt(insets);
6161        }
6162    }
6163
6164    private boolean fitSystemWindowsInt(Rect insets) {
6165        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6166            mUserPaddingStart = UNDEFINED_PADDING;
6167            mUserPaddingEnd = UNDEFINED_PADDING;
6168            Rect localInsets = sThreadLocal.get();
6169            if (localInsets == null) {
6170                localInsets = new Rect();
6171                sThreadLocal.set(localInsets);
6172            }
6173            boolean res = computeFitSystemWindows(insets, localInsets);
6174            mUserPaddingLeftInitial = localInsets.left;
6175            mUserPaddingRightInitial = localInsets.right;
6176            internalSetPadding(localInsets.left, localInsets.top,
6177                    localInsets.right, localInsets.bottom);
6178            return res;
6179        }
6180        return false;
6181    }
6182
6183    /**
6184     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6185     *
6186     * <p>This method should be overridden by views that wish to apply a policy different from or
6187     * in addition to the default behavior. Clients that wish to force a view subtree
6188     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6189     *
6190     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6191     * it will be called during dispatch instead of this method. The listener may optionally
6192     * call this method from its own implementation if it wishes to apply the view's default
6193     * insets policy in addition to its own.</p>
6194     *
6195     * <p>Implementations of this method should either return the insets parameter unchanged
6196     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6197     * that this view applied itself. This allows new inset types added in future platform
6198     * versions to pass through existing implementations unchanged without being erroneously
6199     * consumed.</p>
6200     *
6201     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6202     * property is set then the view will consume the system window insets and apply them
6203     * as padding for the view.</p>
6204     *
6205     * @param insets Insets to apply
6206     * @return The supplied insets with any applied insets consumed
6207     */
6208    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6209        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6210            // We weren't called from within a direct call to fitSystemWindows,
6211            // call into it as a fallback in case we're in a class that overrides it
6212            // and has logic to perform.
6213            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6214                return insets.cloneWithSystemWindowInsetsConsumed();
6215            }
6216        } else {
6217            // We were called from within a direct call to fitSystemWindows.
6218            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6219                return insets.cloneWithSystemWindowInsetsConsumed();
6220            }
6221        }
6222        return insets;
6223    }
6224
6225    /**
6226     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6227     * window insets to this view. The listener's
6228     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6229     * method will be called instead of the view's
6230     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6231     *
6232     * @param listener Listener to set
6233     *
6234     * @see #onApplyWindowInsets(WindowInsets)
6235     */
6236    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6237        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6238    }
6239
6240    /**
6241     * Request to apply the given window insets to this view or another view in its subtree.
6242     *
6243     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6244     * obscured by window decorations or overlays. This can include the status and navigation bars,
6245     * action bars, input methods and more. New inset categories may be added in the future.
6246     * The method returns the insets provided minus any that were applied by this view or its
6247     * children.</p>
6248     *
6249     * <p>Clients wishing to provide custom behavior should override the
6250     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6251     * {@link OnApplyWindowInsetsListener} via the
6252     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6253     * method.</p>
6254     *
6255     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6256     * </p>
6257     *
6258     * @param insets Insets to apply
6259     * @return The provided insets minus the insets that were consumed
6260     */
6261    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6262        try {
6263            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6264            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6265                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6266            } else {
6267                return onApplyWindowInsets(insets);
6268            }
6269        } finally {
6270            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6271        }
6272    }
6273
6274    /**
6275     * @hide Compute the insets that should be consumed by this view and the ones
6276     * that should propagate to those under it.
6277     */
6278    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6279        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6280                || mAttachInfo == null
6281                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6282                        && !mAttachInfo.mOverscanRequested)) {
6283            outLocalInsets.set(inoutInsets);
6284            inoutInsets.set(0, 0, 0, 0);
6285            return true;
6286        } else {
6287            // The application wants to take care of fitting system window for
6288            // the content...  however we still need to take care of any overscan here.
6289            final Rect overscan = mAttachInfo.mOverscanInsets;
6290            outLocalInsets.set(overscan);
6291            inoutInsets.left -= overscan.left;
6292            inoutInsets.top -= overscan.top;
6293            inoutInsets.right -= overscan.right;
6294            inoutInsets.bottom -= overscan.bottom;
6295            return false;
6296        }
6297    }
6298
6299    /**
6300     * Sets whether or not this view should account for system screen decorations
6301     * such as the status bar and inset its content; that is, controlling whether
6302     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6303     * executed.  See that method for more details.
6304     *
6305     * <p>Note that if you are providing your own implementation of
6306     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6307     * flag to true -- your implementation will be overriding the default
6308     * implementation that checks this flag.
6309     *
6310     * @param fitSystemWindows If true, then the default implementation of
6311     * {@link #fitSystemWindows(Rect)} will be executed.
6312     *
6313     * @attr ref android.R.styleable#View_fitsSystemWindows
6314     * @see #getFitsSystemWindows()
6315     * @see #fitSystemWindows(Rect)
6316     * @see #setSystemUiVisibility(int)
6317     */
6318    public void setFitsSystemWindows(boolean fitSystemWindows) {
6319        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6320    }
6321
6322    /**
6323     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6324     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6325     * will be executed.
6326     *
6327     * @return {@code true} if the default implementation of
6328     * {@link #fitSystemWindows(Rect)} will be executed.
6329     *
6330     * @attr ref android.R.styleable#View_fitsSystemWindows
6331     * @see #setFitsSystemWindows(boolean)
6332     * @see #fitSystemWindows(Rect)
6333     * @see #setSystemUiVisibility(int)
6334     */
6335    public boolean getFitsSystemWindows() {
6336        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6337    }
6338
6339    /** @hide */
6340    public boolean fitsSystemWindows() {
6341        return getFitsSystemWindows();
6342    }
6343
6344    /**
6345     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6346     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6347     */
6348    public void requestFitSystemWindows() {
6349        if (mParent != null) {
6350            mParent.requestFitSystemWindows();
6351        }
6352    }
6353
6354    /**
6355     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6356     */
6357    public void requestApplyInsets() {
6358        requestFitSystemWindows();
6359    }
6360
6361    /**
6362     * For use by PhoneWindow to make its own system window fitting optional.
6363     * @hide
6364     */
6365    public void makeOptionalFitsSystemWindows() {
6366        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6367    }
6368
6369    /**
6370     * Returns the visibility status for this view.
6371     *
6372     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6373     * @attr ref android.R.styleable#View_visibility
6374     */
6375    @ViewDebug.ExportedProperty(mapping = {
6376        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6377        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6378        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6379    })
6380    @Visibility
6381    public int getVisibility() {
6382        return mViewFlags & VISIBILITY_MASK;
6383    }
6384
6385    /**
6386     * Set the enabled state of this view.
6387     *
6388     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6389     * @attr ref android.R.styleable#View_visibility
6390     */
6391    @RemotableViewMethod
6392    public void setVisibility(@Visibility int visibility) {
6393        setFlags(visibility, VISIBILITY_MASK);
6394        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6395    }
6396
6397    /**
6398     * Returns the enabled status for this view. The interpretation of the
6399     * enabled state varies by subclass.
6400     *
6401     * @return True if this view is enabled, false otherwise.
6402     */
6403    @ViewDebug.ExportedProperty
6404    public boolean isEnabled() {
6405        return (mViewFlags & ENABLED_MASK) == ENABLED;
6406    }
6407
6408    /**
6409     * Set the enabled state of this view. The interpretation of the enabled
6410     * state varies by subclass.
6411     *
6412     * @param enabled True if this view is enabled, false otherwise.
6413     */
6414    @RemotableViewMethod
6415    public void setEnabled(boolean enabled) {
6416        if (enabled == isEnabled()) return;
6417
6418        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6419
6420        /*
6421         * The View most likely has to change its appearance, so refresh
6422         * the drawable state.
6423         */
6424        refreshDrawableState();
6425
6426        // Invalidate too, since the default behavior for views is to be
6427        // be drawn at 50% alpha rather than to change the drawable.
6428        invalidate(true);
6429
6430        if (!enabled) {
6431            cancelPendingInputEvents();
6432        }
6433    }
6434
6435    /**
6436     * Set whether this view can receive the focus.
6437     *
6438     * Setting this to false will also ensure that this view is not focusable
6439     * in touch mode.
6440     *
6441     * @param focusable If true, this view can receive the focus.
6442     *
6443     * @see #setFocusableInTouchMode(boolean)
6444     * @attr ref android.R.styleable#View_focusable
6445     */
6446    public void setFocusable(boolean focusable) {
6447        if (!focusable) {
6448            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6449        }
6450        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6451    }
6452
6453    /**
6454     * Set whether this view can receive focus while in touch mode.
6455     *
6456     * Setting this to true will also ensure that this view is focusable.
6457     *
6458     * @param focusableInTouchMode If true, this view can receive the focus while
6459     *   in touch mode.
6460     *
6461     * @see #setFocusable(boolean)
6462     * @attr ref android.R.styleable#View_focusableInTouchMode
6463     */
6464    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6465        // Focusable in touch mode should always be set before the focusable flag
6466        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6467        // which, in touch mode, will not successfully request focus on this view
6468        // because the focusable in touch mode flag is not set
6469        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6470        if (focusableInTouchMode) {
6471            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6472        }
6473    }
6474
6475    /**
6476     * Set whether this view should have sound effects enabled for events such as
6477     * clicking and touching.
6478     *
6479     * <p>You may wish to disable sound effects for a view if you already play sounds,
6480     * for instance, a dial key that plays dtmf tones.
6481     *
6482     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6483     * @see #isSoundEffectsEnabled()
6484     * @see #playSoundEffect(int)
6485     * @attr ref android.R.styleable#View_soundEffectsEnabled
6486     */
6487    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6488        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6489    }
6490
6491    /**
6492     * @return whether this view should have sound effects enabled for events such as
6493     *     clicking and touching.
6494     *
6495     * @see #setSoundEffectsEnabled(boolean)
6496     * @see #playSoundEffect(int)
6497     * @attr ref android.R.styleable#View_soundEffectsEnabled
6498     */
6499    @ViewDebug.ExportedProperty
6500    public boolean isSoundEffectsEnabled() {
6501        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6502    }
6503
6504    /**
6505     * Set whether this view should have haptic feedback for events such as
6506     * long presses.
6507     *
6508     * <p>You may wish to disable haptic feedback if your view already controls
6509     * its own haptic feedback.
6510     *
6511     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6512     * @see #isHapticFeedbackEnabled()
6513     * @see #performHapticFeedback(int)
6514     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6515     */
6516    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6517        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6518    }
6519
6520    /**
6521     * @return whether this view should have haptic feedback enabled for events
6522     * long presses.
6523     *
6524     * @see #setHapticFeedbackEnabled(boolean)
6525     * @see #performHapticFeedback(int)
6526     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6527     */
6528    @ViewDebug.ExportedProperty
6529    public boolean isHapticFeedbackEnabled() {
6530        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6531    }
6532
6533    /**
6534     * Returns the layout direction for this view.
6535     *
6536     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6537     *   {@link #LAYOUT_DIRECTION_RTL},
6538     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6539     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6540     *
6541     * @attr ref android.R.styleable#View_layoutDirection
6542     *
6543     * @hide
6544     */
6545    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6546        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6547        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6548        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6549        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6550    })
6551    @LayoutDir
6552    public int getRawLayoutDirection() {
6553        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6554    }
6555
6556    /**
6557     * Set the layout direction for this view. This will propagate a reset of layout direction
6558     * resolution to the view's children and resolve layout direction for this view.
6559     *
6560     * @param layoutDirection the layout direction to set. Should be one of:
6561     *
6562     * {@link #LAYOUT_DIRECTION_LTR},
6563     * {@link #LAYOUT_DIRECTION_RTL},
6564     * {@link #LAYOUT_DIRECTION_INHERIT},
6565     * {@link #LAYOUT_DIRECTION_LOCALE}.
6566     *
6567     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6568     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6569     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6570     *
6571     * @attr ref android.R.styleable#View_layoutDirection
6572     */
6573    @RemotableViewMethod
6574    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6575        if (getRawLayoutDirection() != layoutDirection) {
6576            // Reset the current layout direction and the resolved one
6577            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6578            resetRtlProperties();
6579            // Set the new layout direction (filtered)
6580            mPrivateFlags2 |=
6581                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6582            // We need to resolve all RTL properties as they all depend on layout direction
6583            resolveRtlPropertiesIfNeeded();
6584            requestLayout();
6585            invalidate(true);
6586        }
6587    }
6588
6589    /**
6590     * Returns the resolved layout direction for this view.
6591     *
6592     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6593     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6594     *
6595     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6596     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6597     *
6598     * @attr ref android.R.styleable#View_layoutDirection
6599     */
6600    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6601        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6602        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6603    })
6604    @ResolvedLayoutDir
6605    public int getLayoutDirection() {
6606        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6607        if (targetSdkVersion < JELLY_BEAN_MR1) {
6608            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6609            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6610        }
6611        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6612                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6613    }
6614
6615    /**
6616     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6617     * layout attribute and/or the inherited value from the parent
6618     *
6619     * @return true if the layout is right-to-left.
6620     *
6621     * @hide
6622     */
6623    @ViewDebug.ExportedProperty(category = "layout")
6624    public boolean isLayoutRtl() {
6625        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6626    }
6627
6628    /**
6629     * Indicates whether the view is currently tracking transient state that the
6630     * app should not need to concern itself with saving and restoring, but that
6631     * the framework should take special note to preserve when possible.
6632     *
6633     * <p>A view with transient state cannot be trivially rebound from an external
6634     * data source, such as an adapter binding item views in a list. This may be
6635     * because the view is performing an animation, tracking user selection
6636     * of content, or similar.</p>
6637     *
6638     * @return true if the view has transient state
6639     */
6640    @ViewDebug.ExportedProperty(category = "layout")
6641    public boolean hasTransientState() {
6642        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6643    }
6644
6645    /**
6646     * Set whether this view is currently tracking transient state that the
6647     * framework should attempt to preserve when possible. This flag is reference counted,
6648     * so every call to setHasTransientState(true) should be paired with a later call
6649     * to setHasTransientState(false).
6650     *
6651     * <p>A view with transient state cannot be trivially rebound from an external
6652     * data source, such as an adapter binding item views in a list. This may be
6653     * because the view is performing an animation, tracking user selection
6654     * of content, or similar.</p>
6655     *
6656     * @param hasTransientState true if this view has transient state
6657     */
6658    public void setHasTransientState(boolean hasTransientState) {
6659        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6660                mTransientStateCount - 1;
6661        if (mTransientStateCount < 0) {
6662            mTransientStateCount = 0;
6663            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6664                    "unmatched pair of setHasTransientState calls");
6665        } else if ((hasTransientState && mTransientStateCount == 1) ||
6666                (!hasTransientState && mTransientStateCount == 0)) {
6667            // update flag if we've just incremented up from 0 or decremented down to 0
6668            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6669                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6670            if (mParent != null) {
6671                try {
6672                    mParent.childHasTransientStateChanged(this, hasTransientState);
6673                } catch (AbstractMethodError e) {
6674                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6675                            " does not fully implement ViewParent", e);
6676                }
6677            }
6678        }
6679    }
6680
6681    /**
6682     * Returns true if this view is currently attached to a window.
6683     */
6684    public boolean isAttachedToWindow() {
6685        return mAttachInfo != null;
6686    }
6687
6688    /**
6689     * Returns true if this view has been through at least one layout since it
6690     * was last attached to or detached from a window.
6691     */
6692    public boolean isLaidOut() {
6693        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6694    }
6695
6696    /**
6697     * If this view doesn't do any drawing on its own, set this flag to
6698     * allow further optimizations. By default, this flag is not set on
6699     * View, but could be set on some View subclasses such as ViewGroup.
6700     *
6701     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6702     * you should clear this flag.
6703     *
6704     * @param willNotDraw whether or not this View draw on its own
6705     */
6706    public void setWillNotDraw(boolean willNotDraw) {
6707        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6708    }
6709
6710    /**
6711     * Returns whether or not this View draws on its own.
6712     *
6713     * @return true if this view has nothing to draw, false otherwise
6714     */
6715    @ViewDebug.ExportedProperty(category = "drawing")
6716    public boolean willNotDraw() {
6717        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6718    }
6719
6720    /**
6721     * When a View's drawing cache is enabled, drawing is redirected to an
6722     * offscreen bitmap. Some views, like an ImageView, must be able to
6723     * bypass this mechanism if they already draw a single bitmap, to avoid
6724     * unnecessary usage of the memory.
6725     *
6726     * @param willNotCacheDrawing true if this view does not cache its
6727     *        drawing, false otherwise
6728     */
6729    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6730        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6731    }
6732
6733    /**
6734     * Returns whether or not this View can cache its drawing or not.
6735     *
6736     * @return true if this view does not cache its drawing, false otherwise
6737     */
6738    @ViewDebug.ExportedProperty(category = "drawing")
6739    public boolean willNotCacheDrawing() {
6740        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6741    }
6742
6743    /**
6744     * Indicates whether this view reacts to click events or not.
6745     *
6746     * @return true if the view is clickable, false otherwise
6747     *
6748     * @see #setClickable(boolean)
6749     * @attr ref android.R.styleable#View_clickable
6750     */
6751    @ViewDebug.ExportedProperty
6752    public boolean isClickable() {
6753        return (mViewFlags & CLICKABLE) == CLICKABLE;
6754    }
6755
6756    /**
6757     * Enables or disables click events for this view. When a view
6758     * is clickable it will change its state to "pressed" on every click.
6759     * Subclasses should set the view clickable to visually react to
6760     * user's clicks.
6761     *
6762     * @param clickable true to make the view clickable, false otherwise
6763     *
6764     * @see #isClickable()
6765     * @attr ref android.R.styleable#View_clickable
6766     */
6767    public void setClickable(boolean clickable) {
6768        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6769    }
6770
6771    /**
6772     * Indicates whether this view reacts to long click events or not.
6773     *
6774     * @return true if the view is long clickable, false otherwise
6775     *
6776     * @see #setLongClickable(boolean)
6777     * @attr ref android.R.styleable#View_longClickable
6778     */
6779    public boolean isLongClickable() {
6780        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6781    }
6782
6783    /**
6784     * Enables or disables long click events for this view. When a view is long
6785     * clickable it reacts to the user holding down the button for a longer
6786     * duration than a tap. This event can either launch the listener or a
6787     * context menu.
6788     *
6789     * @param longClickable true to make the view long clickable, false otherwise
6790     * @see #isLongClickable()
6791     * @attr ref android.R.styleable#View_longClickable
6792     */
6793    public void setLongClickable(boolean longClickable) {
6794        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6795    }
6796
6797    /**
6798     * Sets the pressed state for this view.
6799     *
6800     * @see #isClickable()
6801     * @see #setClickable(boolean)
6802     *
6803     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6804     *        the View's internal state from a previously set "pressed" state.
6805     */
6806    public void setPressed(boolean pressed) {
6807        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6808
6809        if (pressed) {
6810            mPrivateFlags |= PFLAG_PRESSED;
6811        } else {
6812            mPrivateFlags &= ~PFLAG_PRESSED;
6813        }
6814
6815        if (needsRefresh) {
6816            refreshDrawableState();
6817        }
6818        dispatchSetPressed(pressed);
6819    }
6820
6821    /**
6822     * Dispatch setPressed to all of this View's children.
6823     *
6824     * @see #setPressed(boolean)
6825     *
6826     * @param pressed The new pressed state
6827     */
6828    protected void dispatchSetPressed(boolean pressed) {
6829    }
6830
6831    /**
6832     * Indicates whether the view is currently in pressed state. Unless
6833     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6834     * the pressed state.
6835     *
6836     * @see #setPressed(boolean)
6837     * @see #isClickable()
6838     * @see #setClickable(boolean)
6839     *
6840     * @return true if the view is currently pressed, false otherwise
6841     */
6842    public boolean isPressed() {
6843        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6844    }
6845
6846    /**
6847     * Indicates whether this view will save its state (that is,
6848     * whether its {@link #onSaveInstanceState} method will be called).
6849     *
6850     * @return Returns true if the view state saving is enabled, else false.
6851     *
6852     * @see #setSaveEnabled(boolean)
6853     * @attr ref android.R.styleable#View_saveEnabled
6854     */
6855    public boolean isSaveEnabled() {
6856        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6857    }
6858
6859    /**
6860     * Controls whether the saving of this view's state is
6861     * enabled (that is, whether its {@link #onSaveInstanceState} method
6862     * will be called).  Note that even if freezing is enabled, the
6863     * view still must have an id assigned to it (via {@link #setId(int)})
6864     * for its state to be saved.  This flag can only disable the
6865     * saving of this view; any child views may still have their state saved.
6866     *
6867     * @param enabled Set to false to <em>disable</em> state saving, or true
6868     * (the default) to allow it.
6869     *
6870     * @see #isSaveEnabled()
6871     * @see #setId(int)
6872     * @see #onSaveInstanceState()
6873     * @attr ref android.R.styleable#View_saveEnabled
6874     */
6875    public void setSaveEnabled(boolean enabled) {
6876        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6877    }
6878
6879    /**
6880     * Gets whether the framework should discard touches when the view's
6881     * window is obscured by another visible window.
6882     * Refer to the {@link View} security documentation for more details.
6883     *
6884     * @return True if touch filtering is enabled.
6885     *
6886     * @see #setFilterTouchesWhenObscured(boolean)
6887     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6888     */
6889    @ViewDebug.ExportedProperty
6890    public boolean getFilterTouchesWhenObscured() {
6891        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6892    }
6893
6894    /**
6895     * Sets whether the framework should discard touches when the view's
6896     * window is obscured by another visible window.
6897     * Refer to the {@link View} security documentation for more details.
6898     *
6899     * @param enabled True if touch filtering should be enabled.
6900     *
6901     * @see #getFilterTouchesWhenObscured
6902     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6903     */
6904    public void setFilterTouchesWhenObscured(boolean enabled) {
6905        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6906                FILTER_TOUCHES_WHEN_OBSCURED);
6907    }
6908
6909    /**
6910     * Indicates whether the entire hierarchy under this view will save its
6911     * state when a state saving traversal occurs from its parent.  The default
6912     * is true; if false, these views will not be saved unless
6913     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6914     *
6915     * @return Returns true if the view state saving from parent is enabled, else false.
6916     *
6917     * @see #setSaveFromParentEnabled(boolean)
6918     */
6919    public boolean isSaveFromParentEnabled() {
6920        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6921    }
6922
6923    /**
6924     * Controls whether the entire hierarchy under this view will save its
6925     * state when a state saving traversal occurs from its parent.  The default
6926     * is true; if false, these views will not be saved unless
6927     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6928     *
6929     * @param enabled Set to false to <em>disable</em> state saving, or true
6930     * (the default) to allow it.
6931     *
6932     * @see #isSaveFromParentEnabled()
6933     * @see #setId(int)
6934     * @see #onSaveInstanceState()
6935     */
6936    public void setSaveFromParentEnabled(boolean enabled) {
6937        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6938    }
6939
6940
6941    /**
6942     * Returns whether this View is able to take focus.
6943     *
6944     * @return True if this view can take focus, or false otherwise.
6945     * @attr ref android.R.styleable#View_focusable
6946     */
6947    @ViewDebug.ExportedProperty(category = "focus")
6948    public final boolean isFocusable() {
6949        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6950    }
6951
6952    /**
6953     * When a view is focusable, it may not want to take focus when in touch mode.
6954     * For example, a button would like focus when the user is navigating via a D-pad
6955     * so that the user can click on it, but once the user starts touching the screen,
6956     * the button shouldn't take focus
6957     * @return Whether the view is focusable in touch mode.
6958     * @attr ref android.R.styleable#View_focusableInTouchMode
6959     */
6960    @ViewDebug.ExportedProperty
6961    public final boolean isFocusableInTouchMode() {
6962        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6963    }
6964
6965    /**
6966     * Find the nearest view in the specified direction that can take focus.
6967     * This does not actually give focus to that view.
6968     *
6969     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6970     *
6971     * @return The nearest focusable in the specified direction, or null if none
6972     *         can be found.
6973     */
6974    public View focusSearch(@FocusRealDirection int direction) {
6975        if (mParent != null) {
6976            return mParent.focusSearch(this, direction);
6977        } else {
6978            return null;
6979        }
6980    }
6981
6982    /**
6983     * This method is the last chance for the focused view and its ancestors to
6984     * respond to an arrow key. This is called when the focused view did not
6985     * consume the key internally, nor could the view system find a new view in
6986     * the requested direction to give focus to.
6987     *
6988     * @param focused The currently focused view.
6989     * @param direction The direction focus wants to move. One of FOCUS_UP,
6990     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6991     * @return True if the this view consumed this unhandled move.
6992     */
6993    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6994        return false;
6995    }
6996
6997    /**
6998     * If a user manually specified the next view id for a particular direction,
6999     * use the root to look up the view.
7000     * @param root The root view of the hierarchy containing this view.
7001     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7002     * or FOCUS_BACKWARD.
7003     * @return The user specified next view, or null if there is none.
7004     */
7005    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7006        switch (direction) {
7007            case FOCUS_LEFT:
7008                if (mNextFocusLeftId == View.NO_ID) return null;
7009                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7010            case FOCUS_RIGHT:
7011                if (mNextFocusRightId == View.NO_ID) return null;
7012                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7013            case FOCUS_UP:
7014                if (mNextFocusUpId == View.NO_ID) return null;
7015                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7016            case FOCUS_DOWN:
7017                if (mNextFocusDownId == View.NO_ID) return null;
7018                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7019            case FOCUS_FORWARD:
7020                if (mNextFocusForwardId == View.NO_ID) return null;
7021                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7022            case FOCUS_BACKWARD: {
7023                if (mID == View.NO_ID) return null;
7024                final int id = mID;
7025                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7026                    @Override
7027                    public boolean apply(View t) {
7028                        return t.mNextFocusForwardId == id;
7029                    }
7030                });
7031            }
7032        }
7033        return null;
7034    }
7035
7036    private View findViewInsideOutShouldExist(View root, int id) {
7037        if (mMatchIdPredicate == null) {
7038            mMatchIdPredicate = new MatchIdPredicate();
7039        }
7040        mMatchIdPredicate.mId = id;
7041        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7042        if (result == null) {
7043            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7044        }
7045        return result;
7046    }
7047
7048    /**
7049     * Find and return all focusable views that are descendants of this view,
7050     * possibly including this view if it is focusable itself.
7051     *
7052     * @param direction The direction of the focus
7053     * @return A list of focusable views
7054     */
7055    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7056        ArrayList<View> result = new ArrayList<View>(24);
7057        addFocusables(result, direction);
7058        return result;
7059    }
7060
7061    /**
7062     * Add any focusable views that are descendants of this view (possibly
7063     * including this view if it is focusable itself) to views.  If we are in touch mode,
7064     * only add views that are also focusable in touch mode.
7065     *
7066     * @param views Focusable views found so far
7067     * @param direction The direction of the focus
7068     */
7069    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7070        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7071    }
7072
7073    /**
7074     * Adds any focusable views that are descendants of this view (possibly
7075     * including this view if it is focusable itself) to views. This method
7076     * adds all focusable views regardless if we are in touch mode or
7077     * only views focusable in touch mode if we are in touch mode or
7078     * only views that can take accessibility focus if accessibility is enabeld
7079     * depending on the focusable mode paramater.
7080     *
7081     * @param views Focusable views found so far or null if all we are interested is
7082     *        the number of focusables.
7083     * @param direction The direction of the focus.
7084     * @param focusableMode The type of focusables to be added.
7085     *
7086     * @see #FOCUSABLES_ALL
7087     * @see #FOCUSABLES_TOUCH_MODE
7088     */
7089    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7090            @FocusableMode int focusableMode) {
7091        if (views == null) {
7092            return;
7093        }
7094        if (!isFocusable()) {
7095            return;
7096        }
7097        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7098                && isInTouchMode() && !isFocusableInTouchMode()) {
7099            return;
7100        }
7101        views.add(this);
7102    }
7103
7104    /**
7105     * Finds the Views that contain given text. The containment is case insensitive.
7106     * The search is performed by either the text that the View renders or the content
7107     * description that describes the view for accessibility purposes and the view does
7108     * not render or both. Clients can specify how the search is to be performed via
7109     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7110     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7111     *
7112     * @param outViews The output list of matching Views.
7113     * @param searched The text to match against.
7114     *
7115     * @see #FIND_VIEWS_WITH_TEXT
7116     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7117     * @see #setContentDescription(CharSequence)
7118     */
7119    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7120            @FindViewFlags int flags) {
7121        if (getAccessibilityNodeProvider() != null) {
7122            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7123                outViews.add(this);
7124            }
7125        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7126                && (searched != null && searched.length() > 0)
7127                && (mContentDescription != null && mContentDescription.length() > 0)) {
7128            String searchedLowerCase = searched.toString().toLowerCase();
7129            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7130            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7131                outViews.add(this);
7132            }
7133        }
7134    }
7135
7136    /**
7137     * Find and return all touchable views that are descendants of this view,
7138     * possibly including this view if it is touchable itself.
7139     *
7140     * @return A list of touchable views
7141     */
7142    public ArrayList<View> getTouchables() {
7143        ArrayList<View> result = new ArrayList<View>();
7144        addTouchables(result);
7145        return result;
7146    }
7147
7148    /**
7149     * Add any touchable views that are descendants of this view (possibly
7150     * including this view if it is touchable itself) to views.
7151     *
7152     * @param views Touchable views found so far
7153     */
7154    public void addTouchables(ArrayList<View> views) {
7155        final int viewFlags = mViewFlags;
7156
7157        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7158                && (viewFlags & ENABLED_MASK) == ENABLED) {
7159            views.add(this);
7160        }
7161    }
7162
7163    /**
7164     * Returns whether this View is accessibility focused.
7165     *
7166     * @return True if this View is accessibility focused.
7167     */
7168    public boolean isAccessibilityFocused() {
7169        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7170    }
7171
7172    /**
7173     * Call this to try to give accessibility focus to this view.
7174     *
7175     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7176     * returns false or the view is no visible or the view already has accessibility
7177     * focus.
7178     *
7179     * See also {@link #focusSearch(int)}, which is what you call to say that you
7180     * have focus, and you want your parent to look for the next one.
7181     *
7182     * @return Whether this view actually took accessibility focus.
7183     *
7184     * @hide
7185     */
7186    public boolean requestAccessibilityFocus() {
7187        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7188        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7189            return false;
7190        }
7191        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7192            return false;
7193        }
7194        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7195            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7196            ViewRootImpl viewRootImpl = getViewRootImpl();
7197            if (viewRootImpl != null) {
7198                viewRootImpl.setAccessibilityFocus(this, null);
7199            }
7200            invalidate();
7201            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7202            return true;
7203        }
7204        return false;
7205    }
7206
7207    /**
7208     * Call this to try to clear accessibility focus of this view.
7209     *
7210     * See also {@link #focusSearch(int)}, which is what you call to say that you
7211     * have focus, and you want your parent to look for the next one.
7212     *
7213     * @hide
7214     */
7215    public void clearAccessibilityFocus() {
7216        clearAccessibilityFocusNoCallbacks();
7217        // Clear the global reference of accessibility focus if this
7218        // view or any of its descendants had accessibility focus.
7219        ViewRootImpl viewRootImpl = getViewRootImpl();
7220        if (viewRootImpl != null) {
7221            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7222            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7223                viewRootImpl.setAccessibilityFocus(null, null);
7224            }
7225        }
7226    }
7227
7228    private void sendAccessibilityHoverEvent(int eventType) {
7229        // Since we are not delivering to a client accessibility events from not
7230        // important views (unless the clinet request that) we need to fire the
7231        // event from the deepest view exposed to the client. As a consequence if
7232        // the user crosses a not exposed view the client will see enter and exit
7233        // of the exposed predecessor followed by and enter and exit of that same
7234        // predecessor when entering and exiting the not exposed descendant. This
7235        // is fine since the client has a clear idea which view is hovered at the
7236        // price of a couple more events being sent. This is a simple and
7237        // working solution.
7238        View source = this;
7239        while (true) {
7240            if (source.includeForAccessibility()) {
7241                source.sendAccessibilityEvent(eventType);
7242                return;
7243            }
7244            ViewParent parent = source.getParent();
7245            if (parent instanceof View) {
7246                source = (View) parent;
7247            } else {
7248                return;
7249            }
7250        }
7251    }
7252
7253    /**
7254     * Clears accessibility focus without calling any callback methods
7255     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7256     * is used for clearing accessibility focus when giving this focus to
7257     * another view.
7258     */
7259    void clearAccessibilityFocusNoCallbacks() {
7260        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7261            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7262            invalidate();
7263            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7264        }
7265    }
7266
7267    /**
7268     * Call this to try to give focus to a specific view or to one of its
7269     * descendants.
7270     *
7271     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7272     * false), or if it is focusable and it is not focusable in touch mode
7273     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7274     *
7275     * See also {@link #focusSearch(int)}, which is what you call to say that you
7276     * have focus, and you want your parent to look for the next one.
7277     *
7278     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7279     * {@link #FOCUS_DOWN} and <code>null</code>.
7280     *
7281     * @return Whether this view or one of its descendants actually took focus.
7282     */
7283    public final boolean requestFocus() {
7284        return requestFocus(View.FOCUS_DOWN);
7285    }
7286
7287    /**
7288     * Call this to try to give focus to a specific view or to one of its
7289     * descendants and give it a hint about what direction focus is heading.
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     * See also {@link #focusSearch(int)}, which is what you call to say that you
7296     * have focus, and you want your parent to look for the next one.
7297     *
7298     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7299     * <code>null</code> set for the previously focused rectangle.
7300     *
7301     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7302     * @return Whether this view or one of its descendants actually took focus.
7303     */
7304    public final boolean requestFocus(int direction) {
7305        return requestFocus(direction, null);
7306    }
7307
7308    /**
7309     * Call this to try to give focus to a specific view or to one of its descendants
7310     * and give it hints about the direction and a specific rectangle that the focus
7311     * is coming from.  The rectangle can help give larger views a finer grained hint
7312     * about where focus is coming from, and therefore, where to show selection, or
7313     * forward focus change internally.
7314     *
7315     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7316     * false), or if it is focusable and it is not focusable in touch mode
7317     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7318     *
7319     * A View will not take focus if it is not visible.
7320     *
7321     * A View will not take focus if one of its parents has
7322     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7323     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7324     *
7325     * See also {@link #focusSearch(int)}, which is what you call to say that you
7326     * have focus, and you want your parent to look for the next one.
7327     *
7328     * You may wish to override this method if your custom {@link View} has an internal
7329     * {@link View} that it wishes to forward the request to.
7330     *
7331     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7332     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7333     *        to give a finer grained hint about where focus is coming from.  May be null
7334     *        if there is no hint.
7335     * @return Whether this view or one of its descendants actually took focus.
7336     */
7337    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7338        return requestFocusNoSearch(direction, previouslyFocusedRect);
7339    }
7340
7341    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7342        // need to be focusable
7343        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7344                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7345            return false;
7346        }
7347
7348        // need to be focusable in touch mode if in touch mode
7349        if (isInTouchMode() &&
7350            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7351               return false;
7352        }
7353
7354        // need to not have any parents blocking us
7355        if (hasAncestorThatBlocksDescendantFocus()) {
7356            return false;
7357        }
7358
7359        handleFocusGainInternal(direction, previouslyFocusedRect);
7360        return true;
7361    }
7362
7363    /**
7364     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7365     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7366     * touch mode to request focus when they are touched.
7367     *
7368     * @return Whether this view or one of its descendants actually took focus.
7369     *
7370     * @see #isInTouchMode()
7371     *
7372     */
7373    public final boolean requestFocusFromTouch() {
7374        // Leave touch mode if we need to
7375        if (isInTouchMode()) {
7376            ViewRootImpl viewRoot = getViewRootImpl();
7377            if (viewRoot != null) {
7378                viewRoot.ensureTouchMode(false);
7379            }
7380        }
7381        return requestFocus(View.FOCUS_DOWN);
7382    }
7383
7384    /**
7385     * @return Whether any ancestor of this view blocks descendant focus.
7386     */
7387    private boolean hasAncestorThatBlocksDescendantFocus() {
7388        ViewParent ancestor = mParent;
7389        while (ancestor instanceof ViewGroup) {
7390            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7391            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7392                return true;
7393            } else {
7394                ancestor = vgAncestor.getParent();
7395            }
7396        }
7397        return false;
7398    }
7399
7400    /**
7401     * Gets the mode for determining whether this View is important for accessibility
7402     * which is if it fires accessibility events and if it is reported to
7403     * accessibility services that query the screen.
7404     *
7405     * @return The mode for determining whether a View is important for accessibility.
7406     *
7407     * @attr ref android.R.styleable#View_importantForAccessibility
7408     *
7409     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7410     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7411     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7412     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7413     */
7414    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7415            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7416            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7417            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7418            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7419                    to = "noHideDescendants")
7420        })
7421    public int getImportantForAccessibility() {
7422        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7423                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7424    }
7425
7426    /**
7427     * Sets the live region mode for this view. This indicates to accessibility
7428     * services whether they should automatically notify the user about changes
7429     * to the view's content description or text, or to the content descriptions
7430     * or text of the view's children (where applicable).
7431     * <p>
7432     * For example, in a login screen with a TextView that displays an "incorrect
7433     * password" notification, that view should be marked as a live region with
7434     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7435     * <p>
7436     * To disable change notifications for this view, use
7437     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7438     * mode for most views.
7439     * <p>
7440     * To indicate that the user should be notified of changes, use
7441     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7442     * <p>
7443     * If the view's changes should interrupt ongoing speech and notify the user
7444     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7445     *
7446     * @param mode The live region mode for this view, one of:
7447     *        <ul>
7448     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7449     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7450     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7451     *        </ul>
7452     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7453     */
7454    public void setAccessibilityLiveRegion(int mode) {
7455        if (mode != getAccessibilityLiveRegion()) {
7456            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7457            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7458                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7459            notifyViewAccessibilityStateChangedIfNeeded(
7460                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7461        }
7462    }
7463
7464    /**
7465     * Gets the live region mode for this View.
7466     *
7467     * @return The live region mode for the view.
7468     *
7469     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7470     *
7471     * @see #setAccessibilityLiveRegion(int)
7472     */
7473    public int getAccessibilityLiveRegion() {
7474        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7475                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7476    }
7477
7478    /**
7479     * Sets how to determine whether this view is important for accessibility
7480     * which is if it fires accessibility events and if it is reported to
7481     * accessibility services that query the screen.
7482     *
7483     * @param mode How to determine whether this view is important for accessibility.
7484     *
7485     * @attr ref android.R.styleable#View_importantForAccessibility
7486     *
7487     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7488     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7489     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7490     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7491     */
7492    public void setImportantForAccessibility(int mode) {
7493        final int oldMode = getImportantForAccessibility();
7494        if (mode != oldMode) {
7495            // If we're moving between AUTO and another state, we might not need
7496            // to send a subtree changed notification. We'll store the computed
7497            // importance, since we'll need to check it later to make sure.
7498            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7499                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7500            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7501            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7502            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7503                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7504            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7505                notifySubtreeAccessibilityStateChangedIfNeeded();
7506            } else {
7507                notifyViewAccessibilityStateChangedIfNeeded(
7508                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7509            }
7510        }
7511    }
7512
7513    /**
7514     * Computes whether this view should be exposed for accessibility. In
7515     * general, views that are interactive or provide information are exposed
7516     * while views that serve only as containers are hidden.
7517     * <p>
7518     * If an ancestor of this view has importance
7519     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7520     * returns <code>false</code>.
7521     * <p>
7522     * Otherwise, the value is computed according to the view's
7523     * {@link #getImportantForAccessibility()} value:
7524     * <ol>
7525     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7526     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7527     * </code>
7528     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7529     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7530     * view satisfies any of the following:
7531     * <ul>
7532     * <li>Is actionable, e.g. {@link #isClickable()},
7533     * {@link #isLongClickable()}, or {@link #isFocusable()}
7534     * <li>Has an {@link AccessibilityDelegate}
7535     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7536     * {@link OnKeyListener}, etc.
7537     * <li>Is an accessibility live region, e.g.
7538     * {@link #getAccessibilityLiveRegion()} is not
7539     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7540     * </ul>
7541     * </ol>
7542     *
7543     * @return Whether the view is exposed for accessibility.
7544     * @see #setImportantForAccessibility(int)
7545     * @see #getImportantForAccessibility()
7546     */
7547    public boolean isImportantForAccessibility() {
7548        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7549                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7550        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7551                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7552            return false;
7553        }
7554
7555        // Check parent mode to ensure we're not hidden.
7556        ViewParent parent = mParent;
7557        while (parent instanceof View) {
7558            if (((View) parent).getImportantForAccessibility()
7559                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7560                return false;
7561            }
7562            parent = parent.getParent();
7563        }
7564
7565        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7566                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7567                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7568    }
7569
7570    /**
7571     * Gets the parent for accessibility purposes. Note that the parent for
7572     * accessibility is not necessary the immediate parent. It is the first
7573     * predecessor that is important for accessibility.
7574     *
7575     * @return The parent for accessibility purposes.
7576     */
7577    public ViewParent getParentForAccessibility() {
7578        if (mParent instanceof View) {
7579            View parentView = (View) mParent;
7580            if (parentView.includeForAccessibility()) {
7581                return mParent;
7582            } else {
7583                return mParent.getParentForAccessibility();
7584            }
7585        }
7586        return null;
7587    }
7588
7589    /**
7590     * Adds the children of a given View for accessibility. Since some Views are
7591     * not important for accessibility the children for accessibility are not
7592     * necessarily direct children of the view, rather they are the first level of
7593     * descendants important for accessibility.
7594     *
7595     * @param children The list of children for accessibility.
7596     */
7597    public void addChildrenForAccessibility(ArrayList<View> children) {
7598
7599    }
7600
7601    /**
7602     * Whether to regard this view for accessibility. A view is regarded for
7603     * accessibility if it is important for accessibility or the querying
7604     * accessibility service has explicitly requested that view not
7605     * important for accessibility are regarded.
7606     *
7607     * @return Whether to regard the view for accessibility.
7608     *
7609     * @hide
7610     */
7611    public boolean includeForAccessibility() {
7612        if (mAttachInfo != null) {
7613            return (mAttachInfo.mAccessibilityFetchFlags
7614                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7615                    || isImportantForAccessibility();
7616        }
7617        return false;
7618    }
7619
7620    /**
7621     * Returns whether the View is considered actionable from
7622     * accessibility perspective. Such view are important for
7623     * accessibility.
7624     *
7625     * @return True if the view is actionable for accessibility.
7626     *
7627     * @hide
7628     */
7629    public boolean isActionableForAccessibility() {
7630        return (isClickable() || isLongClickable() || isFocusable());
7631    }
7632
7633    /**
7634     * Returns whether the View has registered callbacks which makes it
7635     * important for accessibility.
7636     *
7637     * @return True if the view is actionable for accessibility.
7638     */
7639    private boolean hasListenersForAccessibility() {
7640        ListenerInfo info = getListenerInfo();
7641        return mTouchDelegate != null || info.mOnKeyListener != null
7642                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7643                || info.mOnHoverListener != null || info.mOnDragListener != null;
7644    }
7645
7646    /**
7647     * Notifies that the accessibility state of this view changed. The change
7648     * is local to this view and does not represent structural changes such
7649     * as children and parent. For example, the view became focusable. The
7650     * notification is at at most once every
7651     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7652     * to avoid unnecessary load to the system. Also once a view has a pending
7653     * notification this method is a NOP until the notification has been sent.
7654     *
7655     * @hide
7656     */
7657    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7658        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7659            return;
7660        }
7661        if (mSendViewStateChangedAccessibilityEvent == null) {
7662            mSendViewStateChangedAccessibilityEvent =
7663                    new SendViewStateChangedAccessibilityEvent();
7664        }
7665        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7666    }
7667
7668    /**
7669     * Notifies that the accessibility state of this view changed. The change
7670     * is *not* local to this view and does represent structural changes such
7671     * as children and parent. For example, the view size changed. The
7672     * notification is at at most once every
7673     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7674     * to avoid unnecessary load to the system. Also once a view has a pending
7675     * notifucation this method is a NOP until the notification has been sent.
7676     *
7677     * @hide
7678     */
7679    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7680        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7681            return;
7682        }
7683        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7684            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7685            if (mParent != null) {
7686                try {
7687                    mParent.notifySubtreeAccessibilityStateChanged(
7688                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7689                } catch (AbstractMethodError e) {
7690                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7691                            " does not fully implement ViewParent", e);
7692                }
7693            }
7694        }
7695    }
7696
7697    /**
7698     * Reset the flag indicating the accessibility state of the subtree rooted
7699     * at this view changed.
7700     */
7701    void resetSubtreeAccessibilityStateChanged() {
7702        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7703    }
7704
7705    /**
7706     * Performs the specified accessibility action on the view. For
7707     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7708     * <p>
7709     * If an {@link AccessibilityDelegate} has been specified via calling
7710     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7711     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7712     * is responsible for handling this call.
7713     * </p>
7714     *
7715     * @param action The action to perform.
7716     * @param arguments Optional action arguments.
7717     * @return Whether the action was performed.
7718     */
7719    public boolean performAccessibilityAction(int action, Bundle arguments) {
7720      if (mAccessibilityDelegate != null) {
7721          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7722      } else {
7723          return performAccessibilityActionInternal(action, arguments);
7724      }
7725    }
7726
7727   /**
7728    * @see #performAccessibilityAction(int, Bundle)
7729    *
7730    * Note: Called from the default {@link AccessibilityDelegate}.
7731    */
7732    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7733        switch (action) {
7734            case AccessibilityNodeInfo.ACTION_CLICK: {
7735                if (isClickable()) {
7736                    performClick();
7737                    return true;
7738                }
7739            } break;
7740            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7741                if (isLongClickable()) {
7742                    performLongClick();
7743                    return true;
7744                }
7745            } break;
7746            case AccessibilityNodeInfo.ACTION_FOCUS: {
7747                if (!hasFocus()) {
7748                    // Get out of touch mode since accessibility
7749                    // wants to move focus around.
7750                    getViewRootImpl().ensureTouchMode(false);
7751                    return requestFocus();
7752                }
7753            } break;
7754            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7755                if (hasFocus()) {
7756                    clearFocus();
7757                    return !isFocused();
7758                }
7759            } break;
7760            case AccessibilityNodeInfo.ACTION_SELECT: {
7761                if (!isSelected()) {
7762                    setSelected(true);
7763                    return isSelected();
7764                }
7765            } break;
7766            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7767                if (isSelected()) {
7768                    setSelected(false);
7769                    return !isSelected();
7770                }
7771            } break;
7772            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7773                if (!isAccessibilityFocused()) {
7774                    return requestAccessibilityFocus();
7775                }
7776            } break;
7777            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7778                if (isAccessibilityFocused()) {
7779                    clearAccessibilityFocus();
7780                    return true;
7781                }
7782            } break;
7783            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7784                if (arguments != null) {
7785                    final int granularity = arguments.getInt(
7786                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7787                    final boolean extendSelection = arguments.getBoolean(
7788                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7789                    return traverseAtGranularity(granularity, true, extendSelection);
7790                }
7791            } break;
7792            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7793                if (arguments != null) {
7794                    final int granularity = arguments.getInt(
7795                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7796                    final boolean extendSelection = arguments.getBoolean(
7797                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7798                    return traverseAtGranularity(granularity, false, extendSelection);
7799                }
7800            } break;
7801            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7802                CharSequence text = getIterableTextForAccessibility();
7803                if (text == null) {
7804                    return false;
7805                }
7806                final int start = (arguments != null) ? arguments.getInt(
7807                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7808                final int end = (arguments != null) ? arguments.getInt(
7809                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7810                // Only cursor position can be specified (selection length == 0)
7811                if ((getAccessibilitySelectionStart() != start
7812                        || getAccessibilitySelectionEnd() != end)
7813                        && (start == end)) {
7814                    setAccessibilitySelection(start, end);
7815                    notifyViewAccessibilityStateChangedIfNeeded(
7816                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7817                    return true;
7818                }
7819            } break;
7820        }
7821        return false;
7822    }
7823
7824    private boolean traverseAtGranularity(int granularity, boolean forward,
7825            boolean extendSelection) {
7826        CharSequence text = getIterableTextForAccessibility();
7827        if (text == null || text.length() == 0) {
7828            return false;
7829        }
7830        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7831        if (iterator == null) {
7832            return false;
7833        }
7834        int current = getAccessibilitySelectionEnd();
7835        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7836            current = forward ? 0 : text.length();
7837        }
7838        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7839        if (range == null) {
7840            return false;
7841        }
7842        final int segmentStart = range[0];
7843        final int segmentEnd = range[1];
7844        int selectionStart;
7845        int selectionEnd;
7846        if (extendSelection && isAccessibilitySelectionExtendable()) {
7847            selectionStart = getAccessibilitySelectionStart();
7848            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7849                selectionStart = forward ? segmentStart : segmentEnd;
7850            }
7851            selectionEnd = forward ? segmentEnd : segmentStart;
7852        } else {
7853            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7854        }
7855        setAccessibilitySelection(selectionStart, selectionEnd);
7856        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7857                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7858        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7859        return true;
7860    }
7861
7862    /**
7863     * Gets the text reported for accessibility purposes.
7864     *
7865     * @return The accessibility text.
7866     *
7867     * @hide
7868     */
7869    public CharSequence getIterableTextForAccessibility() {
7870        return getContentDescription();
7871    }
7872
7873    /**
7874     * Gets whether accessibility selection can be extended.
7875     *
7876     * @return If selection is extensible.
7877     *
7878     * @hide
7879     */
7880    public boolean isAccessibilitySelectionExtendable() {
7881        return false;
7882    }
7883
7884    /**
7885     * @hide
7886     */
7887    public int getAccessibilitySelectionStart() {
7888        return mAccessibilityCursorPosition;
7889    }
7890
7891    /**
7892     * @hide
7893     */
7894    public int getAccessibilitySelectionEnd() {
7895        return getAccessibilitySelectionStart();
7896    }
7897
7898    /**
7899     * @hide
7900     */
7901    public void setAccessibilitySelection(int start, int end) {
7902        if (start ==  end && end == mAccessibilityCursorPosition) {
7903            return;
7904        }
7905        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7906            mAccessibilityCursorPosition = start;
7907        } else {
7908            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7909        }
7910        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7911    }
7912
7913    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7914            int fromIndex, int toIndex) {
7915        if (mParent == null) {
7916            return;
7917        }
7918        AccessibilityEvent event = AccessibilityEvent.obtain(
7919                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7920        onInitializeAccessibilityEvent(event);
7921        onPopulateAccessibilityEvent(event);
7922        event.setFromIndex(fromIndex);
7923        event.setToIndex(toIndex);
7924        event.setAction(action);
7925        event.setMovementGranularity(granularity);
7926        mParent.requestSendAccessibilityEvent(this, event);
7927    }
7928
7929    /**
7930     * @hide
7931     */
7932    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7933        switch (granularity) {
7934            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7935                CharSequence text = getIterableTextForAccessibility();
7936                if (text != null && text.length() > 0) {
7937                    CharacterTextSegmentIterator iterator =
7938                        CharacterTextSegmentIterator.getInstance(
7939                                mContext.getResources().getConfiguration().locale);
7940                    iterator.initialize(text.toString());
7941                    return iterator;
7942                }
7943            } break;
7944            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7945                CharSequence text = getIterableTextForAccessibility();
7946                if (text != null && text.length() > 0) {
7947                    WordTextSegmentIterator iterator =
7948                        WordTextSegmentIterator.getInstance(
7949                                mContext.getResources().getConfiguration().locale);
7950                    iterator.initialize(text.toString());
7951                    return iterator;
7952                }
7953            } break;
7954            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7955                CharSequence text = getIterableTextForAccessibility();
7956                if (text != null && text.length() > 0) {
7957                    ParagraphTextSegmentIterator iterator =
7958                        ParagraphTextSegmentIterator.getInstance();
7959                    iterator.initialize(text.toString());
7960                    return iterator;
7961                }
7962            } break;
7963        }
7964        return null;
7965    }
7966
7967    /**
7968     * @hide
7969     */
7970    public void dispatchStartTemporaryDetach() {
7971        clearDisplayList();
7972
7973        onStartTemporaryDetach();
7974    }
7975
7976    /**
7977     * This is called when a container is going to temporarily detach a child, with
7978     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7979     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7980     * {@link #onDetachedFromWindow()} when the container is done.
7981     */
7982    public void onStartTemporaryDetach() {
7983        removeUnsetPressCallback();
7984        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7985    }
7986
7987    /**
7988     * @hide
7989     */
7990    public void dispatchFinishTemporaryDetach() {
7991        onFinishTemporaryDetach();
7992    }
7993
7994    /**
7995     * Called after {@link #onStartTemporaryDetach} when the container is done
7996     * changing the view.
7997     */
7998    public void onFinishTemporaryDetach() {
7999    }
8000
8001    /**
8002     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8003     * for this view's window.  Returns null if the view is not currently attached
8004     * to the window.  Normally you will not need to use this directly, but
8005     * just use the standard high-level event callbacks like
8006     * {@link #onKeyDown(int, KeyEvent)}.
8007     */
8008    public KeyEvent.DispatcherState getKeyDispatcherState() {
8009        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8010    }
8011
8012    /**
8013     * Dispatch a key event before it is processed by any input method
8014     * associated with the view hierarchy.  This can be used to intercept
8015     * key events in special situations before the IME consumes them; a
8016     * typical example would be handling the BACK key to update the application's
8017     * UI instead of allowing the IME to see it and close itself.
8018     *
8019     * @param event The key event to be dispatched.
8020     * @return True if the event was handled, false otherwise.
8021     */
8022    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8023        return onKeyPreIme(event.getKeyCode(), event);
8024    }
8025
8026    /**
8027     * Dispatch a key event to the next view on the focus path. This path runs
8028     * from the top of the view tree down to the currently focused view. If this
8029     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8030     * the next node down the focus path. This method also fires any key
8031     * listeners.
8032     *
8033     * @param event The key event to be dispatched.
8034     * @return True if the event was handled, false otherwise.
8035     */
8036    public boolean dispatchKeyEvent(KeyEvent event) {
8037        if (mInputEventConsistencyVerifier != null) {
8038            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8039        }
8040
8041        // Give any attached key listener a first crack at the event.
8042        //noinspection SimplifiableIfStatement
8043        ListenerInfo li = mListenerInfo;
8044        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8045                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8046            return true;
8047        }
8048
8049        if (event.dispatch(this, mAttachInfo != null
8050                ? mAttachInfo.mKeyDispatchState : null, this)) {
8051            return true;
8052        }
8053
8054        if (mInputEventConsistencyVerifier != null) {
8055            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8056        }
8057        return false;
8058    }
8059
8060    /**
8061     * Dispatches a key shortcut event.
8062     *
8063     * @param event The key event to be dispatched.
8064     * @return True if the event was handled by the view, false otherwise.
8065     */
8066    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8067        return onKeyShortcut(event.getKeyCode(), event);
8068    }
8069
8070    /**
8071     * Pass the touch screen motion event down to the target view, or this
8072     * view if it is the target.
8073     *
8074     * @param event The motion event to be dispatched.
8075     * @return True if the event was handled by the view, false otherwise.
8076     */
8077    public boolean dispatchTouchEvent(MotionEvent event) {
8078        if (mInputEventConsistencyVerifier != null) {
8079            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8080        }
8081
8082        if (onFilterTouchEventForSecurity(event)) {
8083            //noinspection SimplifiableIfStatement
8084            ListenerInfo li = mListenerInfo;
8085            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8086                    && li.mOnTouchListener.onTouch(this, event)) {
8087                return true;
8088            }
8089
8090            if (onTouchEvent(event)) {
8091                return true;
8092            }
8093        }
8094
8095        if (mInputEventConsistencyVerifier != null) {
8096            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8097        }
8098        return false;
8099    }
8100
8101    /**
8102     * Filter the touch event to apply security policies.
8103     *
8104     * @param event The motion event to be filtered.
8105     * @return True if the event should be dispatched, false if the event should be dropped.
8106     *
8107     * @see #getFilterTouchesWhenObscured
8108     */
8109    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8110        //noinspection RedundantIfStatement
8111        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8112                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8113            // Window is obscured, drop this touch.
8114            return false;
8115        }
8116        return true;
8117    }
8118
8119    /**
8120     * Pass a trackball motion event down to the focused view.
8121     *
8122     * @param event The motion event to be dispatched.
8123     * @return True if the event was handled by the view, false otherwise.
8124     */
8125    public boolean dispatchTrackballEvent(MotionEvent event) {
8126        if (mInputEventConsistencyVerifier != null) {
8127            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8128        }
8129
8130        return onTrackballEvent(event);
8131    }
8132
8133    /**
8134     * Dispatch a generic motion event.
8135     * <p>
8136     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8137     * are delivered to the view under the pointer.  All other generic motion events are
8138     * delivered to the focused view.  Hover events are handled specially and are delivered
8139     * to {@link #onHoverEvent(MotionEvent)}.
8140     * </p>
8141     *
8142     * @param event The motion event to be dispatched.
8143     * @return True if the event was handled by the view, false otherwise.
8144     */
8145    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8146        if (mInputEventConsistencyVerifier != null) {
8147            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8148        }
8149
8150        final int source = event.getSource();
8151        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8152            final int action = event.getAction();
8153            if (action == MotionEvent.ACTION_HOVER_ENTER
8154                    || action == MotionEvent.ACTION_HOVER_MOVE
8155                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8156                if (dispatchHoverEvent(event)) {
8157                    return true;
8158                }
8159            } else if (dispatchGenericPointerEvent(event)) {
8160                return true;
8161            }
8162        } else if (dispatchGenericFocusedEvent(event)) {
8163            return true;
8164        }
8165
8166        if (dispatchGenericMotionEventInternal(event)) {
8167            return true;
8168        }
8169
8170        if (mInputEventConsistencyVerifier != null) {
8171            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8172        }
8173        return false;
8174    }
8175
8176    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8177        //noinspection SimplifiableIfStatement
8178        ListenerInfo li = mListenerInfo;
8179        if (li != null && li.mOnGenericMotionListener != null
8180                && (mViewFlags & ENABLED_MASK) == ENABLED
8181                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8182            return true;
8183        }
8184
8185        if (onGenericMotionEvent(event)) {
8186            return true;
8187        }
8188
8189        if (mInputEventConsistencyVerifier != null) {
8190            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8191        }
8192        return false;
8193    }
8194
8195    /**
8196     * Dispatch a hover event.
8197     * <p>
8198     * Do not call this method directly.
8199     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8200     * </p>
8201     *
8202     * @param event The motion event to be dispatched.
8203     * @return True if the event was handled by the view, false otherwise.
8204     */
8205    protected boolean dispatchHoverEvent(MotionEvent event) {
8206        ListenerInfo li = mListenerInfo;
8207        //noinspection SimplifiableIfStatement
8208        if (li != null && li.mOnHoverListener != null
8209                && (mViewFlags & ENABLED_MASK) == ENABLED
8210                && li.mOnHoverListener.onHover(this, event)) {
8211            return true;
8212        }
8213
8214        return onHoverEvent(event);
8215    }
8216
8217    /**
8218     * Returns true if the view has a child to which it has recently sent
8219     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8220     * it does not have a hovered child, then it must be the innermost hovered view.
8221     * @hide
8222     */
8223    protected boolean hasHoveredChild() {
8224        return false;
8225    }
8226
8227    /**
8228     * Dispatch a generic motion event to the view under the first pointer.
8229     * <p>
8230     * Do not call this method directly.
8231     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8232     * </p>
8233     *
8234     * @param event The motion event to be dispatched.
8235     * @return True if the event was handled by the view, false otherwise.
8236     */
8237    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8238        return false;
8239    }
8240
8241    /**
8242     * Dispatch a generic motion event to the currently focused view.
8243     * <p>
8244     * Do not call this method directly.
8245     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8246     * </p>
8247     *
8248     * @param event The motion event to be dispatched.
8249     * @return True if the event was handled by the view, false otherwise.
8250     */
8251    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8252        return false;
8253    }
8254
8255    /**
8256     * Dispatch a pointer event.
8257     * <p>
8258     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8259     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8260     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8261     * and should not be expected to handle other pointing device features.
8262     * </p>
8263     *
8264     * @param event The motion event to be dispatched.
8265     * @return True if the event was handled by the view, false otherwise.
8266     * @hide
8267     */
8268    public final boolean dispatchPointerEvent(MotionEvent event) {
8269        if (event.isTouchEvent()) {
8270            return dispatchTouchEvent(event);
8271        } else {
8272            return dispatchGenericMotionEvent(event);
8273        }
8274    }
8275
8276    /**
8277     * Called when the window containing this view gains or loses window focus.
8278     * ViewGroups should override to route to their children.
8279     *
8280     * @param hasFocus True if the window containing this view now has focus,
8281     *        false otherwise.
8282     */
8283    public void dispatchWindowFocusChanged(boolean hasFocus) {
8284        onWindowFocusChanged(hasFocus);
8285    }
8286
8287    /**
8288     * Called when the window containing this view gains or loses focus.  Note
8289     * that this is separate from view focus: to receive key events, both
8290     * your view and its window must have focus.  If a window is displayed
8291     * on top of yours that takes input focus, then your own window will lose
8292     * focus but the view focus will remain unchanged.
8293     *
8294     * @param hasWindowFocus True if the window containing this view now has
8295     *        focus, false otherwise.
8296     */
8297    public void onWindowFocusChanged(boolean hasWindowFocus) {
8298        InputMethodManager imm = InputMethodManager.peekInstance();
8299        if (!hasWindowFocus) {
8300            if (isPressed()) {
8301                setPressed(false);
8302            }
8303            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8304                imm.focusOut(this);
8305            }
8306            removeLongPressCallback();
8307            removeTapCallback();
8308            onFocusLost();
8309        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8310            imm.focusIn(this);
8311        }
8312        refreshDrawableState();
8313    }
8314
8315    /**
8316     * Returns true if this view is in a window that currently has window focus.
8317     * Note that this is not the same as the view itself having focus.
8318     *
8319     * @return True if this view is in a window that currently has window focus.
8320     */
8321    public boolean hasWindowFocus() {
8322        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8323    }
8324
8325    /**
8326     * Dispatch a view visibility change down the view hierarchy.
8327     * ViewGroups should override to route to their children.
8328     * @param changedView The view whose visibility changed. Could be 'this' or
8329     * an ancestor view.
8330     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8331     * {@link #INVISIBLE} or {@link #GONE}.
8332     */
8333    protected void dispatchVisibilityChanged(@NonNull View changedView,
8334            @Visibility int visibility) {
8335        onVisibilityChanged(changedView, visibility);
8336    }
8337
8338    /**
8339     * Called when the visibility of the view or an ancestor of the view is changed.
8340     * @param changedView The view whose visibility changed. Could be 'this' or
8341     * an ancestor view.
8342     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8343     * {@link #INVISIBLE} or {@link #GONE}.
8344     */
8345    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8346        if (visibility == VISIBLE) {
8347            if (mAttachInfo != null) {
8348                initialAwakenScrollBars();
8349            } else {
8350                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8351            }
8352        }
8353    }
8354
8355    /**
8356     * Dispatch a hint about whether this view is displayed. For instance, when
8357     * a View moves out of the screen, it might receives a display hint indicating
8358     * the view is not displayed. Applications should not <em>rely</em> on this hint
8359     * as there is no guarantee that they will receive one.
8360     *
8361     * @param hint A hint about whether or not this view is displayed:
8362     * {@link #VISIBLE} or {@link #INVISIBLE}.
8363     */
8364    public void dispatchDisplayHint(@Visibility int hint) {
8365        onDisplayHint(hint);
8366    }
8367
8368    /**
8369     * Gives this view a hint about whether is displayed or not. For instance, when
8370     * a View moves out of the screen, it might receives a display hint indicating
8371     * the view is not displayed. Applications should not <em>rely</em> on this hint
8372     * as there is no guarantee that they will receive one.
8373     *
8374     * @param hint A hint about whether or not this view is displayed:
8375     * {@link #VISIBLE} or {@link #INVISIBLE}.
8376     */
8377    protected void onDisplayHint(@Visibility int hint) {
8378    }
8379
8380    /**
8381     * Dispatch a window visibility change down the view hierarchy.
8382     * ViewGroups should override to route to their children.
8383     *
8384     * @param visibility The new visibility of the window.
8385     *
8386     * @see #onWindowVisibilityChanged(int)
8387     */
8388    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8389        onWindowVisibilityChanged(visibility);
8390    }
8391
8392    /**
8393     * Called when the window containing has change its visibility
8394     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8395     * that this tells you whether or not your window is being made visible
8396     * to the window manager; this does <em>not</em> tell you whether or not
8397     * your window is obscured by other windows on the screen, even if it
8398     * is itself visible.
8399     *
8400     * @param visibility The new visibility of the window.
8401     */
8402    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8403        if (visibility == VISIBLE) {
8404            initialAwakenScrollBars();
8405        }
8406    }
8407
8408    /**
8409     * Returns the current visibility of the window this view is attached to
8410     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8411     *
8412     * @return Returns the current visibility of the view's window.
8413     */
8414    @Visibility
8415    public int getWindowVisibility() {
8416        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8417    }
8418
8419    /**
8420     * Retrieve the overall visible display size in which the window this view is
8421     * attached to has been positioned in.  This takes into account screen
8422     * decorations above the window, for both cases where the window itself
8423     * is being position inside of them or the window is being placed under
8424     * then and covered insets are used for the window to position its content
8425     * inside.  In effect, this tells you the available area where content can
8426     * be placed and remain visible to users.
8427     *
8428     * <p>This function requires an IPC back to the window manager to retrieve
8429     * the requested information, so should not be used in performance critical
8430     * code like drawing.
8431     *
8432     * @param outRect Filled in with the visible display frame.  If the view
8433     * is not attached to a window, this is simply the raw display size.
8434     */
8435    public void getWindowVisibleDisplayFrame(Rect outRect) {
8436        if (mAttachInfo != null) {
8437            try {
8438                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8439            } catch (RemoteException e) {
8440                return;
8441            }
8442            // XXX This is really broken, and probably all needs to be done
8443            // in the window manager, and we need to know more about whether
8444            // we want the area behind or in front of the IME.
8445            final Rect insets = mAttachInfo.mVisibleInsets;
8446            outRect.left += insets.left;
8447            outRect.top += insets.top;
8448            outRect.right -= insets.right;
8449            outRect.bottom -= insets.bottom;
8450            return;
8451        }
8452        // The view is not attached to a display so we don't have a context.
8453        // Make a best guess about the display size.
8454        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8455        d.getRectSize(outRect);
8456    }
8457
8458    /**
8459     * Dispatch a notification about a resource configuration change down
8460     * the view hierarchy.
8461     * ViewGroups should override to route to their children.
8462     *
8463     * @param newConfig The new resource configuration.
8464     *
8465     * @see #onConfigurationChanged(android.content.res.Configuration)
8466     */
8467    public void dispatchConfigurationChanged(Configuration newConfig) {
8468        onConfigurationChanged(newConfig);
8469    }
8470
8471    /**
8472     * Called when the current configuration of the resources being used
8473     * by the application have changed.  You can use this to decide when
8474     * to reload resources that can changed based on orientation and other
8475     * configuration characterstics.  You only need to use this if you are
8476     * not relying on the normal {@link android.app.Activity} mechanism of
8477     * recreating the activity instance upon a configuration change.
8478     *
8479     * @param newConfig The new resource configuration.
8480     */
8481    protected void onConfigurationChanged(Configuration newConfig) {
8482    }
8483
8484    /**
8485     * Private function to aggregate all per-view attributes in to the view
8486     * root.
8487     */
8488    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8489        performCollectViewAttributes(attachInfo, visibility);
8490    }
8491
8492    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8493        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8494            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8495                attachInfo.mKeepScreenOn = true;
8496            }
8497            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8498            ListenerInfo li = mListenerInfo;
8499            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8500                attachInfo.mHasSystemUiListeners = true;
8501            }
8502        }
8503    }
8504
8505    void needGlobalAttributesUpdate(boolean force) {
8506        final AttachInfo ai = mAttachInfo;
8507        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8508            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8509                    || ai.mHasSystemUiListeners) {
8510                ai.mRecomputeGlobalAttributes = true;
8511            }
8512        }
8513    }
8514
8515    /**
8516     * Returns whether the device is currently in touch mode.  Touch mode is entered
8517     * once the user begins interacting with the device by touch, and affects various
8518     * things like whether focus is always visible to the user.
8519     *
8520     * @return Whether the device is in touch mode.
8521     */
8522    @ViewDebug.ExportedProperty
8523    public boolean isInTouchMode() {
8524        if (mAttachInfo != null) {
8525            return mAttachInfo.mInTouchMode;
8526        } else {
8527            return ViewRootImpl.isInTouchMode();
8528        }
8529    }
8530
8531    /**
8532     * Returns the context the view is running in, through which it can
8533     * access the current theme, resources, etc.
8534     *
8535     * @return The view's Context.
8536     */
8537    @ViewDebug.CapturedViewProperty
8538    public final Context getContext() {
8539        return mContext;
8540    }
8541
8542    /**
8543     * Handle a key event before it is processed by any input method
8544     * associated with the view hierarchy.  This can be used to intercept
8545     * key events in special situations before the IME consumes them; a
8546     * typical example would be handling the BACK key to update the application's
8547     * UI instead of allowing the IME to see it and close itself.
8548     *
8549     * @param keyCode The value in event.getKeyCode().
8550     * @param event Description of the key event.
8551     * @return If you handled the event, return true. If you want to allow the
8552     *         event to be handled by the next receiver, return false.
8553     */
8554    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8555        return false;
8556    }
8557
8558    /**
8559     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8560     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8561     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8562     * is released, if the view is enabled and clickable.
8563     *
8564     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8565     * although some may elect to do so in some situations. Do not rely on this to
8566     * catch software key presses.
8567     *
8568     * @param keyCode A key code that represents the button pressed, from
8569     *                {@link android.view.KeyEvent}.
8570     * @param event   The KeyEvent object that defines the button action.
8571     */
8572    public boolean onKeyDown(int keyCode, KeyEvent event) {
8573        boolean result = false;
8574
8575        if (KeyEvent.isConfirmKey(keyCode)) {
8576            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8577                return true;
8578            }
8579            // Long clickable items don't necessarily have to be clickable
8580            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8581                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8582                    (event.getRepeatCount() == 0)) {
8583                setPressed(true);
8584                checkForLongClick(0);
8585                return true;
8586            }
8587        }
8588        return result;
8589    }
8590
8591    /**
8592     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8593     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8594     * the event).
8595     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8596     * although some may elect to do so in some situations. Do not rely on this to
8597     * catch software key presses.
8598     */
8599    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8600        return false;
8601    }
8602
8603    /**
8604     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8605     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8606     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8607     * {@link KeyEvent#KEYCODE_ENTER} is released.
8608     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8609     * although some may elect to do so in some situations. Do not rely on this to
8610     * catch software key presses.
8611     *
8612     * @param keyCode A key code that represents the button pressed, from
8613     *                {@link android.view.KeyEvent}.
8614     * @param event   The KeyEvent object that defines the button action.
8615     */
8616    public boolean onKeyUp(int keyCode, KeyEvent event) {
8617        if (KeyEvent.isConfirmKey(keyCode)) {
8618            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8619                return true;
8620            }
8621            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8622                setPressed(false);
8623
8624                if (!mHasPerformedLongPress) {
8625                    // This is a tap, so remove the longpress check
8626                    removeLongPressCallback();
8627                    return performClick();
8628                }
8629            }
8630        }
8631        return false;
8632    }
8633
8634    /**
8635     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8636     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8637     * the event).
8638     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8639     * although some may elect to do so in some situations. Do not rely on this to
8640     * catch software key presses.
8641     *
8642     * @param keyCode     A key code that represents the button pressed, from
8643     *                    {@link android.view.KeyEvent}.
8644     * @param repeatCount The number of times the action was made.
8645     * @param event       The KeyEvent object that defines the button action.
8646     */
8647    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8648        return false;
8649    }
8650
8651    /**
8652     * Called on the focused view when a key shortcut event is not handled.
8653     * Override this method to implement local key shortcuts for the View.
8654     * Key shortcuts can also be implemented by setting the
8655     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8656     *
8657     * @param keyCode The value in event.getKeyCode().
8658     * @param event Description of the key event.
8659     * @return If you handled the event, return true. If you want to allow the
8660     *         event to be handled by the next receiver, return false.
8661     */
8662    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8663        return false;
8664    }
8665
8666    /**
8667     * Check whether the called view is a text editor, in which case it
8668     * would make sense to automatically display a soft input window for
8669     * it.  Subclasses should override this if they implement
8670     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8671     * a call on that method would return a non-null InputConnection, and
8672     * they are really a first-class editor that the user would normally
8673     * start typing on when the go into a window containing your view.
8674     *
8675     * <p>The default implementation always returns false.  This does
8676     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8677     * will not be called or the user can not otherwise perform edits on your
8678     * view; it is just a hint to the system that this is not the primary
8679     * purpose of this view.
8680     *
8681     * @return Returns true if this view is a text editor, else false.
8682     */
8683    public boolean onCheckIsTextEditor() {
8684        return false;
8685    }
8686
8687    /**
8688     * Create a new InputConnection for an InputMethod to interact
8689     * with the view.  The default implementation returns null, since it doesn't
8690     * support input methods.  You can override this to implement such support.
8691     * This is only needed for views that take focus and text input.
8692     *
8693     * <p>When implementing this, you probably also want to implement
8694     * {@link #onCheckIsTextEditor()} to indicate you will return a
8695     * non-null InputConnection.
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                // If the window does not have input focus we take away accessibility
8885                // focus as soon as the user stop hovering over the view.
8886                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8887                    getViewRootImpl().setAccessibilityFocus(null, null);
8888                }
8889            }
8890        }
8891
8892        if (isHoverable()) {
8893            switch (action) {
8894                case MotionEvent.ACTION_HOVER_ENTER:
8895                    setHovered(true);
8896                    break;
8897                case MotionEvent.ACTION_HOVER_EXIT:
8898                    setHovered(false);
8899                    break;
8900            }
8901
8902            // Dispatch the event to onGenericMotionEvent before returning true.
8903            // This is to provide compatibility with existing applications that
8904            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8905            // break because of the new default handling for hoverable views
8906            // in onHoverEvent.
8907            // Note that onGenericMotionEvent will be called by default when
8908            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8909            dispatchGenericMotionEventInternal(event);
8910            // The event was already handled by calling setHovered(), so always
8911            // return true.
8912            return true;
8913        }
8914
8915        return false;
8916    }
8917
8918    /**
8919     * Returns true if the view should handle {@link #onHoverEvent}
8920     * by calling {@link #setHovered} to change its hovered state.
8921     *
8922     * @return True if the view is hoverable.
8923     */
8924    private boolean isHoverable() {
8925        final int viewFlags = mViewFlags;
8926        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8927            return false;
8928        }
8929
8930        return (viewFlags & CLICKABLE) == CLICKABLE
8931                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8932    }
8933
8934    /**
8935     * Returns true if the view is currently hovered.
8936     *
8937     * @return True if the view is currently hovered.
8938     *
8939     * @see #setHovered
8940     * @see #onHoverChanged
8941     */
8942    @ViewDebug.ExportedProperty
8943    public boolean isHovered() {
8944        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8945    }
8946
8947    /**
8948     * Sets whether the view is currently hovered.
8949     * <p>
8950     * Calling this method also changes the drawable state of the view.  This
8951     * enables the view to react to hover by using different drawable resources
8952     * to change its appearance.
8953     * </p><p>
8954     * The {@link #onHoverChanged} method is called when the hovered state changes.
8955     * </p>
8956     *
8957     * @param hovered True if the view is hovered.
8958     *
8959     * @see #isHovered
8960     * @see #onHoverChanged
8961     */
8962    public void setHovered(boolean hovered) {
8963        if (hovered) {
8964            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8965                mPrivateFlags |= PFLAG_HOVERED;
8966                refreshDrawableState();
8967                onHoverChanged(true);
8968            }
8969        } else {
8970            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8971                mPrivateFlags &= ~PFLAG_HOVERED;
8972                refreshDrawableState();
8973                onHoverChanged(false);
8974            }
8975        }
8976    }
8977
8978    /**
8979     * Implement this method to handle hover state changes.
8980     * <p>
8981     * This method is called whenever the hover state changes as a result of a
8982     * call to {@link #setHovered}.
8983     * </p>
8984     *
8985     * @param hovered The current hover state, as returned by {@link #isHovered}.
8986     *
8987     * @see #isHovered
8988     * @see #setHovered
8989     */
8990    public void onHoverChanged(boolean hovered) {
8991    }
8992
8993    /**
8994     * Implement this method to handle touch screen motion events.
8995     * <p>
8996     * If this method is used to detect click actions, it is recommended that
8997     * the actions be performed by implementing and calling
8998     * {@link #performClick()}. This will ensure consistent system behavior,
8999     * including:
9000     * <ul>
9001     * <li>obeying click sound preferences
9002     * <li>dispatching OnClickListener calls
9003     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9004     * accessibility features are enabled
9005     * </ul>
9006     *
9007     * @param event The motion event.
9008     * @return True if the event was handled, false otherwise.
9009     */
9010    public boolean onTouchEvent(MotionEvent event) {
9011        final int viewFlags = mViewFlags;
9012
9013        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9014            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9015                setPressed(false);
9016            }
9017            // A disabled view that is clickable still consumes the touch
9018            // events, it just doesn't respond to them.
9019            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9020                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9021        }
9022
9023        if (mTouchDelegate != null) {
9024            if (mTouchDelegate.onTouchEvent(event)) {
9025                return true;
9026            }
9027        }
9028
9029        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9030                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9031            switch (event.getAction()) {
9032                case MotionEvent.ACTION_UP:
9033                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9034                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9035                        // take focus if we don't have it already and we should in
9036                        // touch mode.
9037                        boolean focusTaken = false;
9038                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9039                            focusTaken = requestFocus();
9040                        }
9041
9042                        if (prepressed) {
9043                            // The button is being released before we actually
9044                            // showed it as pressed.  Make it show the pressed
9045                            // state now (before scheduling the click) to ensure
9046                            // the user sees it.
9047                            setPressed(true);
9048                       }
9049
9050                        if (!mHasPerformedLongPress) {
9051                            // This is a tap, so remove the longpress check
9052                            removeLongPressCallback();
9053
9054                            // Only perform take click actions if we were in the pressed state
9055                            if (!focusTaken) {
9056                                // Use a Runnable and post this rather than calling
9057                                // performClick directly. This lets other visual state
9058                                // of the view update before click actions start.
9059                                if (mPerformClick == null) {
9060                                    mPerformClick = new PerformClick();
9061                                }
9062                                if (!post(mPerformClick)) {
9063                                    performClick();
9064                                }
9065                            }
9066                        }
9067
9068                        if (mUnsetPressedState == null) {
9069                            mUnsetPressedState = new UnsetPressedState();
9070                        }
9071
9072                        if (prepressed) {
9073                            postDelayed(mUnsetPressedState,
9074                                    ViewConfiguration.getPressedStateDuration());
9075                        } else if (!post(mUnsetPressedState)) {
9076                            // If the post failed, unpress right now
9077                            mUnsetPressedState.run();
9078                        }
9079                        removeTapCallback();
9080                    }
9081                    break;
9082
9083                case MotionEvent.ACTION_DOWN:
9084                    mHasPerformedLongPress = false;
9085
9086                    if (performButtonActionOnTouchDown(event)) {
9087                        break;
9088                    }
9089
9090                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9091                    boolean isInScrollingContainer = isInScrollingContainer();
9092
9093                    // For views inside a scrolling container, delay the pressed feedback for
9094                    // a short period in case this is a scroll.
9095                    if (isInScrollingContainer) {
9096                        mPrivateFlags |= PFLAG_PREPRESSED;
9097                        if (mPendingCheckForTap == null) {
9098                            mPendingCheckForTap = new CheckForTap();
9099                        }
9100                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9101                    } else {
9102                        // Not inside a scrolling container, so show the feedback right away
9103                        setPressed(true);
9104                        checkForLongClick(0);
9105                    }
9106                    break;
9107
9108                case MotionEvent.ACTION_CANCEL:
9109                    setPressed(false);
9110                    removeTapCallback();
9111                    removeLongPressCallback();
9112                    break;
9113
9114                case MotionEvent.ACTION_MOVE:
9115                    final int x = (int) event.getX();
9116                    final int y = (int) event.getY();
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            if (mBackground != null && mBackground.supportsHotspots()) {
9133                manageTouchHotspot(event);
9134            }
9135
9136            return true;
9137        }
9138
9139        return false;
9140    }
9141
9142    private void manageTouchHotspot(MotionEvent event) {
9143        switch (event.getAction()) {
9144            case MotionEvent.ACTION_DOWN:
9145            case MotionEvent.ACTION_POINTER_DOWN: {
9146                final int index = event.getActionIndex();
9147                setPointerHotspot(event, index);
9148            } break;
9149            case MotionEvent.ACTION_MOVE: {
9150                final int count = event.getPointerCount();
9151                for (int index = 0; index < count; index++) {
9152                    setPointerHotspot(event, index);
9153                }
9154            } break;
9155            case MotionEvent.ACTION_POINTER_UP: {
9156                final int actionIndex = event.getActionIndex();
9157                final int pointerId = event.getPointerId(actionIndex);
9158                mBackground.removeHotspot(pointerId);
9159            } break;
9160            case MotionEvent.ACTION_UP:
9161            case MotionEvent.ACTION_CANCEL:
9162                mBackground.clearHotspots();
9163                break;
9164        }
9165    }
9166
9167    private void setPointerHotspot(MotionEvent event, int index) {
9168        final int id = event.getPointerId(index);
9169        final float x = event.getX(index);
9170        final float y = event.getY(index);
9171        mBackground.setHotspot(id, x, y);
9172    }
9173
9174    /**
9175     * @hide
9176     */
9177    public boolean isInScrollingContainer() {
9178        ViewParent p = getParent();
9179        while (p != null && p instanceof ViewGroup) {
9180            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9181                return true;
9182            }
9183            p = p.getParent();
9184        }
9185        return false;
9186    }
9187
9188    /**
9189     * Remove the longpress detection timer.
9190     */
9191    private void removeLongPressCallback() {
9192        if (mPendingCheckForLongPress != null) {
9193          removeCallbacks(mPendingCheckForLongPress);
9194        }
9195    }
9196
9197    /**
9198     * Remove the pending click action
9199     */
9200    private void removePerformClickCallback() {
9201        if (mPerformClick != null) {
9202            removeCallbacks(mPerformClick);
9203        }
9204    }
9205
9206    /**
9207     * Remove the prepress detection timer.
9208     */
9209    private void removeUnsetPressCallback() {
9210        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9211            setPressed(false);
9212            removeCallbacks(mUnsetPressedState);
9213        }
9214    }
9215
9216    /**
9217     * Remove the tap detection timer.
9218     */
9219    private void removeTapCallback() {
9220        if (mPendingCheckForTap != null) {
9221            mPrivateFlags &= ~PFLAG_PREPRESSED;
9222            removeCallbacks(mPendingCheckForTap);
9223        }
9224    }
9225
9226    /**
9227     * Cancels a pending long press.  Your subclass can use this if you
9228     * want the context menu to come up if the user presses and holds
9229     * at the same place, but you don't want it to come up if they press
9230     * and then move around enough to cause scrolling.
9231     */
9232    public void cancelLongPress() {
9233        removeLongPressCallback();
9234
9235        /*
9236         * The prepressed state handled by the tap callback is a display
9237         * construct, but the tap callback will post a long press callback
9238         * less its own timeout. Remove it here.
9239         */
9240        removeTapCallback();
9241    }
9242
9243    /**
9244     * Remove the pending callback for sending a
9245     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9246     */
9247    private void removeSendViewScrolledAccessibilityEventCallback() {
9248        if (mSendViewScrolledAccessibilityEvent != null) {
9249            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9250            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9251        }
9252    }
9253
9254    /**
9255     * Sets the TouchDelegate for this View.
9256     */
9257    public void setTouchDelegate(TouchDelegate delegate) {
9258        mTouchDelegate = delegate;
9259    }
9260
9261    /**
9262     * Gets the TouchDelegate for this View.
9263     */
9264    public TouchDelegate getTouchDelegate() {
9265        return mTouchDelegate;
9266    }
9267
9268    /**
9269     * Set flags controlling behavior of this view.
9270     *
9271     * @param flags Constant indicating the value which should be set
9272     * @param mask Constant indicating the bit range that should be changed
9273     */
9274    void setFlags(int flags, int mask) {
9275        final boolean accessibilityEnabled =
9276                AccessibilityManager.getInstance(mContext).isEnabled();
9277        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9278
9279        int old = mViewFlags;
9280        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9281
9282        int changed = mViewFlags ^ old;
9283        if (changed == 0) {
9284            return;
9285        }
9286        int privateFlags = mPrivateFlags;
9287
9288        /* Check if the FOCUSABLE bit has changed */
9289        if (((changed & FOCUSABLE_MASK) != 0) &&
9290                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9291            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9292                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9293                /* Give up focus if we are no longer focusable */
9294                clearFocus();
9295            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9296                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9297                /*
9298                 * Tell the view system that we are now available to take focus
9299                 * if no one else already has it.
9300                 */
9301                if (mParent != null) mParent.focusableViewAvailable(this);
9302            }
9303        }
9304
9305        final int newVisibility = flags & VISIBILITY_MASK;
9306        if (newVisibility == VISIBLE) {
9307            if ((changed & VISIBILITY_MASK) != 0) {
9308                /*
9309                 * If this view is becoming visible, invalidate it in case it changed while
9310                 * it was not visible. Marking it drawn ensures that the invalidation will
9311                 * go through.
9312                 */
9313                mPrivateFlags |= PFLAG_DRAWN;
9314                invalidate(true);
9315
9316                needGlobalAttributesUpdate(true);
9317
9318                // a view becoming visible is worth notifying the parent
9319                // about in case nothing has focus.  even if this specific view
9320                // isn't focusable, it may contain something that is, so let
9321                // the root view try to give this focus if nothing else does.
9322                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9323                    mParent.focusableViewAvailable(this);
9324                }
9325            }
9326        }
9327
9328        /* Check if the GONE bit has changed */
9329        if ((changed & GONE) != 0) {
9330            needGlobalAttributesUpdate(false);
9331            requestLayout();
9332
9333            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9334                if (hasFocus()) clearFocus();
9335                clearAccessibilityFocus();
9336                destroyDrawingCache();
9337                if (mParent instanceof View) {
9338                    // GONE views noop invalidation, so invalidate the parent
9339                    ((View) mParent).invalidate(true);
9340                }
9341                // Mark the view drawn to ensure that it gets invalidated properly the next
9342                // time it is visible and gets invalidated
9343                mPrivateFlags |= PFLAG_DRAWN;
9344            }
9345            if (mAttachInfo != null) {
9346                mAttachInfo.mViewVisibilityChanged = true;
9347            }
9348        }
9349
9350        /* Check if the VISIBLE bit has changed */
9351        if ((changed & INVISIBLE) != 0) {
9352            needGlobalAttributesUpdate(false);
9353            /*
9354             * If this view is becoming invisible, set the DRAWN flag so that
9355             * the next invalidate() will not be skipped.
9356             */
9357            mPrivateFlags |= PFLAG_DRAWN;
9358
9359            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9360                // root view becoming invisible shouldn't clear focus and accessibility focus
9361                if (getRootView() != this) {
9362                    if (hasFocus()) clearFocus();
9363                    clearAccessibilityFocus();
9364                }
9365            }
9366            if (mAttachInfo != null) {
9367                mAttachInfo.mViewVisibilityChanged = true;
9368            }
9369        }
9370
9371        if ((changed & VISIBILITY_MASK) != 0) {
9372            // If the view is invisible, cleanup its display list to free up resources
9373            if (newVisibility != VISIBLE) {
9374                cleanupDraw();
9375            }
9376
9377            if (mParent instanceof ViewGroup) {
9378                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9379                        (changed & VISIBILITY_MASK), newVisibility);
9380                ((View) mParent).invalidate(true);
9381            } else if (mParent != null) {
9382                mParent.invalidateChild(this, null);
9383            }
9384            dispatchVisibilityChanged(this, newVisibility);
9385        }
9386
9387        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9388            destroyDrawingCache();
9389        }
9390
9391        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9392            destroyDrawingCache();
9393            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9394            invalidateParentCaches();
9395        }
9396
9397        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9398            destroyDrawingCache();
9399            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9400        }
9401
9402        if ((changed & DRAW_MASK) != 0) {
9403            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9404                if (mBackground != null) {
9405                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9406                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9407                } else {
9408                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9409                }
9410            } else {
9411                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9412            }
9413            requestLayout();
9414            invalidate(true);
9415        }
9416
9417        if ((changed & KEEP_SCREEN_ON) != 0) {
9418            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9419                mParent.recomputeViewAttributes(this);
9420            }
9421        }
9422
9423        if (accessibilityEnabled) {
9424            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9425                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9426                if (oldIncludeForAccessibility != includeForAccessibility()) {
9427                    notifySubtreeAccessibilityStateChangedIfNeeded();
9428                } else {
9429                    notifyViewAccessibilityStateChangedIfNeeded(
9430                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9431                }
9432            } else if ((changed & ENABLED_MASK) != 0) {
9433                notifyViewAccessibilityStateChangedIfNeeded(
9434                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9435            }
9436        }
9437    }
9438
9439    /**
9440     * Change the view's z order in the tree, so it's on top of other sibling
9441     * views. This ordering change may affect layout, if the parent container
9442     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9443     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9444     * method should be followed by calls to {@link #requestLayout()} and
9445     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9446     * with the new child ordering.
9447     *
9448     * @see ViewGroup#bringChildToFront(View)
9449     */
9450    public void bringToFront() {
9451        if (mParent != null) {
9452            mParent.bringChildToFront(this);
9453        }
9454    }
9455
9456    /**
9457     * This is called in response to an internal scroll in this view (i.e., the
9458     * view scrolled its own contents). This is typically as a result of
9459     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9460     * called.
9461     *
9462     * @param l Current horizontal scroll origin.
9463     * @param t Current vertical scroll origin.
9464     * @param oldl Previous horizontal scroll origin.
9465     * @param oldt Previous vertical scroll origin.
9466     */
9467    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9468        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9469            postSendViewScrolledAccessibilityEventCallback();
9470        }
9471
9472        mBackgroundSizeChanged = true;
9473
9474        final AttachInfo ai = mAttachInfo;
9475        if (ai != null) {
9476            ai.mViewScrollChanged = true;
9477        }
9478    }
9479
9480    /**
9481     * Interface definition for a callback to be invoked when the layout bounds of a view
9482     * changes due to layout processing.
9483     */
9484    public interface OnLayoutChangeListener {
9485        /**
9486         * Called when the layout bounds of a view changes due to layout processing.
9487         *
9488         * @param v The view whose bounds have changed.
9489         * @param left The new value of the view's left property.
9490         * @param top The new value of the view's top property.
9491         * @param right The new value of the view's right property.
9492         * @param bottom The new value of the view's bottom property.
9493         * @param oldLeft The previous value of the view's left property.
9494         * @param oldTop The previous value of the view's top property.
9495         * @param oldRight The previous value of the view's right property.
9496         * @param oldBottom The previous value of the view's bottom property.
9497         */
9498        void onLayoutChange(View v, int left, int top, int right, int bottom,
9499            int oldLeft, int oldTop, int oldRight, int oldBottom);
9500    }
9501
9502    /**
9503     * This is called during layout when the size of this view has changed. If
9504     * you were just added to the view hierarchy, you're called with the old
9505     * values of 0.
9506     *
9507     * @param w Current width of this view.
9508     * @param h Current height of this view.
9509     * @param oldw Old width of this view.
9510     * @param oldh Old height of this view.
9511     */
9512    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9513    }
9514
9515    /**
9516     * Called by draw to draw the child views. This may be overridden
9517     * by derived classes to gain control just before its children are drawn
9518     * (but after its own view has been drawn).
9519     * @param canvas the canvas on which to draw the view
9520     */
9521    protected void dispatchDraw(Canvas canvas) {
9522
9523    }
9524
9525    /**
9526     * Gets the parent of this view. Note that the parent is a
9527     * ViewParent and not necessarily a View.
9528     *
9529     * @return Parent of this view.
9530     */
9531    public final ViewParent getParent() {
9532        return mParent;
9533    }
9534
9535    /**
9536     * Set the horizontal scrolled position of your view. This will cause a call to
9537     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9538     * invalidated.
9539     * @param value the x position to scroll to
9540     */
9541    public void setScrollX(int value) {
9542        scrollTo(value, mScrollY);
9543    }
9544
9545    /**
9546     * Set the vertical scrolled position of your view. This will cause a call to
9547     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9548     * invalidated.
9549     * @param value the y position to scroll to
9550     */
9551    public void setScrollY(int value) {
9552        scrollTo(mScrollX, value);
9553    }
9554
9555    /**
9556     * Return the scrolled left position of this view. This is the left edge of
9557     * the displayed part of your view. You do not need to draw any pixels
9558     * farther left, since those are outside of the frame of your view on
9559     * screen.
9560     *
9561     * @return The left edge of the displayed part of your view, in pixels.
9562     */
9563    public final int getScrollX() {
9564        return mScrollX;
9565    }
9566
9567    /**
9568     * Return the scrolled top position of this view. This is the top edge of
9569     * the displayed part of your view. You do not need to draw any pixels above
9570     * it, since those are outside of the frame of your view on screen.
9571     *
9572     * @return The top edge of the displayed part of your view, in pixels.
9573     */
9574    public final int getScrollY() {
9575        return mScrollY;
9576    }
9577
9578    /**
9579     * Return the width of the your view.
9580     *
9581     * @return The width of your view, in pixels.
9582     */
9583    @ViewDebug.ExportedProperty(category = "layout")
9584    public final int getWidth() {
9585        return mRight - mLeft;
9586    }
9587
9588    /**
9589     * Return the height of your view.
9590     *
9591     * @return The height of your view, in pixels.
9592     */
9593    @ViewDebug.ExportedProperty(category = "layout")
9594    public final int getHeight() {
9595        return mBottom - mTop;
9596    }
9597
9598    /**
9599     * Return the visible drawing bounds of your view. Fills in the output
9600     * rectangle with the values from getScrollX(), getScrollY(),
9601     * getWidth(), and getHeight(). These bounds do not account for any
9602     * transformation properties currently set on the view, such as
9603     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9604     *
9605     * @param outRect The (scrolled) drawing bounds of the view.
9606     */
9607    public void getDrawingRect(Rect outRect) {
9608        outRect.left = mScrollX;
9609        outRect.top = mScrollY;
9610        outRect.right = mScrollX + (mRight - mLeft);
9611        outRect.bottom = mScrollY + (mBottom - mTop);
9612    }
9613
9614    /**
9615     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9616     * raw width component (that is the result is masked by
9617     * {@link #MEASURED_SIZE_MASK}).
9618     *
9619     * @return The raw measured width of this view.
9620     */
9621    public final int getMeasuredWidth() {
9622        return mMeasuredWidth & MEASURED_SIZE_MASK;
9623    }
9624
9625    /**
9626     * Return the full width measurement information for this view as computed
9627     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9628     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9629     * This should be used during measurement and layout calculations only. Use
9630     * {@link #getWidth()} to see how wide a view is after layout.
9631     *
9632     * @return The measured width of this view as a bit mask.
9633     */
9634    public final int getMeasuredWidthAndState() {
9635        return mMeasuredWidth;
9636    }
9637
9638    /**
9639     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9640     * raw width component (that is the result is masked by
9641     * {@link #MEASURED_SIZE_MASK}).
9642     *
9643     * @return The raw measured height of this view.
9644     */
9645    public final int getMeasuredHeight() {
9646        return mMeasuredHeight & MEASURED_SIZE_MASK;
9647    }
9648
9649    /**
9650     * Return the full height measurement information for this view as computed
9651     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9652     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9653     * This should be used during measurement and layout calculations only. Use
9654     * {@link #getHeight()} to see how wide a view is after layout.
9655     *
9656     * @return The measured width of this view as a bit mask.
9657     */
9658    public final int getMeasuredHeightAndState() {
9659        return mMeasuredHeight;
9660    }
9661
9662    /**
9663     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9664     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9665     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9666     * and the height component is at the shifted bits
9667     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9668     */
9669    public final int getMeasuredState() {
9670        return (mMeasuredWidth&MEASURED_STATE_MASK)
9671                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9672                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9673    }
9674
9675    /**
9676     * The transform matrix of this view, which is calculated based on the current
9677     * roation, scale, and pivot properties.
9678     *
9679     * @see #getRotation()
9680     * @see #getScaleX()
9681     * @see #getScaleY()
9682     * @see #getPivotX()
9683     * @see #getPivotY()
9684     * @return The current transform matrix for the view
9685     */
9686    public Matrix getMatrix() {
9687        if (mTransformationInfo != null) {
9688            updateMatrix();
9689            return mTransformationInfo.mMatrix;
9690        }
9691        return Matrix.IDENTITY_MATRIX;
9692    }
9693
9694    /**
9695     * Utility function to determine if the value is far enough away from zero to be
9696     * considered non-zero.
9697     * @param value A floating point value to check for zero-ness
9698     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9699     */
9700    private static boolean nonzero(float value) {
9701        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9702    }
9703
9704    /**
9705     * Returns true if the transform matrix is the identity matrix.
9706     * Recomputes the matrix if necessary.
9707     *
9708     * @return True if the transform matrix is the identity matrix, false otherwise.
9709     */
9710    final boolean hasIdentityMatrix() {
9711        if (mTransformationInfo != null) {
9712            updateMatrix();
9713            return mTransformationInfo.mMatrixIsIdentity;
9714        }
9715        return true;
9716    }
9717
9718    void ensureTransformationInfo() {
9719        if (mTransformationInfo == null) {
9720            mTransformationInfo = new TransformationInfo();
9721        }
9722    }
9723
9724    /**
9725     * Recomputes the transform matrix if necessary.
9726     */
9727    private void updateMatrix() {
9728        final TransformationInfo info = mTransformationInfo;
9729        if (info == null) {
9730            return;
9731        }
9732        if (info.mMatrixDirty) {
9733            // transform-related properties have changed since the last time someone
9734            // asked for the matrix; recalculate it with the current values
9735
9736            // Figure out if we need to update the pivot point
9737            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9738                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9739                    info.mPrevWidth = mRight - mLeft;
9740                    info.mPrevHeight = mBottom - mTop;
9741                    info.mPivotX = info.mPrevWidth / 2f;
9742                    info.mPivotY = info.mPrevHeight / 2f;
9743                }
9744            }
9745            info.mMatrix.reset();
9746            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9747                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9748                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9749                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9750            } else {
9751                if (info.mCamera == null) {
9752                    info.mCamera = new Camera();
9753                    info.matrix3D = new Matrix();
9754                }
9755                info.mCamera.save();
9756                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9757                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9758                info.mCamera.getMatrix(info.matrix3D);
9759                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9760                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9761                        info.mPivotY + info.mTranslationY);
9762                info.mMatrix.postConcat(info.matrix3D);
9763                info.mCamera.restore();
9764            }
9765            info.mMatrixDirty = false;
9766            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9767            info.mInverseMatrixDirty = true;
9768        }
9769    }
9770
9771   /**
9772     * Utility method to retrieve the inverse of the current mMatrix property.
9773     * We cache the matrix to avoid recalculating it when transform properties
9774     * have not changed.
9775     *
9776     * @return The inverse of the current matrix of this view.
9777     */
9778    final Matrix getInverseMatrix() {
9779        final TransformationInfo info = mTransformationInfo;
9780        if (info != null) {
9781            updateMatrix();
9782            if (info.mInverseMatrixDirty) {
9783                if (info.mInverseMatrix == null) {
9784                    info.mInverseMatrix = new Matrix();
9785                }
9786                info.mMatrix.invert(info.mInverseMatrix);
9787                info.mInverseMatrixDirty = false;
9788            }
9789            return info.mInverseMatrix;
9790        }
9791        return Matrix.IDENTITY_MATRIX;
9792    }
9793
9794    /**
9795     * Gets the distance along the Z axis from the camera to this view.
9796     *
9797     * @see #setCameraDistance(float)
9798     *
9799     * @return The distance along the Z axis.
9800     */
9801    public float getCameraDistance() {
9802        ensureTransformationInfo();
9803        final float dpi = mResources.getDisplayMetrics().densityDpi;
9804        final TransformationInfo info = mTransformationInfo;
9805        if (info.mCamera == null) {
9806            info.mCamera = new Camera();
9807            info.matrix3D = new Matrix();
9808        }
9809        return -(info.mCamera.getLocationZ() * dpi);
9810    }
9811
9812    /**
9813     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9814     * views are drawn) from the camera to this view. The camera's distance
9815     * affects 3D transformations, for instance rotations around the X and Y
9816     * axis. If the rotationX or rotationY properties are changed and this view is
9817     * large (more than half the size of the screen), it is recommended to always
9818     * use a camera distance that's greater than the height (X axis rotation) or
9819     * the width (Y axis rotation) of this view.</p>
9820     *
9821     * <p>The distance of the camera from the view plane can have an affect on the
9822     * perspective distortion of the view when it is rotated around the x or y axis.
9823     * For example, a large distance will result in a large viewing angle, and there
9824     * will not be much perspective distortion of the view as it rotates. A short
9825     * distance may cause much more perspective distortion upon rotation, and can
9826     * also result in some drawing artifacts if the rotated view ends up partially
9827     * behind the camera (which is why the recommendation is to use a distance at
9828     * least as far as the size of the view, if the view is to be rotated.)</p>
9829     *
9830     * <p>The distance is expressed in "depth pixels." The default distance depends
9831     * on the screen density. For instance, on a medium density display, the
9832     * default distance is 1280. On a high density display, the default distance
9833     * is 1920.</p>
9834     *
9835     * <p>If you want to specify a distance that leads to visually consistent
9836     * results across various densities, use the following formula:</p>
9837     * <pre>
9838     * float scale = context.getResources().getDisplayMetrics().density;
9839     * view.setCameraDistance(distance * scale);
9840     * </pre>
9841     *
9842     * <p>The density scale factor of a high density display is 1.5,
9843     * and 1920 = 1280 * 1.5.</p>
9844     *
9845     * @param distance The distance in "depth pixels", if negative the opposite
9846     *        value is used
9847     *
9848     * @see #setRotationX(float)
9849     * @see #setRotationY(float)
9850     */
9851    public void setCameraDistance(float distance) {
9852        invalidateViewProperty(true, false);
9853
9854        ensureTransformationInfo();
9855        final float dpi = mResources.getDisplayMetrics().densityDpi;
9856        final TransformationInfo info = mTransformationInfo;
9857        if (info.mCamera == null) {
9858            info.mCamera = new Camera();
9859            info.matrix3D = new Matrix();
9860        }
9861
9862        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9863        info.mMatrixDirty = true;
9864
9865        invalidateViewProperty(false, false);
9866        if (mDisplayList != null) {
9867            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9868        }
9869        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9870            // View was rejected last time it was drawn by its parent; this may have changed
9871            invalidateParentIfNeeded();
9872        }
9873    }
9874
9875    /**
9876     * The degrees that the view is rotated around the pivot point.
9877     *
9878     * @see #setRotation(float)
9879     * @see #getPivotX()
9880     * @see #getPivotY()
9881     *
9882     * @return The degrees of rotation.
9883     */
9884    @ViewDebug.ExportedProperty(category = "drawing")
9885    public float getRotation() {
9886        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9887    }
9888
9889    /**
9890     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9891     * result in clockwise rotation.
9892     *
9893     * @param rotation The degrees of rotation.
9894     *
9895     * @see #getRotation()
9896     * @see #getPivotX()
9897     * @see #getPivotY()
9898     * @see #setRotationX(float)
9899     * @see #setRotationY(float)
9900     *
9901     * @attr ref android.R.styleable#View_rotation
9902     */
9903    public void setRotation(float rotation) {
9904        ensureTransformationInfo();
9905        final TransformationInfo info = mTransformationInfo;
9906        if (info.mRotation != rotation) {
9907            // Double-invalidation is necessary to capture view's old and new areas
9908            invalidateViewProperty(true, false);
9909            info.mRotation = rotation;
9910            info.mMatrixDirty = true;
9911            invalidateViewProperty(false, true);
9912            if (mDisplayList != null) {
9913                mDisplayList.setRotation(rotation);
9914            }
9915            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9916                // View was rejected last time it was drawn by its parent; this may have changed
9917                invalidateParentIfNeeded();
9918            }
9919        }
9920    }
9921
9922    /**
9923     * The degrees that the view is rotated around the vertical axis through the pivot point.
9924     *
9925     * @see #getPivotX()
9926     * @see #getPivotY()
9927     * @see #setRotationY(float)
9928     *
9929     * @return The degrees of Y rotation.
9930     */
9931    @ViewDebug.ExportedProperty(category = "drawing")
9932    public float getRotationY() {
9933        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9934    }
9935
9936    /**
9937     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9938     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9939     * down the y axis.
9940     *
9941     * When rotating large views, it is recommended to adjust the camera distance
9942     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9943     *
9944     * @param rotationY The degrees of Y rotation.
9945     *
9946     * @see #getRotationY()
9947     * @see #getPivotX()
9948     * @see #getPivotY()
9949     * @see #setRotation(float)
9950     * @see #setRotationX(float)
9951     * @see #setCameraDistance(float)
9952     *
9953     * @attr ref android.R.styleable#View_rotationY
9954     */
9955    public void setRotationY(float rotationY) {
9956        ensureTransformationInfo();
9957        final TransformationInfo info = mTransformationInfo;
9958        if (info.mRotationY != rotationY) {
9959            invalidateViewProperty(true, false);
9960            info.mRotationY = rotationY;
9961            info.mMatrixDirty = true;
9962            invalidateViewProperty(false, true);
9963            if (mDisplayList != null) {
9964                mDisplayList.setRotationY(rotationY);
9965            }
9966            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9967                // View was rejected last time it was drawn by its parent; this may have changed
9968                invalidateParentIfNeeded();
9969            }
9970        }
9971    }
9972
9973    /**
9974     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9975     *
9976     * @see #getPivotX()
9977     * @see #getPivotY()
9978     * @see #setRotationX(float)
9979     *
9980     * @return The degrees of X rotation.
9981     */
9982    @ViewDebug.ExportedProperty(category = "drawing")
9983    public float getRotationX() {
9984        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9985    }
9986
9987    /**
9988     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9989     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9990     * x axis.
9991     *
9992     * When rotating large views, it is recommended to adjust the camera distance
9993     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9994     *
9995     * @param rotationX The degrees of X rotation.
9996     *
9997     * @see #getRotationX()
9998     * @see #getPivotX()
9999     * @see #getPivotY()
10000     * @see #setRotation(float)
10001     * @see #setRotationY(float)
10002     * @see #setCameraDistance(float)
10003     *
10004     * @attr ref android.R.styleable#View_rotationX
10005     */
10006    public void setRotationX(float rotationX) {
10007        ensureTransformationInfo();
10008        final TransformationInfo info = mTransformationInfo;
10009        if (info.mRotationX != rotationX) {
10010            invalidateViewProperty(true, false);
10011            info.mRotationX = rotationX;
10012            info.mMatrixDirty = true;
10013            invalidateViewProperty(false, true);
10014            if (mDisplayList != null) {
10015                mDisplayList.setRotationX(rotationX);
10016            }
10017            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10018                // View was rejected last time it was drawn by its parent; this may have changed
10019                invalidateParentIfNeeded();
10020            }
10021        }
10022    }
10023
10024    /**
10025     * The amount that the view is scaled in x around the pivot point, as a proportion of
10026     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10027     *
10028     * <p>By default, this is 1.0f.
10029     *
10030     * @see #getPivotX()
10031     * @see #getPivotY()
10032     * @return The scaling factor.
10033     */
10034    @ViewDebug.ExportedProperty(category = "drawing")
10035    public float getScaleX() {
10036        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
10037    }
10038
10039    /**
10040     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10041     * the view's unscaled width. A value of 1 means that no scaling is applied.
10042     *
10043     * @param scaleX The scaling factor.
10044     * @see #getPivotX()
10045     * @see #getPivotY()
10046     *
10047     * @attr ref android.R.styleable#View_scaleX
10048     */
10049    public void setScaleX(float scaleX) {
10050        ensureTransformationInfo();
10051        final TransformationInfo info = mTransformationInfo;
10052        if (info.mScaleX != scaleX) {
10053            invalidateViewProperty(true, false);
10054            info.mScaleX = scaleX;
10055            info.mMatrixDirty = true;
10056            invalidateViewProperty(false, true);
10057            if (mDisplayList != null) {
10058                mDisplayList.setScaleX(scaleX);
10059            }
10060            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10061                // View was rejected last time it was drawn by its parent; this may have changed
10062                invalidateParentIfNeeded();
10063            }
10064        }
10065    }
10066
10067    /**
10068     * The amount that the view is scaled in y around the pivot point, as a proportion of
10069     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10070     *
10071     * <p>By default, this is 1.0f.
10072     *
10073     * @see #getPivotX()
10074     * @see #getPivotY()
10075     * @return The scaling factor.
10076     */
10077    @ViewDebug.ExportedProperty(category = "drawing")
10078    public float getScaleY() {
10079        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
10080    }
10081
10082    /**
10083     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10084     * the view's unscaled width. A value of 1 means that no scaling is applied.
10085     *
10086     * @param scaleY The scaling factor.
10087     * @see #getPivotX()
10088     * @see #getPivotY()
10089     *
10090     * @attr ref android.R.styleable#View_scaleY
10091     */
10092    public void setScaleY(float scaleY) {
10093        ensureTransformationInfo();
10094        final TransformationInfo info = mTransformationInfo;
10095        if (info.mScaleY != scaleY) {
10096            invalidateViewProperty(true, false);
10097            info.mScaleY = scaleY;
10098            info.mMatrixDirty = true;
10099            invalidateViewProperty(false, true);
10100            if (mDisplayList != null) {
10101                mDisplayList.setScaleY(scaleY);
10102            }
10103            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10104                // View was rejected last time it was drawn by its parent; this may have changed
10105                invalidateParentIfNeeded();
10106            }
10107        }
10108    }
10109
10110    /**
10111     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10112     * and {@link #setScaleX(float) scaled}.
10113     *
10114     * @see #getRotation()
10115     * @see #getScaleX()
10116     * @see #getScaleY()
10117     * @see #getPivotY()
10118     * @return The x location of the pivot point.
10119     *
10120     * @attr ref android.R.styleable#View_transformPivotX
10121     */
10122    @ViewDebug.ExportedProperty(category = "drawing")
10123    public float getPivotX() {
10124        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
10125    }
10126
10127    /**
10128     * Sets the x location of the point around which the view is
10129     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10130     * By default, the pivot point is centered on the object.
10131     * Setting this property disables this behavior and causes the view to use only the
10132     * explicitly set pivotX and pivotY values.
10133     *
10134     * @param pivotX The x location of the pivot point.
10135     * @see #getRotation()
10136     * @see #getScaleX()
10137     * @see #getScaleY()
10138     * @see #getPivotY()
10139     *
10140     * @attr ref android.R.styleable#View_transformPivotX
10141     */
10142    public void setPivotX(float pivotX) {
10143        ensureTransformationInfo();
10144        final TransformationInfo info = mTransformationInfo;
10145        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10146                PFLAG_PIVOT_EXPLICITLY_SET;
10147        if (info.mPivotX != pivotX || !pivotSet) {
10148            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10149            invalidateViewProperty(true, false);
10150            info.mPivotX = pivotX;
10151            info.mMatrixDirty = true;
10152            invalidateViewProperty(false, true);
10153            if (mDisplayList != null) {
10154                mDisplayList.setPivotX(pivotX);
10155            }
10156            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10157                // View was rejected last time it was drawn by its parent; this may have changed
10158                invalidateParentIfNeeded();
10159            }
10160        }
10161    }
10162
10163    /**
10164     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10165     * and {@link #setScaleY(float) scaled}.
10166     *
10167     * @see #getRotation()
10168     * @see #getScaleX()
10169     * @see #getScaleY()
10170     * @see #getPivotY()
10171     * @return The y location of the pivot point.
10172     *
10173     * @attr ref android.R.styleable#View_transformPivotY
10174     */
10175    @ViewDebug.ExportedProperty(category = "drawing")
10176    public float getPivotY() {
10177        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
10178    }
10179
10180    /**
10181     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10182     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10183     * Setting this property disables this behavior and causes the view to use only the
10184     * explicitly set pivotX and pivotY values.
10185     *
10186     * @param pivotY The y location of the pivot point.
10187     * @see #getRotation()
10188     * @see #getScaleX()
10189     * @see #getScaleY()
10190     * @see #getPivotY()
10191     *
10192     * @attr ref android.R.styleable#View_transformPivotY
10193     */
10194    public void setPivotY(float pivotY) {
10195        ensureTransformationInfo();
10196        final TransformationInfo info = mTransformationInfo;
10197        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10198                PFLAG_PIVOT_EXPLICITLY_SET;
10199        if (info.mPivotY != pivotY || !pivotSet) {
10200            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10201            invalidateViewProperty(true, false);
10202            info.mPivotY = pivotY;
10203            info.mMatrixDirty = true;
10204            invalidateViewProperty(false, true);
10205            if (mDisplayList != null) {
10206                mDisplayList.setPivotY(pivotY);
10207            }
10208            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10209                // View was rejected last time it was drawn by its parent; this may have changed
10210                invalidateParentIfNeeded();
10211            }
10212        }
10213    }
10214
10215    /**
10216     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10217     * completely transparent and 1 means the view is completely opaque.
10218     *
10219     * <p>By default this is 1.0f.
10220     * @return The opacity of the view.
10221     */
10222    @ViewDebug.ExportedProperty(category = "drawing")
10223    public float getAlpha() {
10224        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10225    }
10226
10227    /**
10228     * Returns whether this View has content which overlaps.
10229     *
10230     * <p>This function, intended to be overridden by specific View types, is an optimization when
10231     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10232     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10233     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10234     * directly. An example of overlapping rendering is a TextView with a background image, such as
10235     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10236     * ImageView with only the foreground image. The default implementation returns true; subclasses
10237     * should override if they have cases which can be optimized.</p>
10238     *
10239     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10240     * necessitates that a View return true if it uses the methods internally without passing the
10241     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10242     *
10243     * @return true if the content in this view might overlap, false otherwise.
10244     */
10245    public boolean hasOverlappingRendering() {
10246        return true;
10247    }
10248
10249    /**
10250     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10251     * completely transparent and 1 means the view is completely opaque.</p>
10252     *
10253     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10254     * performance implications, especially for large views. It is best to use the alpha property
10255     * sparingly and transiently, as in the case of fading animations.</p>
10256     *
10257     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10258     * strongly recommended for performance reasons to either override
10259     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10260     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10261     *
10262     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10263     * responsible for applying the opacity itself.</p>
10264     *
10265     * <p>Note that if the view is backed by a
10266     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10267     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10268     * 1.0 will supercede the alpha of the layer paint.</p>
10269     *
10270     * @param alpha The opacity of the view.
10271     *
10272     * @see #hasOverlappingRendering()
10273     * @see #setLayerType(int, android.graphics.Paint)
10274     *
10275     * @attr ref android.R.styleable#View_alpha
10276     */
10277    public void setAlpha(float alpha) {
10278        ensureTransformationInfo();
10279        if (mTransformationInfo.mAlpha != alpha) {
10280            mTransformationInfo.mAlpha = alpha;
10281            if (onSetAlpha((int) (alpha * 255))) {
10282                mPrivateFlags |= PFLAG_ALPHA_SET;
10283                // subclass is handling alpha - don't optimize rendering cache invalidation
10284                invalidateParentCaches();
10285                invalidate(true);
10286            } else {
10287                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10288                invalidateViewProperty(true, false);
10289                if (mDisplayList != null) {
10290                    mDisplayList.setAlpha(getFinalAlpha());
10291                }
10292            }
10293        }
10294    }
10295
10296    /**
10297     * Faster version of setAlpha() which performs the same steps except there are
10298     * no calls to invalidate(). The caller of this function should perform proper invalidation
10299     * on the parent and this object. The return value indicates whether the subclass handles
10300     * alpha (the return value for onSetAlpha()).
10301     *
10302     * @param alpha The new value for the alpha property
10303     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10304     *         the new value for the alpha property is different from the old value
10305     */
10306    boolean setAlphaNoInvalidation(float alpha) {
10307        ensureTransformationInfo();
10308        if (mTransformationInfo.mAlpha != alpha) {
10309            mTransformationInfo.mAlpha = alpha;
10310            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10311            if (subclassHandlesAlpha) {
10312                mPrivateFlags |= PFLAG_ALPHA_SET;
10313                return true;
10314            } else {
10315                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10316                if (mDisplayList != null) {
10317                    mDisplayList.setAlpha(getFinalAlpha());
10318                }
10319            }
10320        }
10321        return false;
10322    }
10323
10324    /**
10325     * This property is hidden and intended only for use by the Fade transition, which
10326     * animates it to produce a visual translucency that does not side-effect (or get
10327     * affected by) the real alpha property. This value is composited with the other
10328     * alpha value (and the AlphaAnimation value, when that is present) to produce
10329     * a final visual translucency result, which is what is passed into the DisplayList.
10330     *
10331     * @hide
10332     */
10333    public void setTransitionAlpha(float alpha) {
10334        ensureTransformationInfo();
10335        if (mTransformationInfo.mTransitionAlpha != alpha) {
10336            mTransformationInfo.mTransitionAlpha = alpha;
10337            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10338            invalidateViewProperty(true, false);
10339            if (mDisplayList != null) {
10340                mDisplayList.setAlpha(getFinalAlpha());
10341            }
10342        }
10343    }
10344
10345    /**
10346     * Calculates the visual alpha of this view, which is a combination of the actual
10347     * alpha value and the transitionAlpha value (if set).
10348     */
10349    private float getFinalAlpha() {
10350        if (mTransformationInfo != null) {
10351            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10352        }
10353        return 1;
10354    }
10355
10356    /**
10357     * This property is hidden and intended only for use by the Fade transition, which
10358     * animates it to produce a visual translucency that does not side-effect (or get
10359     * affected by) the real alpha property. This value is composited with the other
10360     * alpha value (and the AlphaAnimation value, when that is present) to produce
10361     * a final visual translucency result, which is what is passed into the DisplayList.
10362     *
10363     * @hide
10364     */
10365    public float getTransitionAlpha() {
10366        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10367    }
10368
10369    /**
10370     * Top position of this view relative to its parent.
10371     *
10372     * @return The top of this view, in pixels.
10373     */
10374    @ViewDebug.CapturedViewProperty
10375    public final int getTop() {
10376        return mTop;
10377    }
10378
10379    /**
10380     * Sets the top position of this view relative to its parent. This method is meant to be called
10381     * by the layout system and should not generally be called otherwise, because the property
10382     * may be changed at any time by the layout.
10383     *
10384     * @param top The top of this view, in pixels.
10385     */
10386    public final void setTop(int top) {
10387        if (top != mTop) {
10388            updateMatrix();
10389            final boolean matrixIsIdentity = mTransformationInfo == null
10390                    || mTransformationInfo.mMatrixIsIdentity;
10391            if (matrixIsIdentity) {
10392                if (mAttachInfo != null) {
10393                    int minTop;
10394                    int yLoc;
10395                    if (top < mTop) {
10396                        minTop = top;
10397                        yLoc = top - mTop;
10398                    } else {
10399                        minTop = mTop;
10400                        yLoc = 0;
10401                    }
10402                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10403                }
10404            } else {
10405                // Double-invalidation is necessary to capture view's old and new areas
10406                invalidate(true);
10407            }
10408
10409            int width = mRight - mLeft;
10410            int oldHeight = mBottom - mTop;
10411
10412            mTop = top;
10413            if (mDisplayList != null) {
10414                mDisplayList.setTop(mTop);
10415            }
10416
10417            sizeChange(width, mBottom - mTop, width, oldHeight);
10418
10419            if (!matrixIsIdentity) {
10420                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10421                    // A change in dimension means an auto-centered pivot point changes, too
10422                    mTransformationInfo.mMatrixDirty = true;
10423                }
10424                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10425                invalidate(true);
10426            }
10427            mBackgroundSizeChanged = true;
10428            invalidateParentIfNeeded();
10429            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10430                // View was rejected last time it was drawn by its parent; this may have changed
10431                invalidateParentIfNeeded();
10432            }
10433        }
10434    }
10435
10436    /**
10437     * Bottom position of this view relative to its parent.
10438     *
10439     * @return The bottom of this view, in pixels.
10440     */
10441    @ViewDebug.CapturedViewProperty
10442    public final int getBottom() {
10443        return mBottom;
10444    }
10445
10446    /**
10447     * True if this view has changed since the last time being drawn.
10448     *
10449     * @return The dirty state of this view.
10450     */
10451    public boolean isDirty() {
10452        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10453    }
10454
10455    /**
10456     * Sets the bottom position of this view relative to its parent. This method is meant to be
10457     * called by the layout system and should not generally be called otherwise, because the
10458     * property may be changed at any time by the layout.
10459     *
10460     * @param bottom The bottom of this view, in pixels.
10461     */
10462    public final void setBottom(int bottom) {
10463        if (bottom != mBottom) {
10464            updateMatrix();
10465            final boolean matrixIsIdentity = mTransformationInfo == null
10466                    || mTransformationInfo.mMatrixIsIdentity;
10467            if (matrixIsIdentity) {
10468                if (mAttachInfo != null) {
10469                    int maxBottom;
10470                    if (bottom < mBottom) {
10471                        maxBottom = mBottom;
10472                    } else {
10473                        maxBottom = bottom;
10474                    }
10475                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10476                }
10477            } else {
10478                // Double-invalidation is necessary to capture view's old and new areas
10479                invalidate(true);
10480            }
10481
10482            int width = mRight - mLeft;
10483            int oldHeight = mBottom - mTop;
10484
10485            mBottom = bottom;
10486            if (mDisplayList != null) {
10487                mDisplayList.setBottom(mBottom);
10488            }
10489
10490            sizeChange(width, mBottom - mTop, width, oldHeight);
10491
10492            if (!matrixIsIdentity) {
10493                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10494                    // A change in dimension means an auto-centered pivot point changes, too
10495                    mTransformationInfo.mMatrixDirty = true;
10496                }
10497                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10498                invalidate(true);
10499            }
10500            mBackgroundSizeChanged = true;
10501            invalidateParentIfNeeded();
10502            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10503                // View was rejected last time it was drawn by its parent; this may have changed
10504                invalidateParentIfNeeded();
10505            }
10506        }
10507    }
10508
10509    /**
10510     * Left position of this view relative to its parent.
10511     *
10512     * @return The left edge of this view, in pixels.
10513     */
10514    @ViewDebug.CapturedViewProperty
10515    public final int getLeft() {
10516        return mLeft;
10517    }
10518
10519    /**
10520     * Sets the left position of this view relative to its parent. This method is meant to be called
10521     * by the layout system and should not generally be called otherwise, because the property
10522     * may be changed at any time by the layout.
10523     *
10524     * @param left The bottom of this view, in pixels.
10525     */
10526    public final void setLeft(int left) {
10527        if (left != mLeft) {
10528            updateMatrix();
10529            final boolean matrixIsIdentity = mTransformationInfo == null
10530                    || mTransformationInfo.mMatrixIsIdentity;
10531            if (matrixIsIdentity) {
10532                if (mAttachInfo != null) {
10533                    int minLeft;
10534                    int xLoc;
10535                    if (left < mLeft) {
10536                        minLeft = left;
10537                        xLoc = left - mLeft;
10538                    } else {
10539                        minLeft = mLeft;
10540                        xLoc = 0;
10541                    }
10542                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10543                }
10544            } else {
10545                // Double-invalidation is necessary to capture view's old and new areas
10546                invalidate(true);
10547            }
10548
10549            int oldWidth = mRight - mLeft;
10550            int height = mBottom - mTop;
10551
10552            mLeft = left;
10553            if (mDisplayList != null) {
10554                mDisplayList.setLeft(left);
10555            }
10556
10557            sizeChange(mRight - mLeft, height, oldWidth, height);
10558
10559            if (!matrixIsIdentity) {
10560                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10561                    // A change in dimension means an auto-centered pivot point changes, too
10562                    mTransformationInfo.mMatrixDirty = true;
10563                }
10564                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10565                invalidate(true);
10566            }
10567            mBackgroundSizeChanged = true;
10568            invalidateParentIfNeeded();
10569            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10570                // View was rejected last time it was drawn by its parent; this may have changed
10571                invalidateParentIfNeeded();
10572            }
10573        }
10574    }
10575
10576    /**
10577     * Right position of this view relative to its parent.
10578     *
10579     * @return The right edge of this view, in pixels.
10580     */
10581    @ViewDebug.CapturedViewProperty
10582    public final int getRight() {
10583        return mRight;
10584    }
10585
10586    /**
10587     * Sets the right position of this view relative to its parent. This method is meant to be called
10588     * by the layout system and should not generally be called otherwise, because the property
10589     * may be changed at any time by the layout.
10590     *
10591     * @param right The bottom of this view, in pixels.
10592     */
10593    public final void setRight(int right) {
10594        if (right != mRight) {
10595            updateMatrix();
10596            final boolean matrixIsIdentity = mTransformationInfo == null
10597                    || mTransformationInfo.mMatrixIsIdentity;
10598            if (matrixIsIdentity) {
10599                if (mAttachInfo != null) {
10600                    int maxRight;
10601                    if (right < mRight) {
10602                        maxRight = mRight;
10603                    } else {
10604                        maxRight = right;
10605                    }
10606                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10607                }
10608            } else {
10609                // Double-invalidation is necessary to capture view's old and new areas
10610                invalidate(true);
10611            }
10612
10613            int oldWidth = mRight - mLeft;
10614            int height = mBottom - mTop;
10615
10616            mRight = right;
10617            if (mDisplayList != null) {
10618                mDisplayList.setRight(mRight);
10619            }
10620
10621            sizeChange(mRight - mLeft, height, oldWidth, height);
10622
10623            if (!matrixIsIdentity) {
10624                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10625                    // A change in dimension means an auto-centered pivot point changes, too
10626                    mTransformationInfo.mMatrixDirty = true;
10627                }
10628                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10629                invalidate(true);
10630            }
10631            mBackgroundSizeChanged = true;
10632            invalidateParentIfNeeded();
10633            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10634                // View was rejected last time it was drawn by its parent; this may have changed
10635                invalidateParentIfNeeded();
10636            }
10637        }
10638    }
10639
10640    /**
10641     * The visual x position of this view, in pixels. This is equivalent to the
10642     * {@link #setTranslationX(float) translationX} property plus the current
10643     * {@link #getLeft() left} property.
10644     *
10645     * @return The visual x position of this view, in pixels.
10646     */
10647    @ViewDebug.ExportedProperty(category = "drawing")
10648    public float getX() {
10649        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10650    }
10651
10652    /**
10653     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10654     * {@link #setTranslationX(float) translationX} property to be the difference between
10655     * the x value passed in and the current {@link #getLeft() left} property.
10656     *
10657     * @param x The visual x position of this view, in pixels.
10658     */
10659    public void setX(float x) {
10660        setTranslationX(x - mLeft);
10661    }
10662
10663    /**
10664     * The visual y position of this view, in pixels. This is equivalent to the
10665     * {@link #setTranslationY(float) translationY} property plus the current
10666     * {@link #getTop() top} property.
10667     *
10668     * @return The visual y position of this view, in pixels.
10669     */
10670    @ViewDebug.ExportedProperty(category = "drawing")
10671    public float getY() {
10672        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10673    }
10674
10675    /**
10676     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10677     * {@link #setTranslationY(float) translationY} property to be the difference between
10678     * the y value passed in and the current {@link #getTop() top} property.
10679     *
10680     * @param y The visual y position of this view, in pixels.
10681     */
10682    public void setY(float y) {
10683        setTranslationY(y - mTop);
10684    }
10685
10686
10687    /**
10688     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10689     * This position is post-layout, in addition to wherever the object's
10690     * layout placed it.
10691     *
10692     * @return The horizontal position of this view relative to its left position, in pixels.
10693     */
10694    @ViewDebug.ExportedProperty(category = "drawing")
10695    public float getTranslationX() {
10696        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10697    }
10698
10699    /**
10700     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10701     * This effectively positions the object post-layout, in addition to wherever the object's
10702     * layout placed it.
10703     *
10704     * @param translationX The horizontal position of this view relative to its left position,
10705     * in pixels.
10706     *
10707     * @attr ref android.R.styleable#View_translationX
10708     */
10709    public void setTranslationX(float translationX) {
10710        ensureTransformationInfo();
10711        final TransformationInfo info = mTransformationInfo;
10712        if (info.mTranslationX != translationX) {
10713            // Double-invalidation is necessary to capture view's old and new areas
10714            invalidateViewProperty(true, false);
10715            info.mTranslationX = translationX;
10716            info.mMatrixDirty = true;
10717            invalidateViewProperty(false, true);
10718            if (mDisplayList != null) {
10719                mDisplayList.setTranslationX(translationX);
10720            }
10721            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10722                // View was rejected last time it was drawn by its parent; this may have changed
10723                invalidateParentIfNeeded();
10724            }
10725        }
10726    }
10727
10728    /**
10729     * The vertical location of this view relative to its {@link #getTop() top} position.
10730     * This position is post-layout, in addition to wherever the object's
10731     * layout placed it.
10732     *
10733     * @return The vertical position of this view relative to its top position,
10734     * in pixels.
10735     */
10736    @ViewDebug.ExportedProperty(category = "drawing")
10737    public float getTranslationY() {
10738        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10739    }
10740
10741    /**
10742     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10743     * This effectively positions the object post-layout, in addition to wherever the object's
10744     * layout placed it.
10745     *
10746     * @param translationY The vertical position of this view relative to its top position,
10747     * in pixels.
10748     *
10749     * @attr ref android.R.styleable#View_translationY
10750     */
10751    public void setTranslationY(float translationY) {
10752        ensureTransformationInfo();
10753        final TransformationInfo info = mTransformationInfo;
10754        if (info.mTranslationY != translationY) {
10755            invalidateViewProperty(true, false);
10756            info.mTranslationY = translationY;
10757            info.mMatrixDirty = true;
10758            invalidateViewProperty(false, true);
10759            if (mDisplayList != null) {
10760                mDisplayList.setTranslationY(translationY);
10761            }
10762            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10763                // View was rejected last time it was drawn by its parent; this may have changed
10764                invalidateParentIfNeeded();
10765            }
10766        }
10767    }
10768
10769    /**
10770     * The depth location of this view relative to its parent.
10771     *
10772     * @return The depth of this view relative to its parent.
10773     */
10774    @ViewDebug.ExportedProperty(category = "drawing")
10775    public float getTranslationZ() {
10776        return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0;
10777    }
10778
10779    /**
10780     * Sets the depth location of this view relative to its parent.
10781     *
10782     * @attr ref android.R.styleable#View_translationZ
10783     */
10784    public void setTranslationZ(float translationZ) {
10785        ensureTransformationInfo();
10786        final TransformationInfo info = mTransformationInfo;
10787        if (info.mTranslationZ != translationZ) {
10788            invalidateViewProperty(true, false);
10789            info.mTranslationZ = translationZ;
10790            info.mMatrixDirty = true;
10791            invalidateViewProperty(false, true);
10792            if (mDisplayList != null) {
10793                mDisplayList.setTranslationZ(translationZ);
10794            }
10795            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10796                // View was rejected last time it was drawn by its parent; this may have changed
10797                invalidateParentIfNeeded();
10798            }
10799        }
10800    }
10801
10802    /**
10803     * @hide
10804     */
10805    public final void getOutline(Path outline) {
10806        if (mOutline == null) {
10807            outline.reset();
10808        } else {
10809            outline.set(mOutline);
10810        }
10811    }
10812
10813    /**
10814     * @hide
10815     */
10816    public void setOutline(Path path) {
10817        // always copy the path since caller may reuse
10818        if (mOutline == null) {
10819            mOutline = new Path(path);
10820        } else {
10821            mOutline.set(path);
10822        }
10823
10824        if (mDisplayList != null) {
10825            mDisplayList.setOutline(path);
10826        }
10827    }
10828
10829    /**
10830     * Hit rectangle in parent's coordinates
10831     *
10832     * @param outRect The hit rectangle of the view.
10833     */
10834    public void getHitRect(Rect outRect) {
10835        updateMatrix();
10836        final TransformationInfo info = mTransformationInfo;
10837        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10838            outRect.set(mLeft, mTop, mRight, mBottom);
10839        } else {
10840            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10841            tmpRect.set(0, 0, getWidth(), getHeight());
10842            info.mMatrix.mapRect(tmpRect);
10843            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10844                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10845        }
10846    }
10847
10848    /**
10849     * Determines whether the given point, in local coordinates is inside the view.
10850     */
10851    /*package*/ final boolean pointInView(float localX, float localY) {
10852        return localX >= 0 && localX < (mRight - mLeft)
10853                && localY >= 0 && localY < (mBottom - mTop);
10854    }
10855
10856    /**
10857     * Utility method to determine whether the given point, in local coordinates,
10858     * is inside the view, where the area of the view is expanded by the slop factor.
10859     * This method is called while processing touch-move events to determine if the event
10860     * is still within the view.
10861     *
10862     * @hide
10863     */
10864    public boolean pointInView(float localX, float localY, float slop) {
10865        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10866                localY < ((mBottom - mTop) + slop);
10867    }
10868
10869    /**
10870     * When a view has focus and the user navigates away from it, the next view is searched for
10871     * starting from the rectangle filled in by this method.
10872     *
10873     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10874     * of the view.  However, if your view maintains some idea of internal selection,
10875     * such as a cursor, or a selected row or column, you should override this method and
10876     * fill in a more specific rectangle.
10877     *
10878     * @param r The rectangle to fill in, in this view's coordinates.
10879     */
10880    public void getFocusedRect(Rect r) {
10881        getDrawingRect(r);
10882    }
10883
10884    /**
10885     * If some part of this view is not clipped by any of its parents, then
10886     * return that area in r in global (root) coordinates. To convert r to local
10887     * coordinates (without taking possible View rotations into account), offset
10888     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10889     * If the view is completely clipped or translated out, return false.
10890     *
10891     * @param r If true is returned, r holds the global coordinates of the
10892     *        visible portion of this view.
10893     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10894     *        between this view and its root. globalOffet may be null.
10895     * @return true if r is non-empty (i.e. part of the view is visible at the
10896     *         root level.
10897     */
10898    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10899        int width = mRight - mLeft;
10900        int height = mBottom - mTop;
10901        if (width > 0 && height > 0) {
10902            r.set(0, 0, width, height);
10903            if (globalOffset != null) {
10904                globalOffset.set(-mScrollX, -mScrollY);
10905            }
10906            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10907        }
10908        return false;
10909    }
10910
10911    public final boolean getGlobalVisibleRect(Rect r) {
10912        return getGlobalVisibleRect(r, null);
10913    }
10914
10915    public final boolean getLocalVisibleRect(Rect r) {
10916        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10917        if (getGlobalVisibleRect(r, offset)) {
10918            r.offset(-offset.x, -offset.y); // make r local
10919            return true;
10920        }
10921        return false;
10922    }
10923
10924    /**
10925     * Offset this view's vertical location by the specified number of pixels.
10926     *
10927     * @param offset the number of pixels to offset the view by
10928     */
10929    public void offsetTopAndBottom(int offset) {
10930        if (offset != 0) {
10931            updateMatrix();
10932            final boolean matrixIsIdentity = mTransformationInfo == null
10933                    || mTransformationInfo.mMatrixIsIdentity;
10934            if (matrixIsIdentity) {
10935                if (mDisplayList != null) {
10936                    invalidateViewProperty(false, false);
10937                } else {
10938                    final ViewParent p = mParent;
10939                    if (p != null && mAttachInfo != null) {
10940                        final Rect r = mAttachInfo.mTmpInvalRect;
10941                        int minTop;
10942                        int maxBottom;
10943                        int yLoc;
10944                        if (offset < 0) {
10945                            minTop = mTop + offset;
10946                            maxBottom = mBottom;
10947                            yLoc = offset;
10948                        } else {
10949                            minTop = mTop;
10950                            maxBottom = mBottom + offset;
10951                            yLoc = 0;
10952                        }
10953                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10954                        p.invalidateChild(this, r);
10955                    }
10956                }
10957            } else {
10958                invalidateViewProperty(false, false);
10959            }
10960
10961            mTop += offset;
10962            mBottom += offset;
10963            if (mDisplayList != null) {
10964                mDisplayList.offsetTopAndBottom(offset);
10965                invalidateViewProperty(false, false);
10966            } else {
10967                if (!matrixIsIdentity) {
10968                    invalidateViewProperty(false, true);
10969                }
10970                invalidateParentIfNeeded();
10971            }
10972        }
10973    }
10974
10975    /**
10976     * Offset this view's horizontal location by the specified amount of pixels.
10977     *
10978     * @param offset the number of pixels to offset the view by
10979     */
10980    public void offsetLeftAndRight(int offset) {
10981        if (offset != 0) {
10982            updateMatrix();
10983            final boolean matrixIsIdentity = mTransformationInfo == null
10984                    || mTransformationInfo.mMatrixIsIdentity;
10985            if (matrixIsIdentity) {
10986                if (mDisplayList != null) {
10987                    invalidateViewProperty(false, false);
10988                } else {
10989                    final ViewParent p = mParent;
10990                    if (p != null && mAttachInfo != null) {
10991                        final Rect r = mAttachInfo.mTmpInvalRect;
10992                        int minLeft;
10993                        int maxRight;
10994                        if (offset < 0) {
10995                            minLeft = mLeft + offset;
10996                            maxRight = mRight;
10997                        } else {
10998                            minLeft = mLeft;
10999                            maxRight = mRight + offset;
11000                        }
11001                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11002                        p.invalidateChild(this, r);
11003                    }
11004                }
11005            } else {
11006                invalidateViewProperty(false, false);
11007            }
11008
11009            mLeft += offset;
11010            mRight += offset;
11011            if (mDisplayList != null) {
11012                mDisplayList.offsetLeftAndRight(offset);
11013                invalidateViewProperty(false, false);
11014            } else {
11015                if (!matrixIsIdentity) {
11016                    invalidateViewProperty(false, true);
11017                }
11018                invalidateParentIfNeeded();
11019            }
11020        }
11021    }
11022
11023    /**
11024     * Get the LayoutParams associated with this view. All views should have
11025     * layout parameters. These supply parameters to the <i>parent</i> of this
11026     * view specifying how it should be arranged. There are many subclasses of
11027     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11028     * of ViewGroup that are responsible for arranging their children.
11029     *
11030     * This method may return null if this View is not attached to a parent
11031     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11032     * was not invoked successfully. When a View is attached to a parent
11033     * ViewGroup, this method must not return null.
11034     *
11035     * @return The LayoutParams associated with this view, or null if no
11036     *         parameters have been set yet
11037     */
11038    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11039    public ViewGroup.LayoutParams getLayoutParams() {
11040        return mLayoutParams;
11041    }
11042
11043    /**
11044     * Set the layout parameters associated with this view. These supply
11045     * parameters to the <i>parent</i> of this view specifying how it should be
11046     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11047     * correspond to the different subclasses of ViewGroup that are responsible
11048     * for arranging their children.
11049     *
11050     * @param params The layout parameters for this view, cannot be null
11051     */
11052    public void setLayoutParams(ViewGroup.LayoutParams params) {
11053        if (params == null) {
11054            throw new NullPointerException("Layout parameters cannot be null");
11055        }
11056        mLayoutParams = params;
11057        resolveLayoutParams();
11058        if (mParent instanceof ViewGroup) {
11059            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11060        }
11061        requestLayout();
11062    }
11063
11064    /**
11065     * Resolve the layout parameters depending on the resolved layout direction
11066     *
11067     * @hide
11068     */
11069    public void resolveLayoutParams() {
11070        if (mLayoutParams != null) {
11071            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11072        }
11073    }
11074
11075    /**
11076     * Set the scrolled position of your view. This will cause a call to
11077     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11078     * invalidated.
11079     * @param x the x position to scroll to
11080     * @param y the y position to scroll to
11081     */
11082    public void scrollTo(int x, int y) {
11083        if (mScrollX != x || mScrollY != y) {
11084            int oldX = mScrollX;
11085            int oldY = mScrollY;
11086            mScrollX = x;
11087            mScrollY = y;
11088            invalidateParentCaches();
11089            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11090            if (!awakenScrollBars()) {
11091                postInvalidateOnAnimation();
11092            }
11093        }
11094    }
11095
11096    /**
11097     * Move the scrolled position of your view. This will cause a call to
11098     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11099     * invalidated.
11100     * @param x the amount of pixels to scroll by horizontally
11101     * @param y the amount of pixels to scroll by vertically
11102     */
11103    public void scrollBy(int x, int y) {
11104        scrollTo(mScrollX + x, mScrollY + y);
11105    }
11106
11107    /**
11108     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11109     * animation to fade the scrollbars out after a default delay. If a subclass
11110     * provides animated scrolling, the start delay should equal the duration
11111     * of the scrolling animation.</p>
11112     *
11113     * <p>The animation starts only if at least one of the scrollbars is
11114     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11115     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11116     * this method returns true, and false otherwise. If the animation is
11117     * started, this method calls {@link #invalidate()}; in that case the
11118     * caller should not call {@link #invalidate()}.</p>
11119     *
11120     * <p>This method should be invoked every time a subclass directly updates
11121     * the scroll parameters.</p>
11122     *
11123     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11124     * and {@link #scrollTo(int, int)}.</p>
11125     *
11126     * @return true if the animation is played, false otherwise
11127     *
11128     * @see #awakenScrollBars(int)
11129     * @see #scrollBy(int, int)
11130     * @see #scrollTo(int, int)
11131     * @see #isHorizontalScrollBarEnabled()
11132     * @see #isVerticalScrollBarEnabled()
11133     * @see #setHorizontalScrollBarEnabled(boolean)
11134     * @see #setVerticalScrollBarEnabled(boolean)
11135     */
11136    protected boolean awakenScrollBars() {
11137        return mScrollCache != null &&
11138                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11139    }
11140
11141    /**
11142     * Trigger the scrollbars to draw.
11143     * This method differs from awakenScrollBars() only in its default duration.
11144     * initialAwakenScrollBars() will show the scroll bars for longer than
11145     * usual to give the user more of a chance to notice them.
11146     *
11147     * @return true if the animation is played, false otherwise.
11148     */
11149    private boolean initialAwakenScrollBars() {
11150        return mScrollCache != null &&
11151                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11152    }
11153
11154    /**
11155     * <p>
11156     * Trigger the scrollbars to draw. When invoked this method starts an
11157     * animation to fade the scrollbars out after a fixed delay. If a subclass
11158     * provides animated scrolling, the start delay should equal the duration of
11159     * the scrolling animation.
11160     * </p>
11161     *
11162     * <p>
11163     * The animation starts only if at least one of the scrollbars is enabled,
11164     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11165     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11166     * this method returns true, and false otherwise. If the animation is
11167     * started, this method calls {@link #invalidate()}; in that case the caller
11168     * should not call {@link #invalidate()}.
11169     * </p>
11170     *
11171     * <p>
11172     * This method should be invoked everytime a subclass directly updates the
11173     * scroll parameters.
11174     * </p>
11175     *
11176     * @param startDelay the delay, in milliseconds, after which the animation
11177     *        should start; when the delay is 0, the animation starts
11178     *        immediately
11179     * @return true if the animation is played, false otherwise
11180     *
11181     * @see #scrollBy(int, int)
11182     * @see #scrollTo(int, int)
11183     * @see #isHorizontalScrollBarEnabled()
11184     * @see #isVerticalScrollBarEnabled()
11185     * @see #setHorizontalScrollBarEnabled(boolean)
11186     * @see #setVerticalScrollBarEnabled(boolean)
11187     */
11188    protected boolean awakenScrollBars(int startDelay) {
11189        return awakenScrollBars(startDelay, true);
11190    }
11191
11192    /**
11193     * <p>
11194     * Trigger the scrollbars to draw. When invoked this method starts an
11195     * animation to fade the scrollbars out after a fixed delay. If a subclass
11196     * provides animated scrolling, the start delay should equal the duration of
11197     * the scrolling animation.
11198     * </p>
11199     *
11200     * <p>
11201     * The animation starts only if at least one of the scrollbars is enabled,
11202     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11203     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11204     * this method returns true, and false otherwise. If the animation is
11205     * started, this method calls {@link #invalidate()} if the invalidate parameter
11206     * is set to true; in that case the caller
11207     * should not call {@link #invalidate()}.
11208     * </p>
11209     *
11210     * <p>
11211     * This method should be invoked everytime a subclass directly updates the
11212     * scroll parameters.
11213     * </p>
11214     *
11215     * @param startDelay the delay, in milliseconds, after which the animation
11216     *        should start; when the delay is 0, the animation starts
11217     *        immediately
11218     *
11219     * @param invalidate Wheter this method should call invalidate
11220     *
11221     * @return true if the animation is played, false otherwise
11222     *
11223     * @see #scrollBy(int, int)
11224     * @see #scrollTo(int, int)
11225     * @see #isHorizontalScrollBarEnabled()
11226     * @see #isVerticalScrollBarEnabled()
11227     * @see #setHorizontalScrollBarEnabled(boolean)
11228     * @see #setVerticalScrollBarEnabled(boolean)
11229     */
11230    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11231        final ScrollabilityCache scrollCache = mScrollCache;
11232
11233        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11234            return false;
11235        }
11236
11237        if (scrollCache.scrollBar == null) {
11238            scrollCache.scrollBar = new ScrollBarDrawable();
11239        }
11240
11241        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11242
11243            if (invalidate) {
11244                // Invalidate to show the scrollbars
11245                postInvalidateOnAnimation();
11246            }
11247
11248            if (scrollCache.state == ScrollabilityCache.OFF) {
11249                // FIXME: this is copied from WindowManagerService.
11250                // We should get this value from the system when it
11251                // is possible to do so.
11252                final int KEY_REPEAT_FIRST_DELAY = 750;
11253                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11254            }
11255
11256            // Tell mScrollCache when we should start fading. This may
11257            // extend the fade start time if one was already scheduled
11258            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11259            scrollCache.fadeStartTime = fadeStartTime;
11260            scrollCache.state = ScrollabilityCache.ON;
11261
11262            // Schedule our fader to run, unscheduling any old ones first
11263            if (mAttachInfo != null) {
11264                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11265                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11266            }
11267
11268            return true;
11269        }
11270
11271        return false;
11272    }
11273
11274    /**
11275     * Do not invalidate views which are not visible and which are not running an animation. They
11276     * will not get drawn and they should not set dirty flags as if they will be drawn
11277     */
11278    private boolean skipInvalidate() {
11279        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11280                (!(mParent instanceof ViewGroup) ||
11281                        !((ViewGroup) mParent).isViewTransitioning(this));
11282    }
11283    /**
11284     * Mark the area defined by dirty as needing to be drawn. If the view is
11285     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
11286     * in the future. This must be called from a UI thread. To call from a non-UI
11287     * thread, call {@link #postInvalidate()}.
11288     *
11289     * WARNING: This method is destructive to dirty.
11290     * @param dirty the rectangle representing the bounds of the dirty region
11291     */
11292    public void invalidate(Rect dirty) {
11293        if (skipInvalidate()) {
11294            return;
11295        }
11296        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11297                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
11298                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
11299            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11300            mPrivateFlags |= PFLAG_INVALIDATED;
11301            mPrivateFlags |= PFLAG_DIRTY;
11302            final ViewParent p = mParent;
11303            final AttachInfo ai = mAttachInfo;
11304            if (p != null && ai != null) {
11305                final int scrollX = mScrollX;
11306                final int scrollY = mScrollY;
11307                final Rect r = ai.mTmpInvalRect;
11308                r.set(dirty.left - scrollX, dirty.top - scrollY,
11309                        dirty.right - scrollX, dirty.bottom - scrollY);
11310                mParent.invalidateChild(this, r);
11311            }
11312        }
11313    }
11314
11315    /**
11316     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
11317     * The coordinates of the dirty rect are relative to the view.
11318     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
11319     * will be called at some point in the future. This must be called from
11320     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
11321     * @param l the left position of the dirty region
11322     * @param t the top position of the dirty region
11323     * @param r the right position of the dirty region
11324     * @param b the bottom position of the dirty region
11325     */
11326    public void invalidate(int l, int t, int r, int b) {
11327        if (skipInvalidate()) {
11328            return;
11329        }
11330        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11331                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
11332                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
11333            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11334            mPrivateFlags |= PFLAG_INVALIDATED;
11335            mPrivateFlags |= PFLAG_DIRTY;
11336            final ViewParent p = mParent;
11337            final AttachInfo ai = mAttachInfo;
11338            if (p != null && ai != null && l < r && t < b) {
11339                final int scrollX = mScrollX;
11340                final int scrollY = mScrollY;
11341                final Rect tmpr = ai.mTmpInvalRect;
11342                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
11343                p.invalidateChild(this, tmpr);
11344            }
11345        }
11346    }
11347
11348    /**
11349     * Invalidate the whole view. If the view is visible,
11350     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11351     * the future. This must be called from a UI thread. To call from a non-UI thread,
11352     * call {@link #postInvalidate()}.
11353     */
11354    public void invalidate() {
11355        invalidate(true);
11356    }
11357
11358    /**
11359     * This is where the invalidate() work actually happens. A full invalidate()
11360     * causes the drawing cache to be invalidated, but this function can be called with
11361     * invalidateCache set to false to skip that invalidation step for cases that do not
11362     * need it (for example, a component that remains at the same dimensions with the same
11363     * content).
11364     *
11365     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
11366     * well. This is usually true for a full invalidate, but may be set to false if the
11367     * View's contents or dimensions have not changed.
11368     */
11369    void invalidate(boolean invalidateCache) {
11370        if (skipInvalidate()) {
11371            return;
11372        }
11373        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
11374                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
11375                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
11376            mLastIsOpaque = isOpaque();
11377            mPrivateFlags &= ~PFLAG_DRAWN;
11378            mPrivateFlags |= PFLAG_DIRTY;
11379            if (invalidateCache) {
11380                mPrivateFlags |= PFLAG_INVALIDATED;
11381                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11382            }
11383            final AttachInfo ai = mAttachInfo;
11384            final ViewParent p = mParent;
11385
11386            if (p != null && ai != null) {
11387                final Rect r = ai.mTmpInvalRect;
11388                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11389                // Don't call invalidate -- we don't want to internally scroll
11390                // our own bounds
11391                p.invalidateChild(this, r);
11392            }
11393        }
11394    }
11395
11396    /**
11397     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11398     * set any flags or handle all of the cases handled by the default invalidation methods.
11399     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11400     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11401     * walk up the hierarchy, transforming the dirty rect as necessary.
11402     *
11403     * The method also handles normal invalidation logic if display list properties are not
11404     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11405     * backup approach, to handle these cases used in the various property-setting methods.
11406     *
11407     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11408     * are not being used in this view
11409     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11410     * list properties are not being used in this view
11411     */
11412    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11413        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11414            if (invalidateParent) {
11415                invalidateParentCaches();
11416            }
11417            if (forceRedraw) {
11418                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11419            }
11420            invalidate(false);
11421        } else {
11422            final AttachInfo ai = mAttachInfo;
11423            final ViewParent p = mParent;
11424            if (p != null && ai != null) {
11425                final Rect r = ai.mTmpInvalRect;
11426                r.set(0, 0, mRight - mLeft, mBottom - mTop);
11427                if (mParent instanceof ViewGroup) {
11428                    ((ViewGroup) mParent).invalidateChildFast(this, r);
11429                } else {
11430                    mParent.invalidateChild(this, r);
11431                }
11432            }
11433        }
11434    }
11435
11436    /**
11437     * Utility method to transform a given Rect by the current matrix of this view.
11438     */
11439    void transformRect(final Rect rect) {
11440        if (!getMatrix().isIdentity()) {
11441            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11442            boundingRect.set(rect);
11443            getMatrix().mapRect(boundingRect);
11444            rect.set((int) Math.floor(boundingRect.left),
11445                    (int) Math.floor(boundingRect.top),
11446                    (int) Math.ceil(boundingRect.right),
11447                    (int) Math.ceil(boundingRect.bottom));
11448        }
11449    }
11450
11451    /**
11452     * Used to indicate that the parent of this view should clear its caches. This functionality
11453     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11454     * which is necessary when various parent-managed properties of the view change, such as
11455     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11456     * clears the parent caches and does not causes an invalidate event.
11457     *
11458     * @hide
11459     */
11460    protected void invalidateParentCaches() {
11461        if (mParent instanceof View) {
11462            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11463        }
11464    }
11465
11466    /**
11467     * Used to indicate that the parent of this view should be invalidated. This functionality
11468     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11469     * which is necessary when various parent-managed properties of the view change, such as
11470     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11471     * an invalidation event to the parent.
11472     *
11473     * @hide
11474     */
11475    protected void invalidateParentIfNeeded() {
11476        if (isHardwareAccelerated() && mParent instanceof View) {
11477            ((View) mParent).invalidate(true);
11478        }
11479    }
11480
11481    /**
11482     * Indicates whether this View is opaque. An opaque View guarantees that it will
11483     * draw all the pixels overlapping its bounds using a fully opaque color.
11484     *
11485     * Subclasses of View should override this method whenever possible to indicate
11486     * whether an instance is opaque. Opaque Views are treated in a special way by
11487     * the View hierarchy, possibly allowing it to perform optimizations during
11488     * invalidate/draw passes.
11489     *
11490     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11491     */
11492    @ViewDebug.ExportedProperty(category = "drawing")
11493    public boolean isOpaque() {
11494        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11495                getFinalAlpha() >= 1.0f;
11496    }
11497
11498    /**
11499     * @hide
11500     */
11501    protected void computeOpaqueFlags() {
11502        // Opaque if:
11503        //   - Has a background
11504        //   - Background is opaque
11505        //   - Doesn't have scrollbars or scrollbars overlay
11506
11507        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11508            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11509        } else {
11510            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11511        }
11512
11513        final int flags = mViewFlags;
11514        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11515                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11516                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11517            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11518        } else {
11519            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11520        }
11521    }
11522
11523    /**
11524     * @hide
11525     */
11526    protected boolean hasOpaqueScrollbars() {
11527        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11528    }
11529
11530    /**
11531     * @return A handler associated with the thread running the View. This
11532     * handler can be used to pump events in the UI events queue.
11533     */
11534    public Handler getHandler() {
11535        final AttachInfo attachInfo = mAttachInfo;
11536        if (attachInfo != null) {
11537            return attachInfo.mHandler;
11538        }
11539        return null;
11540    }
11541
11542    /**
11543     * Gets the view root associated with the View.
11544     * @return The view root, or null if none.
11545     * @hide
11546     */
11547    public ViewRootImpl getViewRootImpl() {
11548        if (mAttachInfo != null) {
11549            return mAttachInfo.mViewRootImpl;
11550        }
11551        return null;
11552    }
11553
11554    /**
11555     * @hide
11556     */
11557    public HardwareRenderer getHardwareRenderer() {
11558        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11559    }
11560
11561    /**
11562     * <p>Causes the Runnable to be added to the message queue.
11563     * The runnable will be run on the user interface thread.</p>
11564     *
11565     * @param action The Runnable that will be executed.
11566     *
11567     * @return Returns true if the Runnable was successfully placed in to the
11568     *         message queue.  Returns false on failure, usually because the
11569     *         looper processing the message queue is exiting.
11570     *
11571     * @see #postDelayed
11572     * @see #removeCallbacks
11573     */
11574    public boolean post(Runnable action) {
11575        final AttachInfo attachInfo = mAttachInfo;
11576        if (attachInfo != null) {
11577            return attachInfo.mHandler.post(action);
11578        }
11579        // Assume that post will succeed later
11580        ViewRootImpl.getRunQueue().post(action);
11581        return true;
11582    }
11583
11584    /**
11585     * <p>Causes the Runnable to be added to the message queue, to be run
11586     * after the specified amount of time elapses.
11587     * The runnable will be run on the user interface thread.</p>
11588     *
11589     * @param action The Runnable that will be executed.
11590     * @param delayMillis The delay (in milliseconds) until the Runnable
11591     *        will be executed.
11592     *
11593     * @return true if the Runnable was successfully placed in to the
11594     *         message queue.  Returns false on failure, usually because the
11595     *         looper processing the message queue is exiting.  Note that a
11596     *         result of true does not mean the Runnable will be processed --
11597     *         if the looper is quit before the delivery time of the message
11598     *         occurs then the message will be dropped.
11599     *
11600     * @see #post
11601     * @see #removeCallbacks
11602     */
11603    public boolean postDelayed(Runnable action, long delayMillis) {
11604        final AttachInfo attachInfo = mAttachInfo;
11605        if (attachInfo != null) {
11606            return attachInfo.mHandler.postDelayed(action, delayMillis);
11607        }
11608        // Assume that post will succeed later
11609        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11610        return true;
11611    }
11612
11613    /**
11614     * <p>Causes the Runnable to execute on the next animation time step.
11615     * The runnable will be run on the user interface thread.</p>
11616     *
11617     * @param action The Runnable that will be executed.
11618     *
11619     * @see #postOnAnimationDelayed
11620     * @see #removeCallbacks
11621     */
11622    public void postOnAnimation(Runnable action) {
11623        final AttachInfo attachInfo = mAttachInfo;
11624        if (attachInfo != null) {
11625            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11626                    Choreographer.CALLBACK_ANIMATION, action, null);
11627        } else {
11628            // Assume that post will succeed later
11629            ViewRootImpl.getRunQueue().post(action);
11630        }
11631    }
11632
11633    /**
11634     * <p>Causes the Runnable to execute on the next animation time step,
11635     * after the specified amount of time elapses.
11636     * The runnable will be run on the user interface thread.</p>
11637     *
11638     * @param action The Runnable that will be executed.
11639     * @param delayMillis The delay (in milliseconds) until the Runnable
11640     *        will be executed.
11641     *
11642     * @see #postOnAnimation
11643     * @see #removeCallbacks
11644     */
11645    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11646        final AttachInfo attachInfo = mAttachInfo;
11647        if (attachInfo != null) {
11648            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11649                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11650        } else {
11651            // Assume that post will succeed later
11652            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11653        }
11654    }
11655
11656    /**
11657     * <p>Removes the specified Runnable from the message queue.</p>
11658     *
11659     * @param action The Runnable to remove from the message handling queue
11660     *
11661     * @return true if this view could ask the Handler to remove the Runnable,
11662     *         false otherwise. When the returned value is true, the Runnable
11663     *         may or may not have been actually removed from the message queue
11664     *         (for instance, if the Runnable was not in the queue already.)
11665     *
11666     * @see #post
11667     * @see #postDelayed
11668     * @see #postOnAnimation
11669     * @see #postOnAnimationDelayed
11670     */
11671    public boolean removeCallbacks(Runnable action) {
11672        if (action != null) {
11673            final AttachInfo attachInfo = mAttachInfo;
11674            if (attachInfo != null) {
11675                attachInfo.mHandler.removeCallbacks(action);
11676                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11677                        Choreographer.CALLBACK_ANIMATION, action, null);
11678            }
11679            // Assume that post will succeed later
11680            ViewRootImpl.getRunQueue().removeCallbacks(action);
11681        }
11682        return true;
11683    }
11684
11685    /**
11686     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11687     * Use this to invalidate the View from a non-UI thread.</p>
11688     *
11689     * <p>This method can be invoked from outside of the UI thread
11690     * only when this View is attached to a window.</p>
11691     *
11692     * @see #invalidate()
11693     * @see #postInvalidateDelayed(long)
11694     */
11695    public void postInvalidate() {
11696        postInvalidateDelayed(0);
11697    }
11698
11699    /**
11700     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11701     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11702     *
11703     * <p>This method can be invoked from outside of the UI thread
11704     * only when this View is attached to a window.</p>
11705     *
11706     * @param left The left coordinate of the rectangle to invalidate.
11707     * @param top The top coordinate of the rectangle to invalidate.
11708     * @param right The right coordinate of the rectangle to invalidate.
11709     * @param bottom The bottom coordinate of the rectangle to invalidate.
11710     *
11711     * @see #invalidate(int, int, int, int)
11712     * @see #invalidate(Rect)
11713     * @see #postInvalidateDelayed(long, int, int, int, int)
11714     */
11715    public void postInvalidate(int left, int top, int right, int bottom) {
11716        postInvalidateDelayed(0, left, top, right, bottom);
11717    }
11718
11719    /**
11720     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11721     * loop. Waits for the specified amount of time.</p>
11722     *
11723     * <p>This method can be invoked from outside of the UI thread
11724     * only when this View is attached to a window.</p>
11725     *
11726     * @param delayMilliseconds the duration in milliseconds to delay the
11727     *         invalidation by
11728     *
11729     * @see #invalidate()
11730     * @see #postInvalidate()
11731     */
11732    public void postInvalidateDelayed(long delayMilliseconds) {
11733        // We try only with the AttachInfo because there's no point in invalidating
11734        // if we are not attached to our window
11735        final AttachInfo attachInfo = mAttachInfo;
11736        if (attachInfo != null) {
11737            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11738        }
11739    }
11740
11741    /**
11742     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11743     * through the event loop. Waits for the specified amount of time.</p>
11744     *
11745     * <p>This method can be invoked from outside of the UI thread
11746     * only when this View is attached to a window.</p>
11747     *
11748     * @param delayMilliseconds the duration in milliseconds to delay the
11749     *         invalidation by
11750     * @param left The left coordinate of the rectangle to invalidate.
11751     * @param top The top coordinate of the rectangle to invalidate.
11752     * @param right The right coordinate of the rectangle to invalidate.
11753     * @param bottom The bottom coordinate of the rectangle to invalidate.
11754     *
11755     * @see #invalidate(int, int, int, int)
11756     * @see #invalidate(Rect)
11757     * @see #postInvalidate(int, int, int, int)
11758     */
11759    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11760            int right, int bottom) {
11761
11762        // We try only with the AttachInfo because there's no point in invalidating
11763        // if we are not attached to our window
11764        final AttachInfo attachInfo = mAttachInfo;
11765        if (attachInfo != null) {
11766            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11767            info.target = this;
11768            info.left = left;
11769            info.top = top;
11770            info.right = right;
11771            info.bottom = bottom;
11772
11773            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11774        }
11775    }
11776
11777    /**
11778     * <p>Cause an invalidate to happen on the next animation time step, typically the
11779     * next display frame.</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     * @see #invalidate()
11785     */
11786    public void postInvalidateOnAnimation() {
11787        // We try only with the AttachInfo because there's no point in invalidating
11788        // if we are not attached to our window
11789        final AttachInfo attachInfo = mAttachInfo;
11790        if (attachInfo != null) {
11791            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11792        }
11793    }
11794
11795    /**
11796     * <p>Cause an invalidate of the specified area to happen on the next animation
11797     * time step, typically the next display frame.</p>
11798     *
11799     * <p>This method can be invoked from outside of the UI thread
11800     * only when this View is attached to a window.</p>
11801     *
11802     * @param left The left coordinate of the rectangle to invalidate.
11803     * @param top The top coordinate of the rectangle to invalidate.
11804     * @param right The right coordinate of the rectangle to invalidate.
11805     * @param bottom The bottom coordinate of the rectangle to invalidate.
11806     *
11807     * @see #invalidate(int, int, int, int)
11808     * @see #invalidate(Rect)
11809     */
11810    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11811        // We try only with the AttachInfo because there's no point in invalidating
11812        // if we are not attached to our window
11813        final AttachInfo attachInfo = mAttachInfo;
11814        if (attachInfo != null) {
11815            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11816            info.target = this;
11817            info.left = left;
11818            info.top = top;
11819            info.right = right;
11820            info.bottom = bottom;
11821
11822            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11823        }
11824    }
11825
11826    /**
11827     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11828     * This event is sent at most once every
11829     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11830     */
11831    private void postSendViewScrolledAccessibilityEventCallback() {
11832        if (mSendViewScrolledAccessibilityEvent == null) {
11833            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11834        }
11835        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11836            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11837            postDelayed(mSendViewScrolledAccessibilityEvent,
11838                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11839        }
11840    }
11841
11842    /**
11843     * Called by a parent to request that a child update its values for mScrollX
11844     * and mScrollY if necessary. This will typically be done if the child is
11845     * animating a scroll using a {@link android.widget.Scroller Scroller}
11846     * object.
11847     */
11848    public void computeScroll() {
11849    }
11850
11851    /**
11852     * <p>Indicate whether the horizontal edges are faded when the view is
11853     * scrolled horizontally.</p>
11854     *
11855     * @return true if the horizontal edges should are faded on scroll, false
11856     *         otherwise
11857     *
11858     * @see #setHorizontalFadingEdgeEnabled(boolean)
11859     *
11860     * @attr ref android.R.styleable#View_requiresFadingEdge
11861     */
11862    public boolean isHorizontalFadingEdgeEnabled() {
11863        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11864    }
11865
11866    /**
11867     * <p>Define whether the horizontal edges should be faded when this view
11868     * is scrolled horizontally.</p>
11869     *
11870     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11871     *                                    be faded when the view is scrolled
11872     *                                    horizontally
11873     *
11874     * @see #isHorizontalFadingEdgeEnabled()
11875     *
11876     * @attr ref android.R.styleable#View_requiresFadingEdge
11877     */
11878    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11879        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11880            if (horizontalFadingEdgeEnabled) {
11881                initScrollCache();
11882            }
11883
11884            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11885        }
11886    }
11887
11888    /**
11889     * <p>Indicate whether the vertical edges are faded when the view is
11890     * scrolled horizontally.</p>
11891     *
11892     * @return true if the vertical edges should are faded on scroll, false
11893     *         otherwise
11894     *
11895     * @see #setVerticalFadingEdgeEnabled(boolean)
11896     *
11897     * @attr ref android.R.styleable#View_requiresFadingEdge
11898     */
11899    public boolean isVerticalFadingEdgeEnabled() {
11900        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11901    }
11902
11903    /**
11904     * <p>Define whether the vertical edges should be faded when this view
11905     * is scrolled vertically.</p>
11906     *
11907     * @param verticalFadingEdgeEnabled true if the vertical edges should
11908     *                                  be faded when the view is scrolled
11909     *                                  vertically
11910     *
11911     * @see #isVerticalFadingEdgeEnabled()
11912     *
11913     * @attr ref android.R.styleable#View_requiresFadingEdge
11914     */
11915    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11916        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11917            if (verticalFadingEdgeEnabled) {
11918                initScrollCache();
11919            }
11920
11921            mViewFlags ^= FADING_EDGE_VERTICAL;
11922        }
11923    }
11924
11925    /**
11926     * Returns the strength, or intensity, of the top faded edge. The strength is
11927     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11928     * returns 0.0 or 1.0 but no value in between.
11929     *
11930     * Subclasses should override this method to provide a smoother fade transition
11931     * when scrolling occurs.
11932     *
11933     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11934     */
11935    protected float getTopFadingEdgeStrength() {
11936        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11937    }
11938
11939    /**
11940     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11941     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11942     * returns 0.0 or 1.0 but no value in between.
11943     *
11944     * Subclasses should override this method to provide a smoother fade transition
11945     * when scrolling occurs.
11946     *
11947     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11948     */
11949    protected float getBottomFadingEdgeStrength() {
11950        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11951                computeVerticalScrollRange() ? 1.0f : 0.0f;
11952    }
11953
11954    /**
11955     * Returns the strength, or intensity, of the left faded edge. The strength is
11956     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11957     * returns 0.0 or 1.0 but no value in between.
11958     *
11959     * Subclasses should override this method to provide a smoother fade transition
11960     * when scrolling occurs.
11961     *
11962     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11963     */
11964    protected float getLeftFadingEdgeStrength() {
11965        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11966    }
11967
11968    /**
11969     * Returns the strength, or intensity, of the right faded edge. The strength is
11970     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11971     * returns 0.0 or 1.0 but no value in between.
11972     *
11973     * Subclasses should override this method to provide a smoother fade transition
11974     * when scrolling occurs.
11975     *
11976     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11977     */
11978    protected float getRightFadingEdgeStrength() {
11979        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11980                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11981    }
11982
11983    /**
11984     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11985     * scrollbar is not drawn by default.</p>
11986     *
11987     * @return true if the horizontal scrollbar should be painted, false
11988     *         otherwise
11989     *
11990     * @see #setHorizontalScrollBarEnabled(boolean)
11991     */
11992    public boolean isHorizontalScrollBarEnabled() {
11993        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11994    }
11995
11996    /**
11997     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11998     * scrollbar is not drawn by default.</p>
11999     *
12000     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12001     *                                   be painted
12002     *
12003     * @see #isHorizontalScrollBarEnabled()
12004     */
12005    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12006        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12007            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12008            computeOpaqueFlags();
12009            resolvePadding();
12010        }
12011    }
12012
12013    /**
12014     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12015     * scrollbar is not drawn by default.</p>
12016     *
12017     * @return true if the vertical scrollbar should be painted, false
12018     *         otherwise
12019     *
12020     * @see #setVerticalScrollBarEnabled(boolean)
12021     */
12022    public boolean isVerticalScrollBarEnabled() {
12023        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12024    }
12025
12026    /**
12027     * <p>Define whether the vertical scrollbar should be drawn or not. The
12028     * scrollbar is not drawn by default.</p>
12029     *
12030     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12031     *                                 be painted
12032     *
12033     * @see #isVerticalScrollBarEnabled()
12034     */
12035    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12036        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12037            mViewFlags ^= SCROLLBARS_VERTICAL;
12038            computeOpaqueFlags();
12039            resolvePadding();
12040        }
12041    }
12042
12043    /**
12044     * @hide
12045     */
12046    protected void recomputePadding() {
12047        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12048    }
12049
12050    /**
12051     * Define whether scrollbars will fade when the view is not scrolling.
12052     *
12053     * @param fadeScrollbars wheter to enable fading
12054     *
12055     * @attr ref android.R.styleable#View_fadeScrollbars
12056     */
12057    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12058        initScrollCache();
12059        final ScrollabilityCache scrollabilityCache = mScrollCache;
12060        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12061        if (fadeScrollbars) {
12062            scrollabilityCache.state = ScrollabilityCache.OFF;
12063        } else {
12064            scrollabilityCache.state = ScrollabilityCache.ON;
12065        }
12066    }
12067
12068    /**
12069     *
12070     * Returns true if scrollbars will fade when this view is not scrolling
12071     *
12072     * @return true if scrollbar fading is enabled
12073     *
12074     * @attr ref android.R.styleable#View_fadeScrollbars
12075     */
12076    public boolean isScrollbarFadingEnabled() {
12077        return mScrollCache != null && mScrollCache.fadeScrollBars;
12078    }
12079
12080    /**
12081     *
12082     * Returns the delay before scrollbars fade.
12083     *
12084     * @return the delay before scrollbars fade
12085     *
12086     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12087     */
12088    public int getScrollBarDefaultDelayBeforeFade() {
12089        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12090                mScrollCache.scrollBarDefaultDelayBeforeFade;
12091    }
12092
12093    /**
12094     * Define the delay before scrollbars fade.
12095     *
12096     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12097     *
12098     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12099     */
12100    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12101        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12102    }
12103
12104    /**
12105     *
12106     * Returns the scrollbar fade duration.
12107     *
12108     * @return the scrollbar fade duration
12109     *
12110     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12111     */
12112    public int getScrollBarFadeDuration() {
12113        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12114                mScrollCache.scrollBarFadeDuration;
12115    }
12116
12117    /**
12118     * Define the scrollbar fade duration.
12119     *
12120     * @param scrollBarFadeDuration - the scrollbar fade duration
12121     *
12122     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12123     */
12124    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12125        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12126    }
12127
12128    /**
12129     *
12130     * Returns the scrollbar size.
12131     *
12132     * @return the scrollbar size
12133     *
12134     * @attr ref android.R.styleable#View_scrollbarSize
12135     */
12136    public int getScrollBarSize() {
12137        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12138                mScrollCache.scrollBarSize;
12139    }
12140
12141    /**
12142     * Define the scrollbar size.
12143     *
12144     * @param scrollBarSize - the scrollbar size
12145     *
12146     * @attr ref android.R.styleable#View_scrollbarSize
12147     */
12148    public void setScrollBarSize(int scrollBarSize) {
12149        getScrollCache().scrollBarSize = scrollBarSize;
12150    }
12151
12152    /**
12153     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12154     * inset. When inset, they add to the padding of the view. And the scrollbars
12155     * can be drawn inside the padding area or on the edge of the view. For example,
12156     * if a view has a background drawable and you want to draw the scrollbars
12157     * inside the padding specified by the drawable, you can use
12158     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12159     * appear at the edge of the view, ignoring the padding, then you can use
12160     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12161     * @param style the style of the scrollbars. Should be one of
12162     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12163     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12164     * @see #SCROLLBARS_INSIDE_OVERLAY
12165     * @see #SCROLLBARS_INSIDE_INSET
12166     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12167     * @see #SCROLLBARS_OUTSIDE_INSET
12168     *
12169     * @attr ref android.R.styleable#View_scrollbarStyle
12170     */
12171    public void setScrollBarStyle(@ScrollBarStyle int style) {
12172        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12173            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12174            computeOpaqueFlags();
12175            resolvePadding();
12176        }
12177    }
12178
12179    /**
12180     * <p>Returns the current scrollbar style.</p>
12181     * @return the current scrollbar style
12182     * @see #SCROLLBARS_INSIDE_OVERLAY
12183     * @see #SCROLLBARS_INSIDE_INSET
12184     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12185     * @see #SCROLLBARS_OUTSIDE_INSET
12186     *
12187     * @attr ref android.R.styleable#View_scrollbarStyle
12188     */
12189    @ViewDebug.ExportedProperty(mapping = {
12190            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12191            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12192            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12193            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12194    })
12195    @ScrollBarStyle
12196    public int getScrollBarStyle() {
12197        return mViewFlags & SCROLLBARS_STYLE_MASK;
12198    }
12199
12200    /**
12201     * <p>Compute the horizontal range that the horizontal scrollbar
12202     * represents.</p>
12203     *
12204     * <p>The range is expressed in arbitrary units that must be the same as the
12205     * units used by {@link #computeHorizontalScrollExtent()} and
12206     * {@link #computeHorizontalScrollOffset()}.</p>
12207     *
12208     * <p>The default range is the drawing width of this view.</p>
12209     *
12210     * @return the total horizontal range represented by the horizontal
12211     *         scrollbar
12212     *
12213     * @see #computeHorizontalScrollExtent()
12214     * @see #computeHorizontalScrollOffset()
12215     * @see android.widget.ScrollBarDrawable
12216     */
12217    protected int computeHorizontalScrollRange() {
12218        return getWidth();
12219    }
12220
12221    /**
12222     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12223     * within the horizontal range. This value is used to compute the position
12224     * of the thumb within the scrollbar's track.</p>
12225     *
12226     * <p>The range is expressed in arbitrary units that must be the same as the
12227     * units used by {@link #computeHorizontalScrollRange()} and
12228     * {@link #computeHorizontalScrollExtent()}.</p>
12229     *
12230     * <p>The default offset is the scroll offset of this view.</p>
12231     *
12232     * @return the horizontal offset of the scrollbar's thumb
12233     *
12234     * @see #computeHorizontalScrollRange()
12235     * @see #computeHorizontalScrollExtent()
12236     * @see android.widget.ScrollBarDrawable
12237     */
12238    protected int computeHorizontalScrollOffset() {
12239        return mScrollX;
12240    }
12241
12242    /**
12243     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12244     * within the horizontal range. This value is used to compute the length
12245     * of the thumb within the scrollbar's track.</p>
12246     *
12247     * <p>The range is expressed in arbitrary units that must be the same as the
12248     * units used by {@link #computeHorizontalScrollRange()} and
12249     * {@link #computeHorizontalScrollOffset()}.</p>
12250     *
12251     * <p>The default extent is the drawing width of this view.</p>
12252     *
12253     * @return the horizontal extent of the scrollbar's thumb
12254     *
12255     * @see #computeHorizontalScrollRange()
12256     * @see #computeHorizontalScrollOffset()
12257     * @see android.widget.ScrollBarDrawable
12258     */
12259    protected int computeHorizontalScrollExtent() {
12260        return getWidth();
12261    }
12262
12263    /**
12264     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12265     *
12266     * <p>The range is expressed in arbitrary units that must be the same as the
12267     * units used by {@link #computeVerticalScrollExtent()} and
12268     * {@link #computeVerticalScrollOffset()}.</p>
12269     *
12270     * @return the total vertical range represented by the vertical scrollbar
12271     *
12272     * <p>The default range is the drawing height of this view.</p>
12273     *
12274     * @see #computeVerticalScrollExtent()
12275     * @see #computeVerticalScrollOffset()
12276     * @see android.widget.ScrollBarDrawable
12277     */
12278    protected int computeVerticalScrollRange() {
12279        return getHeight();
12280    }
12281
12282    /**
12283     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12284     * within the horizontal range. This value is used to compute the position
12285     * of the thumb within the scrollbar's track.</p>
12286     *
12287     * <p>The range is expressed in arbitrary units that must be the same as the
12288     * units used by {@link #computeVerticalScrollRange()} and
12289     * {@link #computeVerticalScrollExtent()}.</p>
12290     *
12291     * <p>The default offset is the scroll offset of this view.</p>
12292     *
12293     * @return the vertical offset of the scrollbar's thumb
12294     *
12295     * @see #computeVerticalScrollRange()
12296     * @see #computeVerticalScrollExtent()
12297     * @see android.widget.ScrollBarDrawable
12298     */
12299    protected int computeVerticalScrollOffset() {
12300        return mScrollY;
12301    }
12302
12303    /**
12304     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
12305     * within the vertical range. This value is used to compute the length
12306     * of the thumb within the scrollbar's track.</p>
12307     *
12308     * <p>The range is expressed in arbitrary units that must be the same as the
12309     * units used by {@link #computeVerticalScrollRange()} and
12310     * {@link #computeVerticalScrollOffset()}.</p>
12311     *
12312     * <p>The default extent is the drawing height of this view.</p>
12313     *
12314     * @return the vertical extent of the scrollbar's thumb
12315     *
12316     * @see #computeVerticalScrollRange()
12317     * @see #computeVerticalScrollOffset()
12318     * @see android.widget.ScrollBarDrawable
12319     */
12320    protected int computeVerticalScrollExtent() {
12321        return getHeight();
12322    }
12323
12324    /**
12325     * Check if this view can be scrolled horizontally in a certain direction.
12326     *
12327     * @param direction Negative to check scrolling left, positive to check scrolling right.
12328     * @return true if this view can be scrolled in the specified direction, false otherwise.
12329     */
12330    public boolean canScrollHorizontally(int direction) {
12331        final int offset = computeHorizontalScrollOffset();
12332        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12333        if (range == 0) return false;
12334        if (direction < 0) {
12335            return offset > 0;
12336        } else {
12337            return offset < range - 1;
12338        }
12339    }
12340
12341    /**
12342     * Check if this view can be scrolled vertically in a certain direction.
12343     *
12344     * @param direction Negative to check scrolling up, positive to check scrolling down.
12345     * @return true if this view can be scrolled in the specified direction, false otherwise.
12346     */
12347    public boolean canScrollVertically(int direction) {
12348        final int offset = computeVerticalScrollOffset();
12349        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12350        if (range == 0) return false;
12351        if (direction < 0) {
12352            return offset > 0;
12353        } else {
12354            return offset < range - 1;
12355        }
12356    }
12357
12358    /**
12359     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12360     * scrollbars are painted only if they have been awakened first.</p>
12361     *
12362     * @param canvas the canvas on which to draw the scrollbars
12363     *
12364     * @see #awakenScrollBars(int)
12365     */
12366    protected final void onDrawScrollBars(Canvas canvas) {
12367        // scrollbars are drawn only when the animation is running
12368        final ScrollabilityCache cache = mScrollCache;
12369        if (cache != null) {
12370
12371            int state = cache.state;
12372
12373            if (state == ScrollabilityCache.OFF) {
12374                return;
12375            }
12376
12377            boolean invalidate = false;
12378
12379            if (state == ScrollabilityCache.FADING) {
12380                // We're fading -- get our fade interpolation
12381                if (cache.interpolatorValues == null) {
12382                    cache.interpolatorValues = new float[1];
12383                }
12384
12385                float[] values = cache.interpolatorValues;
12386
12387                // Stops the animation if we're done
12388                if (cache.scrollBarInterpolator.timeToValues(values) ==
12389                        Interpolator.Result.FREEZE_END) {
12390                    cache.state = ScrollabilityCache.OFF;
12391                } else {
12392                    cache.scrollBar.setAlpha(Math.round(values[0]));
12393                }
12394
12395                // This will make the scroll bars inval themselves after
12396                // drawing. We only want this when we're fading so that
12397                // we prevent excessive redraws
12398                invalidate = true;
12399            } else {
12400                // We're just on -- but we may have been fading before so
12401                // reset alpha
12402                cache.scrollBar.setAlpha(255);
12403            }
12404
12405
12406            final int viewFlags = mViewFlags;
12407
12408            final boolean drawHorizontalScrollBar =
12409                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12410            final boolean drawVerticalScrollBar =
12411                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12412                && !isVerticalScrollBarHidden();
12413
12414            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12415                final int width = mRight - mLeft;
12416                final int height = mBottom - mTop;
12417
12418                final ScrollBarDrawable scrollBar = cache.scrollBar;
12419
12420                final int scrollX = mScrollX;
12421                final int scrollY = mScrollY;
12422                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12423
12424                int left;
12425                int top;
12426                int right;
12427                int bottom;
12428
12429                if (drawHorizontalScrollBar) {
12430                    int size = scrollBar.getSize(false);
12431                    if (size <= 0) {
12432                        size = cache.scrollBarSize;
12433                    }
12434
12435                    scrollBar.setParameters(computeHorizontalScrollRange(),
12436                                            computeHorizontalScrollOffset(),
12437                                            computeHorizontalScrollExtent(), false);
12438                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12439                            getVerticalScrollbarWidth() : 0;
12440                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12441                    left = scrollX + (mPaddingLeft & inside);
12442                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12443                    bottom = top + size;
12444                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12445                    if (invalidate) {
12446                        invalidate(left, top, right, bottom);
12447                    }
12448                }
12449
12450                if (drawVerticalScrollBar) {
12451                    int size = scrollBar.getSize(true);
12452                    if (size <= 0) {
12453                        size = cache.scrollBarSize;
12454                    }
12455
12456                    scrollBar.setParameters(computeVerticalScrollRange(),
12457                                            computeVerticalScrollOffset(),
12458                                            computeVerticalScrollExtent(), true);
12459                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12460                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12461                        verticalScrollbarPosition = isLayoutRtl() ?
12462                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12463                    }
12464                    switch (verticalScrollbarPosition) {
12465                        default:
12466                        case SCROLLBAR_POSITION_RIGHT:
12467                            left = scrollX + width - size - (mUserPaddingRight & inside);
12468                            break;
12469                        case SCROLLBAR_POSITION_LEFT:
12470                            left = scrollX + (mUserPaddingLeft & inside);
12471                            break;
12472                    }
12473                    top = scrollY + (mPaddingTop & inside);
12474                    right = left + size;
12475                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12476                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12477                    if (invalidate) {
12478                        invalidate(left, top, right, bottom);
12479                    }
12480                }
12481            }
12482        }
12483    }
12484
12485    /**
12486     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12487     * FastScroller is visible.
12488     * @return whether to temporarily hide the vertical scrollbar
12489     * @hide
12490     */
12491    protected boolean isVerticalScrollBarHidden() {
12492        return false;
12493    }
12494
12495    /**
12496     * <p>Draw the horizontal scrollbar if
12497     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12498     *
12499     * @param canvas the canvas on which to draw the scrollbar
12500     * @param scrollBar the scrollbar's drawable
12501     *
12502     * @see #isHorizontalScrollBarEnabled()
12503     * @see #computeHorizontalScrollRange()
12504     * @see #computeHorizontalScrollExtent()
12505     * @see #computeHorizontalScrollOffset()
12506     * @see android.widget.ScrollBarDrawable
12507     * @hide
12508     */
12509    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12510            int l, int t, int r, int b) {
12511        scrollBar.setBounds(l, t, r, b);
12512        scrollBar.draw(canvas);
12513    }
12514
12515    /**
12516     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12517     * returns true.</p>
12518     *
12519     * @param canvas the canvas on which to draw the scrollbar
12520     * @param scrollBar the scrollbar's drawable
12521     *
12522     * @see #isVerticalScrollBarEnabled()
12523     * @see #computeVerticalScrollRange()
12524     * @see #computeVerticalScrollExtent()
12525     * @see #computeVerticalScrollOffset()
12526     * @see android.widget.ScrollBarDrawable
12527     * @hide
12528     */
12529    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12530            int l, int t, int r, int b) {
12531        scrollBar.setBounds(l, t, r, b);
12532        scrollBar.draw(canvas);
12533    }
12534
12535    /**
12536     * Implement this to do your drawing.
12537     *
12538     * @param canvas the canvas on which the background will be drawn
12539     */
12540    protected void onDraw(Canvas canvas) {
12541    }
12542
12543    /*
12544     * Caller is responsible for calling requestLayout if necessary.
12545     * (This allows addViewInLayout to not request a new layout.)
12546     */
12547    void assignParent(ViewParent parent) {
12548        if (mParent == null) {
12549            mParent = parent;
12550        } else if (parent == null) {
12551            mParent = null;
12552        } else {
12553            throw new RuntimeException("view " + this + " being added, but"
12554                    + " it already has a parent");
12555        }
12556    }
12557
12558    /**
12559     * This is called when the view is attached to a window.  At this point it
12560     * has a Surface and will start drawing.  Note that this function is
12561     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12562     * however it may be called any time before the first onDraw -- including
12563     * before or after {@link #onMeasure(int, int)}.
12564     *
12565     * @see #onDetachedFromWindow()
12566     */
12567    protected void onAttachedToWindow() {
12568        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12569            mParent.requestTransparentRegion(this);
12570        }
12571
12572        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12573            initialAwakenScrollBars();
12574            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12575        }
12576
12577        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12578
12579        jumpDrawablesToCurrentState();
12580
12581        resetSubtreeAccessibilityStateChanged();
12582
12583        if (isFocused()) {
12584            InputMethodManager imm = InputMethodManager.peekInstance();
12585            imm.focusIn(this);
12586        }
12587
12588        if (mDisplayList != null) {
12589            mDisplayList.clearDirty();
12590        }
12591    }
12592
12593    /**
12594     * Resolve all RTL related properties.
12595     *
12596     * @return true if resolution of RTL properties has been done
12597     *
12598     * @hide
12599     */
12600    public boolean resolveRtlPropertiesIfNeeded() {
12601        if (!needRtlPropertiesResolution()) return false;
12602
12603        // Order is important here: LayoutDirection MUST be resolved first
12604        if (!isLayoutDirectionResolved()) {
12605            resolveLayoutDirection();
12606            resolveLayoutParams();
12607        }
12608        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12609        if (!isTextDirectionResolved()) {
12610            resolveTextDirection();
12611        }
12612        if (!isTextAlignmentResolved()) {
12613            resolveTextAlignment();
12614        }
12615        // Should resolve Drawables before Padding because we need the layout direction of the
12616        // Drawable to correctly resolve Padding.
12617        if (!isDrawablesResolved()) {
12618            resolveDrawables();
12619        }
12620        if (!isPaddingResolved()) {
12621            resolvePadding();
12622        }
12623        onRtlPropertiesChanged(getLayoutDirection());
12624        return true;
12625    }
12626
12627    /**
12628     * Reset resolution of all RTL related properties.
12629     *
12630     * @hide
12631     */
12632    public void resetRtlProperties() {
12633        resetResolvedLayoutDirection();
12634        resetResolvedTextDirection();
12635        resetResolvedTextAlignment();
12636        resetResolvedPadding();
12637        resetResolvedDrawables();
12638    }
12639
12640    /**
12641     * @see #onScreenStateChanged(int)
12642     */
12643    void dispatchScreenStateChanged(int screenState) {
12644        onScreenStateChanged(screenState);
12645    }
12646
12647    /**
12648     * This method is called whenever the state of the screen this view is
12649     * attached to changes. A state change will usually occurs when the screen
12650     * turns on or off (whether it happens automatically or the user does it
12651     * manually.)
12652     *
12653     * @param screenState The new state of the screen. Can be either
12654     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12655     */
12656    public void onScreenStateChanged(int screenState) {
12657    }
12658
12659    /**
12660     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12661     */
12662    private boolean hasRtlSupport() {
12663        return mContext.getApplicationInfo().hasRtlSupport();
12664    }
12665
12666    /**
12667     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12668     * RTL not supported)
12669     */
12670    private boolean isRtlCompatibilityMode() {
12671        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12672        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12673    }
12674
12675    /**
12676     * @return true if RTL properties need resolution.
12677     *
12678     */
12679    private boolean needRtlPropertiesResolution() {
12680        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12681    }
12682
12683    /**
12684     * Called when any RTL property (layout direction or text direction or text alignment) has
12685     * been changed.
12686     *
12687     * Subclasses need to override this method to take care of cached information that depends on the
12688     * resolved layout direction, or to inform child views that inherit their layout direction.
12689     *
12690     * The default implementation does nothing.
12691     *
12692     * @param layoutDirection the direction of the layout
12693     *
12694     * @see #LAYOUT_DIRECTION_LTR
12695     * @see #LAYOUT_DIRECTION_RTL
12696     */
12697    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12698    }
12699
12700    /**
12701     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12702     * that the parent directionality can and will be resolved before its children.
12703     *
12704     * @return true if resolution has been done, false otherwise.
12705     *
12706     * @hide
12707     */
12708    public boolean resolveLayoutDirection() {
12709        // Clear any previous layout direction resolution
12710        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12711
12712        if (hasRtlSupport()) {
12713            // Set resolved depending on layout direction
12714            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12715                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12716                case LAYOUT_DIRECTION_INHERIT:
12717                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12718                    // later to get the correct resolved value
12719                    if (!canResolveLayoutDirection()) return false;
12720
12721                    // Parent has not yet resolved, LTR is still the default
12722                    try {
12723                        if (!mParent.isLayoutDirectionResolved()) return false;
12724
12725                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12726                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12727                        }
12728                    } catch (AbstractMethodError e) {
12729                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12730                                " does not fully implement ViewParent", e);
12731                    }
12732                    break;
12733                case LAYOUT_DIRECTION_RTL:
12734                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12735                    break;
12736                case LAYOUT_DIRECTION_LOCALE:
12737                    if((LAYOUT_DIRECTION_RTL ==
12738                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12739                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12740                    }
12741                    break;
12742                default:
12743                    // Nothing to do, LTR by default
12744            }
12745        }
12746
12747        // Set to resolved
12748        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12749        return true;
12750    }
12751
12752    /**
12753     * Check if layout direction resolution can be done.
12754     *
12755     * @return true if layout direction resolution can be done otherwise return false.
12756     */
12757    public boolean canResolveLayoutDirection() {
12758        switch (getRawLayoutDirection()) {
12759            case LAYOUT_DIRECTION_INHERIT:
12760                if (mParent != null) {
12761                    try {
12762                        return mParent.canResolveLayoutDirection();
12763                    } catch (AbstractMethodError e) {
12764                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12765                                " does not fully implement ViewParent", e);
12766                    }
12767                }
12768                return false;
12769
12770            default:
12771                return true;
12772        }
12773    }
12774
12775    /**
12776     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12777     * {@link #onMeasure(int, int)}.
12778     *
12779     * @hide
12780     */
12781    public void resetResolvedLayoutDirection() {
12782        // Reset the current resolved bits
12783        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12784    }
12785
12786    /**
12787     * @return true if the layout direction is inherited.
12788     *
12789     * @hide
12790     */
12791    public boolean isLayoutDirectionInherited() {
12792        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12793    }
12794
12795    /**
12796     * @return true if layout direction has been resolved.
12797     */
12798    public boolean isLayoutDirectionResolved() {
12799        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12800    }
12801
12802    /**
12803     * Return if padding has been resolved
12804     *
12805     * @hide
12806     */
12807    boolean isPaddingResolved() {
12808        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12809    }
12810
12811    /**
12812     * Resolves padding depending on layout direction, if applicable, and
12813     * recomputes internal padding values to adjust for scroll bars.
12814     *
12815     * @hide
12816     */
12817    public void resolvePadding() {
12818        final int resolvedLayoutDirection = getLayoutDirection();
12819
12820        if (!isRtlCompatibilityMode()) {
12821            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12822            // If start / end padding are defined, they will be resolved (hence overriding) to
12823            // left / right or right / left depending on the resolved layout direction.
12824            // If start / end padding are not defined, use the left / right ones.
12825            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12826                Rect padding = sThreadLocal.get();
12827                if (padding == null) {
12828                    padding = new Rect();
12829                    sThreadLocal.set(padding);
12830                }
12831                mBackground.getPadding(padding);
12832                if (!mLeftPaddingDefined) {
12833                    mUserPaddingLeftInitial = padding.left;
12834                }
12835                if (!mRightPaddingDefined) {
12836                    mUserPaddingRightInitial = padding.right;
12837                }
12838            }
12839            switch (resolvedLayoutDirection) {
12840                case LAYOUT_DIRECTION_RTL:
12841                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12842                        mUserPaddingRight = mUserPaddingStart;
12843                    } else {
12844                        mUserPaddingRight = mUserPaddingRightInitial;
12845                    }
12846                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12847                        mUserPaddingLeft = mUserPaddingEnd;
12848                    } else {
12849                        mUserPaddingLeft = mUserPaddingLeftInitial;
12850                    }
12851                    break;
12852                case LAYOUT_DIRECTION_LTR:
12853                default:
12854                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12855                        mUserPaddingLeft = mUserPaddingStart;
12856                    } else {
12857                        mUserPaddingLeft = mUserPaddingLeftInitial;
12858                    }
12859                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12860                        mUserPaddingRight = mUserPaddingEnd;
12861                    } else {
12862                        mUserPaddingRight = mUserPaddingRightInitial;
12863                    }
12864            }
12865
12866            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12867        }
12868
12869        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12870        onRtlPropertiesChanged(resolvedLayoutDirection);
12871
12872        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12873    }
12874
12875    /**
12876     * Reset the resolved layout direction.
12877     *
12878     * @hide
12879     */
12880    public void resetResolvedPadding() {
12881        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12882    }
12883
12884    /**
12885     * This is called when the view is detached from a window.  At this point it
12886     * no longer has a surface for drawing.
12887     *
12888     * @see #onAttachedToWindow()
12889     */
12890    protected void onDetachedFromWindow() {
12891        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12892        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12893
12894        removeUnsetPressCallback();
12895        removeLongPressCallback();
12896        removePerformClickCallback();
12897        removeSendViewScrolledAccessibilityEventCallback();
12898
12899        destroyDrawingCache();
12900        destroyLayer(false);
12901
12902        cleanupDraw();
12903
12904        mCurrentAnimation = null;
12905    }
12906
12907    private void cleanupDraw() {
12908        if (mAttachInfo != null) {
12909            if (mDisplayList != null) {
12910                mDisplayList.markDirty();
12911                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12912            }
12913            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12914        } else {
12915            // Should never happen
12916            resetDisplayList();
12917        }
12918    }
12919
12920    /**
12921     * This method ensures the hardware renderer is in a valid state
12922     * before executing the specified action.
12923     *
12924     * This method will attempt to set a valid state even if the window
12925     * the renderer is attached to was destroyed.
12926     *
12927     * This method is not guaranteed to work. If the hardware renderer
12928     * does not exist or cannot be put in a valid state, this method
12929     * will not executed the specified action.
12930     *
12931     * The specified action is executed synchronously.
12932     *
12933     * @param action The action to execute after the renderer is in a valid state
12934     *
12935     * @return True if the specified Runnable was executed, false otherwise
12936     *
12937     * @hide
12938     */
12939    public boolean executeHardwareAction(Runnable action) {
12940        //noinspection SimplifiableIfStatement
12941        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12942            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12943        }
12944        return false;
12945    }
12946
12947    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12948    }
12949
12950    /**
12951     * @return The number of times this view has been attached to a window
12952     */
12953    protected int getWindowAttachCount() {
12954        return mWindowAttachCount;
12955    }
12956
12957    /**
12958     * Retrieve a unique token identifying the window this view is attached to.
12959     * @return Return the window's token for use in
12960     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12961     */
12962    public IBinder getWindowToken() {
12963        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12964    }
12965
12966    /**
12967     * Retrieve the {@link WindowId} for the window this view is
12968     * currently attached to.
12969     */
12970    public WindowId getWindowId() {
12971        if (mAttachInfo == null) {
12972            return null;
12973        }
12974        if (mAttachInfo.mWindowId == null) {
12975            try {
12976                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12977                        mAttachInfo.mWindowToken);
12978                mAttachInfo.mWindowId = new WindowId(
12979                        mAttachInfo.mIWindowId);
12980            } catch (RemoteException e) {
12981            }
12982        }
12983        return mAttachInfo.mWindowId;
12984    }
12985
12986    /**
12987     * Retrieve a unique token identifying the top-level "real" window of
12988     * the window that this view is attached to.  That is, this is like
12989     * {@link #getWindowToken}, except if the window this view in is a panel
12990     * window (attached to another containing window), then the token of
12991     * the containing window is returned instead.
12992     *
12993     * @return Returns the associated window token, either
12994     * {@link #getWindowToken()} or the containing window's token.
12995     */
12996    public IBinder getApplicationWindowToken() {
12997        AttachInfo ai = mAttachInfo;
12998        if (ai != null) {
12999            IBinder appWindowToken = ai.mPanelParentWindowToken;
13000            if (appWindowToken == null) {
13001                appWindowToken = ai.mWindowToken;
13002            }
13003            return appWindowToken;
13004        }
13005        return null;
13006    }
13007
13008    /**
13009     * Gets the logical display to which the view's window has been attached.
13010     *
13011     * @return The logical display, or null if the view is not currently attached to a window.
13012     */
13013    public Display getDisplay() {
13014        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13015    }
13016
13017    /**
13018     * Retrieve private session object this view hierarchy is using to
13019     * communicate with the window manager.
13020     * @return the session object to communicate with the window manager
13021     */
13022    /*package*/ IWindowSession getWindowSession() {
13023        return mAttachInfo != null ? mAttachInfo.mSession : null;
13024    }
13025
13026    /**
13027     * @param info the {@link android.view.View.AttachInfo} to associated with
13028     *        this view
13029     */
13030    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13031        //System.out.println("Attached! " + this);
13032        mAttachInfo = info;
13033        if (mOverlay != null) {
13034            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13035        }
13036        mWindowAttachCount++;
13037        // We will need to evaluate the drawable state at least once.
13038        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13039        if (mFloatingTreeObserver != null) {
13040            info.mTreeObserver.merge(mFloatingTreeObserver);
13041            mFloatingTreeObserver = null;
13042        }
13043        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13044            mAttachInfo.mScrollContainers.add(this);
13045            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13046        }
13047        performCollectViewAttributes(mAttachInfo, visibility);
13048        onAttachedToWindow();
13049
13050        ListenerInfo li = mListenerInfo;
13051        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13052                li != null ? li.mOnAttachStateChangeListeners : null;
13053        if (listeners != null && listeners.size() > 0) {
13054            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13055            // perform the dispatching. The iterator is a safe guard against listeners that
13056            // could mutate the list by calling the various add/remove methods. This prevents
13057            // the array from being modified while we iterate it.
13058            for (OnAttachStateChangeListener listener : listeners) {
13059                listener.onViewAttachedToWindow(this);
13060            }
13061        }
13062
13063        int vis = info.mWindowVisibility;
13064        if (vis != GONE) {
13065            onWindowVisibilityChanged(vis);
13066        }
13067        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13068            // If nobody has evaluated the drawable state yet, then do it now.
13069            refreshDrawableState();
13070        }
13071        needGlobalAttributesUpdate(false);
13072    }
13073
13074    void dispatchDetachedFromWindow() {
13075        AttachInfo info = mAttachInfo;
13076        if (info != null) {
13077            int vis = info.mWindowVisibility;
13078            if (vis != GONE) {
13079                onWindowVisibilityChanged(GONE);
13080            }
13081        }
13082
13083        onDetachedFromWindow();
13084
13085        ListenerInfo li = mListenerInfo;
13086        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13087                li != null ? li.mOnAttachStateChangeListeners : null;
13088        if (listeners != null && listeners.size() > 0) {
13089            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13090            // perform the dispatching. The iterator is a safe guard against listeners that
13091            // could mutate the list by calling the various add/remove methods. This prevents
13092            // the array from being modified while we iterate it.
13093            for (OnAttachStateChangeListener listener : listeners) {
13094                listener.onViewDetachedFromWindow(this);
13095            }
13096        }
13097
13098        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13099            mAttachInfo.mScrollContainers.remove(this);
13100            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13101        }
13102
13103        mAttachInfo = null;
13104        if (mOverlay != null) {
13105            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13106        }
13107    }
13108
13109    /**
13110     * Cancel any deferred high-level input events that were previously posted to the event queue.
13111     *
13112     * <p>Many views post high-level events such as click handlers to the event queue
13113     * to run deferred in order to preserve a desired user experience - clearing visible
13114     * pressed states before executing, etc. This method will abort any events of this nature
13115     * that are currently in flight.</p>
13116     *
13117     * <p>Custom views that generate their own high-level deferred input events should override
13118     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13119     *
13120     * <p>This will also cancel pending input events for any child views.</p>
13121     *
13122     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13123     * This will not impact newer events posted after this call that may occur as a result of
13124     * lower-level input events still waiting in the queue. If you are trying to prevent
13125     * double-submitted  events for the duration of some sort of asynchronous transaction
13126     * you should also take other steps to protect against unexpected double inputs e.g. calling
13127     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13128     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13129     */
13130    public final void cancelPendingInputEvents() {
13131        dispatchCancelPendingInputEvents();
13132    }
13133
13134    /**
13135     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13136     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13137     */
13138    void dispatchCancelPendingInputEvents() {
13139        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13140        onCancelPendingInputEvents();
13141        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13142            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13143                    " did not call through to super.onCancelPendingInputEvents()");
13144        }
13145    }
13146
13147    /**
13148     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13149     * a parent view.
13150     *
13151     * <p>This method is responsible for removing any pending high-level input events that were
13152     * posted to the event queue to run later. Custom view classes that post their own deferred
13153     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13154     * {@link android.os.Handler} should override this method, call
13155     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13156     * </p>
13157     */
13158    public void onCancelPendingInputEvents() {
13159        removePerformClickCallback();
13160        cancelLongPress();
13161        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13162    }
13163
13164    /**
13165     * Store this view hierarchy's frozen state into the given container.
13166     *
13167     * @param container The SparseArray in which to save the view's state.
13168     *
13169     * @see #restoreHierarchyState(android.util.SparseArray)
13170     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13171     * @see #onSaveInstanceState()
13172     */
13173    public void saveHierarchyState(SparseArray<Parcelable> container) {
13174        dispatchSaveInstanceState(container);
13175    }
13176
13177    /**
13178     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13179     * this view and its children. May be overridden to modify how freezing happens to a
13180     * view's children; for example, some views may want to not store state for their children.
13181     *
13182     * @param container The SparseArray in which to save the view's state.
13183     *
13184     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13185     * @see #saveHierarchyState(android.util.SparseArray)
13186     * @see #onSaveInstanceState()
13187     */
13188    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13189        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13190            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13191            Parcelable state = onSaveInstanceState();
13192            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13193                throw new IllegalStateException(
13194                        "Derived class did not call super.onSaveInstanceState()");
13195            }
13196            if (state != null) {
13197                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13198                // + ": " + state);
13199                container.put(mID, state);
13200            }
13201        }
13202    }
13203
13204    /**
13205     * Hook allowing a view to generate a representation of its internal state
13206     * that can later be used to create a new instance with that same state.
13207     * This state should only contain information that is not persistent or can
13208     * not be reconstructed later. For example, you will never store your
13209     * current position on screen because that will be computed again when a
13210     * new instance of the view is placed in its view hierarchy.
13211     * <p>
13212     * Some examples of things you may store here: the current cursor position
13213     * in a text view (but usually not the text itself since that is stored in a
13214     * content provider or other persistent storage), the currently selected
13215     * item in a list view.
13216     *
13217     * @return Returns a Parcelable object containing the view's current dynamic
13218     *         state, or null if there is nothing interesting to save. The
13219     *         default implementation returns null.
13220     * @see #onRestoreInstanceState(android.os.Parcelable)
13221     * @see #saveHierarchyState(android.util.SparseArray)
13222     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13223     * @see #setSaveEnabled(boolean)
13224     */
13225    protected Parcelable onSaveInstanceState() {
13226        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13227        return BaseSavedState.EMPTY_STATE;
13228    }
13229
13230    /**
13231     * Restore this view hierarchy's frozen state from the given container.
13232     *
13233     * @param container The SparseArray which holds previously frozen states.
13234     *
13235     * @see #saveHierarchyState(android.util.SparseArray)
13236     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13237     * @see #onRestoreInstanceState(android.os.Parcelable)
13238     */
13239    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13240        dispatchRestoreInstanceState(container);
13241    }
13242
13243    /**
13244     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13245     * state for this view and its children. May be overridden to modify how restoring
13246     * happens to a view's children; for example, some views may want to not store state
13247     * for their children.
13248     *
13249     * @param container The SparseArray which holds previously saved state.
13250     *
13251     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13252     * @see #restoreHierarchyState(android.util.SparseArray)
13253     * @see #onRestoreInstanceState(android.os.Parcelable)
13254     */
13255    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13256        if (mID != NO_ID) {
13257            Parcelable state = container.get(mID);
13258            if (state != null) {
13259                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13260                // + ": " + state);
13261                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13262                onRestoreInstanceState(state);
13263                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13264                    throw new IllegalStateException(
13265                            "Derived class did not call super.onRestoreInstanceState()");
13266                }
13267            }
13268        }
13269    }
13270
13271    /**
13272     * Hook allowing a view to re-apply a representation of its internal state that had previously
13273     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13274     * null state.
13275     *
13276     * @param state The frozen state that had previously been returned by
13277     *        {@link #onSaveInstanceState}.
13278     *
13279     * @see #onSaveInstanceState()
13280     * @see #restoreHierarchyState(android.util.SparseArray)
13281     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13282     */
13283    protected void onRestoreInstanceState(Parcelable state) {
13284        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13285        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13286            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13287                    + "received " + state.getClass().toString() + " instead. This usually happens "
13288                    + "when two views of different type have the same id in the same hierarchy. "
13289                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13290                    + "other views do not use the same id.");
13291        }
13292    }
13293
13294    /**
13295     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13296     *
13297     * @return the drawing start time in milliseconds
13298     */
13299    public long getDrawingTime() {
13300        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13301    }
13302
13303    /**
13304     * <p>Enables or disables the duplication of the parent's state into this view. When
13305     * duplication is enabled, this view gets its drawable state from its parent rather
13306     * than from its own internal properties.</p>
13307     *
13308     * <p>Note: in the current implementation, setting this property to true after the
13309     * view was added to a ViewGroup might have no effect at all. This property should
13310     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13311     *
13312     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13313     * property is enabled, an exception will be thrown.</p>
13314     *
13315     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13316     * parent, these states should not be affected by this method.</p>
13317     *
13318     * @param enabled True to enable duplication of the parent's drawable state, false
13319     *                to disable it.
13320     *
13321     * @see #getDrawableState()
13322     * @see #isDuplicateParentStateEnabled()
13323     */
13324    public void setDuplicateParentStateEnabled(boolean enabled) {
13325        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13326    }
13327
13328    /**
13329     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13330     *
13331     * @return True if this view's drawable state is duplicated from the parent,
13332     *         false otherwise
13333     *
13334     * @see #getDrawableState()
13335     * @see #setDuplicateParentStateEnabled(boolean)
13336     */
13337    public boolean isDuplicateParentStateEnabled() {
13338        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13339    }
13340
13341    /**
13342     * <p>Specifies the type of layer backing this view. The layer can be
13343     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13344     * {@link #LAYER_TYPE_HARDWARE}.</p>
13345     *
13346     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13347     * instance that controls how the layer is composed on screen. The following
13348     * properties of the paint are taken into account when composing the layer:</p>
13349     * <ul>
13350     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13351     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13352     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13353     * </ul>
13354     *
13355     * <p>If this view has an alpha value set to < 1.0 by calling
13356     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13357     * by this view's alpha value.</p>
13358     *
13359     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13360     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13361     * for more information on when and how to use layers.</p>
13362     *
13363     * @param layerType The type of layer to use with this view, must be one of
13364     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13365     *        {@link #LAYER_TYPE_HARDWARE}
13366     * @param paint The paint used to compose the layer. This argument is optional
13367     *        and can be null. It is ignored when the layer type is
13368     *        {@link #LAYER_TYPE_NONE}
13369     *
13370     * @see #getLayerType()
13371     * @see #LAYER_TYPE_NONE
13372     * @see #LAYER_TYPE_SOFTWARE
13373     * @see #LAYER_TYPE_HARDWARE
13374     * @see #setAlpha(float)
13375     *
13376     * @attr ref android.R.styleable#View_layerType
13377     */
13378    public void setLayerType(int layerType, Paint paint) {
13379        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13380            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13381                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13382        }
13383
13384        if (layerType == mLayerType) {
13385            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
13386                mLayerPaint = paint == null ? new Paint() : paint;
13387                invalidateParentCaches();
13388                invalidate(true);
13389            }
13390            return;
13391        }
13392
13393        // Destroy any previous software drawing cache if needed
13394        switch (mLayerType) {
13395            case LAYER_TYPE_HARDWARE:
13396                destroyLayer(false);
13397                // fall through - non-accelerated views may use software layer mechanism instead
13398            case LAYER_TYPE_SOFTWARE:
13399                destroyDrawingCache();
13400                break;
13401            default:
13402                break;
13403        }
13404
13405        mLayerType = layerType;
13406        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13407        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13408        mLocalDirtyRect = layerDisabled ? null : new Rect();
13409
13410        invalidateParentCaches();
13411        invalidate(true);
13412    }
13413
13414    /**
13415     * Updates the {@link Paint} object used with the current layer (used only if the current
13416     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13417     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13418     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13419     * ensure that the view gets redrawn immediately.
13420     *
13421     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13422     * instance that controls how the layer is composed on screen. The following
13423     * properties of the paint are taken into account when composing the layer:</p>
13424     * <ul>
13425     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13426     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13427     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13428     * </ul>
13429     *
13430     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13431     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13432     *
13433     * @param paint The paint used to compose the layer. This argument is optional
13434     *        and can be null. It is ignored when the layer type is
13435     *        {@link #LAYER_TYPE_NONE}
13436     *
13437     * @see #setLayerType(int, android.graphics.Paint)
13438     */
13439    public void setLayerPaint(Paint paint) {
13440        int layerType = getLayerType();
13441        if (layerType != LAYER_TYPE_NONE) {
13442            mLayerPaint = paint == null ? new Paint() : paint;
13443            if (layerType == LAYER_TYPE_HARDWARE) {
13444                HardwareLayer layer = getHardwareLayer();
13445                if (layer != null) {
13446                    layer.setLayerPaint(paint);
13447                }
13448                invalidateViewProperty(false, false);
13449            } else {
13450                invalidate();
13451            }
13452        }
13453    }
13454
13455    /**
13456     * Indicates whether this view has a static layer. A view with layer type
13457     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13458     * dynamic.
13459     */
13460    boolean hasStaticLayer() {
13461        return true;
13462    }
13463
13464    /**
13465     * Indicates what type of layer is currently associated with this view. By default
13466     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13467     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13468     * for more information on the different types of layers.
13469     *
13470     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13471     *         {@link #LAYER_TYPE_HARDWARE}
13472     *
13473     * @see #setLayerType(int, android.graphics.Paint)
13474     * @see #buildLayer()
13475     * @see #LAYER_TYPE_NONE
13476     * @see #LAYER_TYPE_SOFTWARE
13477     * @see #LAYER_TYPE_HARDWARE
13478     */
13479    public int getLayerType() {
13480        return mLayerType;
13481    }
13482
13483    /**
13484     * Forces this view's layer to be created and this view to be rendered
13485     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13486     * invoking this method will have no effect.
13487     *
13488     * This method can for instance be used to render a view into its layer before
13489     * starting an animation. If this view is complex, rendering into the layer
13490     * before starting the animation will avoid skipping frames.
13491     *
13492     * @throws IllegalStateException If this view is not attached to a window
13493     *
13494     * @see #setLayerType(int, android.graphics.Paint)
13495     */
13496    public void buildLayer() {
13497        if (mLayerType == LAYER_TYPE_NONE) return;
13498
13499        final AttachInfo attachInfo = mAttachInfo;
13500        if (attachInfo == null) {
13501            throw new IllegalStateException("This view must be attached to a window first");
13502        }
13503
13504        switch (mLayerType) {
13505            case LAYER_TYPE_HARDWARE:
13506                if (attachInfo.mHardwareRenderer != null &&
13507                        attachInfo.mHardwareRenderer.isEnabled() &&
13508                        attachInfo.mHardwareRenderer.validate()) {
13509                    getHardwareLayer();
13510                    // TODO: We need a better way to handle this case
13511                    // If views have registered pre-draw listeners they need
13512                    // to be notified before we build the layer. Those listeners
13513                    // may however rely on other events to happen first so we
13514                    // cannot just invoke them here until they don't cancel the
13515                    // current frame
13516                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13517                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13518                    }
13519                }
13520                break;
13521            case LAYER_TYPE_SOFTWARE:
13522                buildDrawingCache(true);
13523                break;
13524        }
13525    }
13526
13527    /**
13528     * <p>Returns a hardware layer that can be used to draw this view again
13529     * without executing its draw method.</p>
13530     *
13531     * @return A HardwareLayer ready to render, or null if an error occurred.
13532     */
13533    HardwareLayer getHardwareLayer() {
13534        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13535                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13536            return null;
13537        }
13538
13539        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
13540
13541        final int width = mRight - mLeft;
13542        final int height = mBottom - mTop;
13543
13544        if (width == 0 || height == 0) {
13545            return null;
13546        }
13547
13548        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13549            if (mHardwareLayer == null) {
13550                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
13551                        width, height, isOpaque());
13552                mLocalDirtyRect.set(0, 0, width, height);
13553            } else {
13554                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
13555                    if (mHardwareLayer.resize(width, height)) {
13556                        mLocalDirtyRect.set(0, 0, width, height);
13557                    }
13558                }
13559
13560                // This should not be necessary but applications that change
13561                // the parameters of their background drawable without calling
13562                // this.setBackground(Drawable) can leave the view in a bad state
13563                // (for instance isOpaque() returns true, but the background is
13564                // not opaque.)
13565                computeOpaqueFlags();
13566
13567                final boolean opaque = isOpaque();
13568                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
13569                    mHardwareLayer.setOpaque(opaque);
13570                    mLocalDirtyRect.set(0, 0, width, height);
13571                }
13572            }
13573
13574            // The layer is not valid if the underlying GPU resources cannot be allocated
13575            if (!mHardwareLayer.isValid()) {
13576                return null;
13577            }
13578
13579            mHardwareLayer.setLayerPaint(mLayerPaint);
13580            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
13581            ViewRootImpl viewRoot = getViewRootImpl();
13582            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
13583
13584            mLocalDirtyRect.setEmpty();
13585        }
13586
13587        return mHardwareLayer;
13588    }
13589
13590    /**
13591     * Destroys this View's hardware layer if possible.
13592     *
13593     * @return True if the layer was destroyed, false otherwise.
13594     *
13595     * @see #setLayerType(int, android.graphics.Paint)
13596     * @see #LAYER_TYPE_HARDWARE
13597     */
13598    boolean destroyLayer(boolean valid) {
13599        if (mHardwareLayer != null) {
13600            AttachInfo info = mAttachInfo;
13601            if (info != null && info.mHardwareRenderer != null &&
13602                    info.mHardwareRenderer.isEnabled() &&
13603                    (valid || info.mHardwareRenderer.validate())) {
13604
13605                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
13606                mHardwareLayer.destroy();
13607                mHardwareLayer = null;
13608
13609                invalidate(true);
13610                invalidateParentCaches();
13611            }
13612            return true;
13613        }
13614        return false;
13615    }
13616
13617    /**
13618     * Destroys all hardware rendering resources. This method is invoked
13619     * when the system needs to reclaim resources. Upon execution of this
13620     * method, you should free any OpenGL resources created by the view.
13621     *
13622     * Note: you <strong>must</strong> call
13623     * <code>super.destroyHardwareResources()</code> when overriding
13624     * this method.
13625     *
13626     * @hide
13627     */
13628    protected void destroyHardwareResources() {
13629        resetDisplayList();
13630        destroyLayer(true);
13631    }
13632
13633    /**
13634     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13635     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13636     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13637     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13638     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13639     * null.</p>
13640     *
13641     * <p>Enabling the drawing cache is similar to
13642     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13643     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13644     * drawing cache has no effect on rendering because the system uses a different mechanism
13645     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13646     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13647     * for information on how to enable software and hardware layers.</p>
13648     *
13649     * <p>This API can be used to manually generate
13650     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13651     * {@link #getDrawingCache()}.</p>
13652     *
13653     * @param enabled true to enable the drawing cache, false otherwise
13654     *
13655     * @see #isDrawingCacheEnabled()
13656     * @see #getDrawingCache()
13657     * @see #buildDrawingCache()
13658     * @see #setLayerType(int, android.graphics.Paint)
13659     */
13660    public void setDrawingCacheEnabled(boolean enabled) {
13661        mCachingFailed = false;
13662        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13663    }
13664
13665    /**
13666     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13667     *
13668     * @return true if the drawing cache is enabled
13669     *
13670     * @see #setDrawingCacheEnabled(boolean)
13671     * @see #getDrawingCache()
13672     */
13673    @ViewDebug.ExportedProperty(category = "drawing")
13674    public boolean isDrawingCacheEnabled() {
13675        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13676    }
13677
13678    /**
13679     * Debugging utility which recursively outputs the dirty state of a view and its
13680     * descendants.
13681     *
13682     * @hide
13683     */
13684    @SuppressWarnings({"UnusedDeclaration"})
13685    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13686        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13687                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13688                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13689                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13690        if (clear) {
13691            mPrivateFlags &= clearMask;
13692        }
13693        if (this instanceof ViewGroup) {
13694            ViewGroup parent = (ViewGroup) this;
13695            final int count = parent.getChildCount();
13696            for (int i = 0; i < count; i++) {
13697                final View child = parent.getChildAt(i);
13698                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13699            }
13700        }
13701    }
13702
13703    /**
13704     * This method is used by ViewGroup to cause its children to restore or recreate their
13705     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13706     * to recreate its own display list, which would happen if it went through the normal
13707     * draw/dispatchDraw mechanisms.
13708     *
13709     * @hide
13710     */
13711    protected void dispatchGetDisplayList() {}
13712
13713    /**
13714     * A view that is not attached or hardware accelerated cannot create a display list.
13715     * This method checks these conditions and returns the appropriate result.
13716     *
13717     * @return true if view has the ability to create a display list, false otherwise.
13718     *
13719     * @hide
13720     */
13721    public boolean canHaveDisplayList() {
13722        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13723    }
13724
13725    /**
13726     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13727     * Otherwise, the same display list will be returned (after having been rendered into
13728     * along the way, depending on the invalidation state of the view).
13729     *
13730     * @param displayList The previous version of this displayList, could be null.
13731     * @param isLayer Whether the requester of the display list is a layer. If so,
13732     * the view will avoid creating a layer inside the resulting display list.
13733     * @return A new or reused DisplayList object.
13734     */
13735    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13736        if (!canHaveDisplayList()) {
13737            return null;
13738        }
13739
13740        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13741                displayList == null || !displayList.isValid() ||
13742                (!isLayer && mRecreateDisplayList))) {
13743            // Don't need to recreate the display list, just need to tell our
13744            // children to restore/recreate theirs
13745            if (displayList != null && displayList.isValid() &&
13746                    !isLayer && !mRecreateDisplayList) {
13747                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13748                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13749                dispatchGetDisplayList();
13750
13751                return displayList;
13752            }
13753
13754            if (!isLayer) {
13755                // If we got here, we're recreating it. Mark it as such to ensure that
13756                // we copy in child display lists into ours in drawChild()
13757                mRecreateDisplayList = true;
13758            }
13759            if (displayList == null) {
13760                displayList = DisplayList.create(getClass().getName());
13761                // If we're creating a new display list, make sure our parent gets invalidated
13762                // since they will need to recreate their display list to account for this
13763                // new child display list.
13764                invalidateParentCaches();
13765            }
13766
13767            boolean caching = false;
13768            int width = mRight - mLeft;
13769            int height = mBottom - mTop;
13770            int layerType = getLayerType();
13771
13772            final HardwareCanvas canvas = displayList.start(width, height);
13773
13774            try {
13775                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13776                    if (layerType == LAYER_TYPE_HARDWARE) {
13777                        final HardwareLayer layer = getHardwareLayer();
13778                        if (layer != null && layer.isValid()) {
13779                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13780                        } else {
13781                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13782                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13783                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13784                        }
13785                        caching = true;
13786                    } else {
13787                        buildDrawingCache(true);
13788                        Bitmap cache = getDrawingCache(true);
13789                        if (cache != null) {
13790                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13791                            caching = true;
13792                        }
13793                    }
13794                } else {
13795
13796                    computeScroll();
13797
13798                    canvas.translate(-mScrollX, -mScrollY);
13799                    if (!isLayer) {
13800                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13801                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13802                    }
13803
13804                    // Fast path for layouts with no backgrounds
13805                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13806                        dispatchDraw(canvas);
13807                        if (mOverlay != null && !mOverlay.isEmpty()) {
13808                            mOverlay.getOverlayView().draw(canvas);
13809                        }
13810                    } else {
13811                        draw(canvas);
13812                    }
13813                }
13814            } finally {
13815                displayList.end();
13816                displayList.setCaching(caching);
13817                if (isLayer) {
13818                    displayList.setLeftTopRightBottom(0, 0, width, height);
13819                } else {
13820                    setDisplayListProperties(displayList);
13821                }
13822            }
13823        } else if (!isLayer) {
13824            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13825            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13826        }
13827
13828        return displayList;
13829    }
13830
13831    /**
13832     * Get the DisplayList for the HardwareLayer
13833     *
13834     * @param layer The HardwareLayer whose DisplayList we want
13835     * @return A DisplayList fopr the specified HardwareLayer
13836     */
13837    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13838        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13839        layer.setDisplayList(displayList);
13840        return displayList;
13841    }
13842
13843
13844    /**
13845     * <p>Returns a display list that can be used to draw this view again
13846     * without executing its draw method.</p>
13847     *
13848     * @return A DisplayList ready to replay, or null if caching is not enabled.
13849     *
13850     * @hide
13851     */
13852    public DisplayList getDisplayList() {
13853        mDisplayList = getDisplayList(mDisplayList, false);
13854        return mDisplayList;
13855    }
13856
13857    private void clearDisplayList() {
13858        if (mDisplayList != null) {
13859            mDisplayList.clear();
13860        }
13861
13862        if (mBackgroundDisplayList != null) {
13863            mBackgroundDisplayList.clear();
13864        }
13865    }
13866
13867    private void resetDisplayList() {
13868        if (mDisplayList != null) {
13869            mDisplayList.reset();
13870        }
13871
13872        if (mBackgroundDisplayList != null) {
13873            mBackgroundDisplayList.reset();
13874        }
13875    }
13876
13877    /**
13878     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13879     *
13880     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13881     *
13882     * @see #getDrawingCache(boolean)
13883     */
13884    public Bitmap getDrawingCache() {
13885        return getDrawingCache(false);
13886    }
13887
13888    /**
13889     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13890     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13891     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13892     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13893     * request the drawing cache by calling this method and draw it on screen if the
13894     * returned bitmap is not null.</p>
13895     *
13896     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13897     * this method will create a bitmap of the same size as this view. Because this bitmap
13898     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13899     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13900     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13901     * size than the view. This implies that your application must be able to handle this
13902     * size.</p>
13903     *
13904     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13905     *        the current density of the screen when the application is in compatibility
13906     *        mode.
13907     *
13908     * @return A bitmap representing this view or null if cache is disabled.
13909     *
13910     * @see #setDrawingCacheEnabled(boolean)
13911     * @see #isDrawingCacheEnabled()
13912     * @see #buildDrawingCache(boolean)
13913     * @see #destroyDrawingCache()
13914     */
13915    public Bitmap getDrawingCache(boolean autoScale) {
13916        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13917            return null;
13918        }
13919        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13920            buildDrawingCache(autoScale);
13921        }
13922        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13923    }
13924
13925    /**
13926     * <p>Frees the resources used by the drawing cache. If you call
13927     * {@link #buildDrawingCache()} manually without calling
13928     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13929     * should cleanup the cache with this method afterwards.</p>
13930     *
13931     * @see #setDrawingCacheEnabled(boolean)
13932     * @see #buildDrawingCache()
13933     * @see #getDrawingCache()
13934     */
13935    public void destroyDrawingCache() {
13936        if (mDrawingCache != null) {
13937            mDrawingCache.recycle();
13938            mDrawingCache = null;
13939        }
13940        if (mUnscaledDrawingCache != null) {
13941            mUnscaledDrawingCache.recycle();
13942            mUnscaledDrawingCache = null;
13943        }
13944    }
13945
13946    /**
13947     * Setting a solid background color for the drawing cache's bitmaps will improve
13948     * performance and memory usage. Note, though that this should only be used if this
13949     * view will always be drawn on top of a solid color.
13950     *
13951     * @param color The background color to use for the drawing cache's bitmap
13952     *
13953     * @see #setDrawingCacheEnabled(boolean)
13954     * @see #buildDrawingCache()
13955     * @see #getDrawingCache()
13956     */
13957    public void setDrawingCacheBackgroundColor(int color) {
13958        if (color != mDrawingCacheBackgroundColor) {
13959            mDrawingCacheBackgroundColor = color;
13960            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13961        }
13962    }
13963
13964    /**
13965     * @see #setDrawingCacheBackgroundColor(int)
13966     *
13967     * @return The background color to used for the drawing cache's bitmap
13968     */
13969    public int getDrawingCacheBackgroundColor() {
13970        return mDrawingCacheBackgroundColor;
13971    }
13972
13973    /**
13974     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13975     *
13976     * @see #buildDrawingCache(boolean)
13977     */
13978    public void buildDrawingCache() {
13979        buildDrawingCache(false);
13980    }
13981
13982    /**
13983     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13984     *
13985     * <p>If you call {@link #buildDrawingCache()} manually without calling
13986     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13987     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13988     *
13989     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13990     * this method will create a bitmap of the same size as this view. Because this bitmap
13991     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13992     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13993     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13994     * size than the view. This implies that your application must be able to handle this
13995     * size.</p>
13996     *
13997     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13998     * you do not need the drawing cache bitmap, calling this method will increase memory
13999     * usage and cause the view to be rendered in software once, thus negatively impacting
14000     * performance.</p>
14001     *
14002     * @see #getDrawingCache()
14003     * @see #destroyDrawingCache()
14004     */
14005    public void buildDrawingCache(boolean autoScale) {
14006        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14007                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14008            mCachingFailed = false;
14009
14010            int width = mRight - mLeft;
14011            int height = mBottom - mTop;
14012
14013            final AttachInfo attachInfo = mAttachInfo;
14014            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14015
14016            if (autoScale && scalingRequired) {
14017                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14018                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14019            }
14020
14021            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14022            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14023            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14024
14025            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14026            final long drawingCacheSize =
14027                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14028            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14029                if (width > 0 && height > 0) {
14030                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14031                            + projectedBitmapSize + " bytes, only "
14032                            + drawingCacheSize + " available");
14033                }
14034                destroyDrawingCache();
14035                mCachingFailed = true;
14036                return;
14037            }
14038
14039            boolean clear = true;
14040            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14041
14042            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14043                Bitmap.Config quality;
14044                if (!opaque) {
14045                    // Never pick ARGB_4444 because it looks awful
14046                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14047                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14048                        case DRAWING_CACHE_QUALITY_AUTO:
14049                        case DRAWING_CACHE_QUALITY_LOW:
14050                        case DRAWING_CACHE_QUALITY_HIGH:
14051                        default:
14052                            quality = Bitmap.Config.ARGB_8888;
14053                            break;
14054                    }
14055                } else {
14056                    // Optimization for translucent windows
14057                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14058                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14059                }
14060
14061                // Try to cleanup memory
14062                if (bitmap != null) bitmap.recycle();
14063
14064                try {
14065                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14066                            width, height, quality);
14067                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14068                    if (autoScale) {
14069                        mDrawingCache = bitmap;
14070                    } else {
14071                        mUnscaledDrawingCache = bitmap;
14072                    }
14073                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14074                } catch (OutOfMemoryError e) {
14075                    // If there is not enough memory to create the bitmap cache, just
14076                    // ignore the issue as bitmap caches are not required to draw the
14077                    // view hierarchy
14078                    if (autoScale) {
14079                        mDrawingCache = null;
14080                    } else {
14081                        mUnscaledDrawingCache = null;
14082                    }
14083                    mCachingFailed = true;
14084                    return;
14085                }
14086
14087                clear = drawingCacheBackgroundColor != 0;
14088            }
14089
14090            Canvas canvas;
14091            if (attachInfo != null) {
14092                canvas = attachInfo.mCanvas;
14093                if (canvas == null) {
14094                    canvas = new Canvas();
14095                }
14096                canvas.setBitmap(bitmap);
14097                // Temporarily clobber the cached Canvas in case one of our children
14098                // is also using a drawing cache. Without this, the children would
14099                // steal the canvas by attaching their own bitmap to it and bad, bad
14100                // thing would happen (invisible views, corrupted drawings, etc.)
14101                attachInfo.mCanvas = null;
14102            } else {
14103                // This case should hopefully never or seldom happen
14104                canvas = new Canvas(bitmap);
14105            }
14106
14107            if (clear) {
14108                bitmap.eraseColor(drawingCacheBackgroundColor);
14109            }
14110
14111            computeScroll();
14112            final int restoreCount = canvas.save();
14113
14114            if (autoScale && scalingRequired) {
14115                final float scale = attachInfo.mApplicationScale;
14116                canvas.scale(scale, scale);
14117            }
14118
14119            canvas.translate(-mScrollX, -mScrollY);
14120
14121            mPrivateFlags |= PFLAG_DRAWN;
14122            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14123                    mLayerType != LAYER_TYPE_NONE) {
14124                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14125            }
14126
14127            // Fast path for layouts with no backgrounds
14128            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14129                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14130                dispatchDraw(canvas);
14131                if (mOverlay != null && !mOverlay.isEmpty()) {
14132                    mOverlay.getOverlayView().draw(canvas);
14133                }
14134            } else {
14135                draw(canvas);
14136            }
14137
14138            canvas.restoreToCount(restoreCount);
14139            canvas.setBitmap(null);
14140
14141            if (attachInfo != null) {
14142                // Restore the cached Canvas for our siblings
14143                attachInfo.mCanvas = canvas;
14144            }
14145        }
14146    }
14147
14148    /**
14149     * Create a snapshot of the view into a bitmap.  We should probably make
14150     * some form of this public, but should think about the API.
14151     */
14152    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14153        int width = mRight - mLeft;
14154        int height = mBottom - mTop;
14155
14156        final AttachInfo attachInfo = mAttachInfo;
14157        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14158        width = (int) ((width * scale) + 0.5f);
14159        height = (int) ((height * scale) + 0.5f);
14160
14161        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14162                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14163        if (bitmap == null) {
14164            throw new OutOfMemoryError();
14165        }
14166
14167        Resources resources = getResources();
14168        if (resources != null) {
14169            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14170        }
14171
14172        Canvas canvas;
14173        if (attachInfo != null) {
14174            canvas = attachInfo.mCanvas;
14175            if (canvas == null) {
14176                canvas = new Canvas();
14177            }
14178            canvas.setBitmap(bitmap);
14179            // Temporarily clobber the cached Canvas in case one of our children
14180            // is also using a drawing cache. Without this, the children would
14181            // steal the canvas by attaching their own bitmap to it and bad, bad
14182            // things would happen (invisible views, corrupted drawings, etc.)
14183            attachInfo.mCanvas = null;
14184        } else {
14185            // This case should hopefully never or seldom happen
14186            canvas = new Canvas(bitmap);
14187        }
14188
14189        if ((backgroundColor & 0xff000000) != 0) {
14190            bitmap.eraseColor(backgroundColor);
14191        }
14192
14193        computeScroll();
14194        final int restoreCount = canvas.save();
14195        canvas.scale(scale, scale);
14196        canvas.translate(-mScrollX, -mScrollY);
14197
14198        // Temporarily remove the dirty mask
14199        int flags = mPrivateFlags;
14200        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14201
14202        // Fast path for layouts with no backgrounds
14203        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14204            dispatchDraw(canvas);
14205            if (mOverlay != null && !mOverlay.isEmpty()) {
14206                mOverlay.getOverlayView().draw(canvas);
14207            }
14208        } else {
14209            draw(canvas);
14210        }
14211
14212        mPrivateFlags = flags;
14213
14214        canvas.restoreToCount(restoreCount);
14215        canvas.setBitmap(null);
14216
14217        if (attachInfo != null) {
14218            // Restore the cached Canvas for our siblings
14219            attachInfo.mCanvas = canvas;
14220        }
14221
14222        return bitmap;
14223    }
14224
14225    /**
14226     * Indicates whether this View is currently in edit mode. A View is usually
14227     * in edit mode when displayed within a developer tool. For instance, if
14228     * this View is being drawn by a visual user interface builder, this method
14229     * should return true.
14230     *
14231     * Subclasses should check the return value of this method to provide
14232     * different behaviors if their normal behavior might interfere with the
14233     * host environment. For instance: the class spawns a thread in its
14234     * constructor, the drawing code relies on device-specific features, etc.
14235     *
14236     * This method is usually checked in the drawing code of custom widgets.
14237     *
14238     * @return True if this View is in edit mode, false otherwise.
14239     */
14240    public boolean isInEditMode() {
14241        return false;
14242    }
14243
14244    /**
14245     * If the View draws content inside its padding and enables fading edges,
14246     * it needs to support padding offsets. Padding offsets are added to the
14247     * fading edges to extend the length of the fade so that it covers pixels
14248     * drawn inside the padding.
14249     *
14250     * Subclasses of this class should override this method if they need
14251     * to draw content inside the padding.
14252     *
14253     * @return True if padding offset must be applied, false otherwise.
14254     *
14255     * @see #getLeftPaddingOffset()
14256     * @see #getRightPaddingOffset()
14257     * @see #getTopPaddingOffset()
14258     * @see #getBottomPaddingOffset()
14259     *
14260     * @since CURRENT
14261     */
14262    protected boolean isPaddingOffsetRequired() {
14263        return false;
14264    }
14265
14266    /**
14267     * Amount by which to extend the left fading region. Called only when
14268     * {@link #isPaddingOffsetRequired()} returns true.
14269     *
14270     * @return The left padding offset in pixels.
14271     *
14272     * @see #isPaddingOffsetRequired()
14273     *
14274     * @since CURRENT
14275     */
14276    protected int getLeftPaddingOffset() {
14277        return 0;
14278    }
14279
14280    /**
14281     * Amount by which to extend the right fading region. Called only when
14282     * {@link #isPaddingOffsetRequired()} returns true.
14283     *
14284     * @return The right padding offset in pixels.
14285     *
14286     * @see #isPaddingOffsetRequired()
14287     *
14288     * @since CURRENT
14289     */
14290    protected int getRightPaddingOffset() {
14291        return 0;
14292    }
14293
14294    /**
14295     * Amount by which to extend the top fading region. Called only when
14296     * {@link #isPaddingOffsetRequired()} returns true.
14297     *
14298     * @return The top padding offset in pixels.
14299     *
14300     * @see #isPaddingOffsetRequired()
14301     *
14302     * @since CURRENT
14303     */
14304    protected int getTopPaddingOffset() {
14305        return 0;
14306    }
14307
14308    /**
14309     * Amount by which to extend the bottom fading region. Called only when
14310     * {@link #isPaddingOffsetRequired()} returns true.
14311     *
14312     * @return The bottom padding offset in pixels.
14313     *
14314     * @see #isPaddingOffsetRequired()
14315     *
14316     * @since CURRENT
14317     */
14318    protected int getBottomPaddingOffset() {
14319        return 0;
14320    }
14321
14322    /**
14323     * @hide
14324     * @param offsetRequired
14325     */
14326    protected int getFadeTop(boolean offsetRequired) {
14327        int top = mPaddingTop;
14328        if (offsetRequired) top += getTopPaddingOffset();
14329        return top;
14330    }
14331
14332    /**
14333     * @hide
14334     * @param offsetRequired
14335     */
14336    protected int getFadeHeight(boolean offsetRequired) {
14337        int padding = mPaddingTop;
14338        if (offsetRequired) padding += getTopPaddingOffset();
14339        return mBottom - mTop - mPaddingBottom - padding;
14340    }
14341
14342    /**
14343     * <p>Indicates whether this view is attached to a hardware accelerated
14344     * window or not.</p>
14345     *
14346     * <p>Even if this method returns true, it does not mean that every call
14347     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14348     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14349     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14350     * window is hardware accelerated,
14351     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14352     * return false, and this method will return true.</p>
14353     *
14354     * @return True if the view is attached to a window and the window is
14355     *         hardware accelerated; false in any other case.
14356     */
14357    public boolean isHardwareAccelerated() {
14358        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14359    }
14360
14361    /**
14362     * Sets a rectangular area on this view to which the view will be clipped
14363     * when it is drawn. Setting the value to null will remove the clip bounds
14364     * and the view will draw normally, using its full bounds.
14365     *
14366     * @param clipBounds The rectangular area, in the local coordinates of
14367     * this view, to which future drawing operations will be clipped.
14368     */
14369    public void setClipBounds(Rect clipBounds) {
14370        if (clipBounds != null) {
14371            if (clipBounds.equals(mClipBounds)) {
14372                return;
14373            }
14374            if (mClipBounds == null) {
14375                invalidate();
14376                mClipBounds = new Rect(clipBounds);
14377            } else {
14378                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14379                        Math.min(mClipBounds.top, clipBounds.top),
14380                        Math.max(mClipBounds.right, clipBounds.right),
14381                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14382                mClipBounds.set(clipBounds);
14383            }
14384        } else {
14385            if (mClipBounds != null) {
14386                invalidate();
14387                mClipBounds = null;
14388            }
14389        }
14390    }
14391
14392    /**
14393     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14394     *
14395     * @return A copy of the current clip bounds if clip bounds are set,
14396     * otherwise null.
14397     */
14398    public Rect getClipBounds() {
14399        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14400    }
14401
14402    /**
14403     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14404     * case of an active Animation being run on the view.
14405     */
14406    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14407            Animation a, boolean scalingRequired) {
14408        Transformation invalidationTransform;
14409        final int flags = parent.mGroupFlags;
14410        final boolean initialized = a.isInitialized();
14411        if (!initialized) {
14412            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14413            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14414            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14415            onAnimationStart();
14416        }
14417
14418        final Transformation t = parent.getChildTransformation();
14419        boolean more = a.getTransformation(drawingTime, t, 1f);
14420        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14421            if (parent.mInvalidationTransformation == null) {
14422                parent.mInvalidationTransformation = new Transformation();
14423            }
14424            invalidationTransform = parent.mInvalidationTransformation;
14425            a.getTransformation(drawingTime, invalidationTransform, 1f);
14426        } else {
14427            invalidationTransform = t;
14428        }
14429
14430        if (more) {
14431            if (!a.willChangeBounds()) {
14432                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14433                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14434                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14435                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14436                    // The child need to draw an animation, potentially offscreen, so
14437                    // make sure we do not cancel invalidate requests
14438                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14439                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14440                }
14441            } else {
14442                if (parent.mInvalidateRegion == null) {
14443                    parent.mInvalidateRegion = new RectF();
14444                }
14445                final RectF region = parent.mInvalidateRegion;
14446                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14447                        invalidationTransform);
14448
14449                // The child need to draw an animation, potentially offscreen, so
14450                // make sure we do not cancel invalidate requests
14451                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14452
14453                final int left = mLeft + (int) region.left;
14454                final int top = mTop + (int) region.top;
14455                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14456                        top + (int) (region.height() + .5f));
14457            }
14458        }
14459        return more;
14460    }
14461
14462    /**
14463     * This method is called by getDisplayList() when a display list is created or re-rendered.
14464     * It sets or resets the current value of all properties on that display list (resetting is
14465     * necessary when a display list is being re-created, because we need to make sure that
14466     * previously-set transform values
14467     */
14468    void setDisplayListProperties(DisplayList displayList) {
14469        if (displayList != null) {
14470            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14471            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14472            if (mParent instanceof ViewGroup) {
14473                displayList.setClipToBounds(
14474                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14475            }
14476            if (this instanceof ViewGroup) {
14477                displayList.setIsolatedZVolume(
14478                        (((ViewGroup) this).mGroupFlags & ViewGroup.FLAG_ISOLATED_Z_VOLUME) != 0);
14479            }
14480            displayList.setOutline(mOutline);
14481            float alpha = 1;
14482            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14483                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14484                ViewGroup parentVG = (ViewGroup) mParent;
14485                final Transformation t = parentVG.getChildTransformation();
14486                if (parentVG.getChildStaticTransformation(this, t)) {
14487                    final int transformType = t.getTransformationType();
14488                    if (transformType != Transformation.TYPE_IDENTITY) {
14489                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14490                            alpha = t.getAlpha();
14491                        }
14492                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14493                            displayList.setMatrix(t.getMatrix());
14494                        }
14495                    }
14496                }
14497            }
14498            if (mTransformationInfo != null) {
14499                alpha *= getFinalAlpha();
14500                if (alpha < 1) {
14501                    final int multipliedAlpha = (int) (255 * alpha);
14502                    if (onSetAlpha(multipliedAlpha)) {
14503                        alpha = 1;
14504                    }
14505                }
14506                displayList.setTransformationInfo(alpha,
14507                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14508                        mTransformationInfo.mTranslationZ,
14509                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14510                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14511                        mTransformationInfo.mScaleY);
14512                if (mTransformationInfo.mCamera == null) {
14513                    mTransformationInfo.mCamera = new Camera();
14514                    mTransformationInfo.matrix3D = new Matrix();
14515                }
14516                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14517                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14518                    displayList.setPivotX(getPivotX());
14519                    displayList.setPivotY(getPivotY());
14520                }
14521            } else if (alpha < 1) {
14522                displayList.setAlpha(alpha);
14523            }
14524        }
14525    }
14526
14527    /**
14528     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14529     * This draw() method is an implementation detail and is not intended to be overridden or
14530     * to be called from anywhere else other than ViewGroup.drawChild().
14531     */
14532    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14533        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14534        boolean more = false;
14535        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14536        final int flags = parent.mGroupFlags;
14537
14538        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14539            parent.getChildTransformation().clear();
14540            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14541        }
14542
14543        Transformation transformToApply = null;
14544        boolean concatMatrix = false;
14545
14546        boolean scalingRequired = false;
14547        boolean caching;
14548        int layerType = getLayerType();
14549
14550        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14551        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14552                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14553            caching = true;
14554            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14555            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14556        } else {
14557            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14558        }
14559
14560        final Animation a = getAnimation();
14561        if (a != null) {
14562            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14563            concatMatrix = a.willChangeTransformationMatrix();
14564            if (concatMatrix) {
14565                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14566            }
14567            transformToApply = parent.getChildTransformation();
14568        } else {
14569            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14570                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14571                // No longer animating: clear out old animation matrix
14572                mDisplayList.setAnimationMatrix(null);
14573                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14574            }
14575            if (!useDisplayListProperties &&
14576                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14577                final Transformation t = parent.getChildTransformation();
14578                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14579                if (hasTransform) {
14580                    final int transformType = t.getTransformationType();
14581                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14582                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14583                }
14584            }
14585        }
14586
14587        concatMatrix |= !childHasIdentityMatrix;
14588
14589        // Sets the flag as early as possible to allow draw() implementations
14590        // to call invalidate() successfully when doing animations
14591        mPrivateFlags |= PFLAG_DRAWN;
14592
14593        if (!concatMatrix &&
14594                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14595                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14596                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14597                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14598            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14599            return more;
14600        }
14601        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14602
14603        if (hardwareAccelerated) {
14604            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14605            // retain the flag's value temporarily in the mRecreateDisplayList flag
14606            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14607            mPrivateFlags &= ~PFLAG_INVALIDATED;
14608        }
14609
14610        DisplayList displayList = null;
14611        Bitmap cache = null;
14612        boolean hasDisplayList = false;
14613        if (caching) {
14614            if (!hardwareAccelerated) {
14615                if (layerType != LAYER_TYPE_NONE) {
14616                    layerType = LAYER_TYPE_SOFTWARE;
14617                    buildDrawingCache(true);
14618                }
14619                cache = getDrawingCache(true);
14620            } else {
14621                switch (layerType) {
14622                    case LAYER_TYPE_SOFTWARE:
14623                        if (useDisplayListProperties) {
14624                            hasDisplayList = canHaveDisplayList();
14625                        } else {
14626                            buildDrawingCache(true);
14627                            cache = getDrawingCache(true);
14628                        }
14629                        break;
14630                    case LAYER_TYPE_HARDWARE:
14631                        if (useDisplayListProperties) {
14632                            hasDisplayList = canHaveDisplayList();
14633                        }
14634                        break;
14635                    case LAYER_TYPE_NONE:
14636                        // Delay getting the display list until animation-driven alpha values are
14637                        // set up and possibly passed on to the view
14638                        hasDisplayList = canHaveDisplayList();
14639                        break;
14640                }
14641            }
14642        }
14643        useDisplayListProperties &= hasDisplayList;
14644        if (useDisplayListProperties) {
14645            displayList = getDisplayList();
14646            if (!displayList.isValid()) {
14647                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14648                // to getDisplayList(), the display list will be marked invalid and we should not
14649                // try to use it again.
14650                displayList = null;
14651                hasDisplayList = false;
14652                useDisplayListProperties = false;
14653            }
14654        }
14655
14656        int sx = 0;
14657        int sy = 0;
14658        if (!hasDisplayList) {
14659            computeScroll();
14660            sx = mScrollX;
14661            sy = mScrollY;
14662        }
14663
14664        final boolean hasNoCache = cache == null || hasDisplayList;
14665        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14666                layerType != LAYER_TYPE_HARDWARE;
14667
14668        int restoreTo = -1;
14669        if (!useDisplayListProperties || transformToApply != null) {
14670            restoreTo = canvas.save();
14671        }
14672        if (offsetForScroll) {
14673            canvas.translate(mLeft - sx, mTop - sy);
14674        } else {
14675            if (!useDisplayListProperties) {
14676                canvas.translate(mLeft, mTop);
14677            }
14678            if (scalingRequired) {
14679                if (useDisplayListProperties) {
14680                    // TODO: Might not need this if we put everything inside the DL
14681                    restoreTo = canvas.save();
14682                }
14683                // mAttachInfo cannot be null, otherwise scalingRequired == false
14684                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14685                canvas.scale(scale, scale);
14686            }
14687        }
14688
14689        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14690        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14691                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14692            if (transformToApply != null || !childHasIdentityMatrix) {
14693                int transX = 0;
14694                int transY = 0;
14695
14696                if (offsetForScroll) {
14697                    transX = -sx;
14698                    transY = -sy;
14699                }
14700
14701                if (transformToApply != null) {
14702                    if (concatMatrix) {
14703                        if (useDisplayListProperties) {
14704                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14705                        } else {
14706                            // Undo the scroll translation, apply the transformation matrix,
14707                            // then redo the scroll translate to get the correct result.
14708                            canvas.translate(-transX, -transY);
14709                            canvas.concat(transformToApply.getMatrix());
14710                            canvas.translate(transX, transY);
14711                        }
14712                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14713                    }
14714
14715                    float transformAlpha = transformToApply.getAlpha();
14716                    if (transformAlpha < 1) {
14717                        alpha *= transformAlpha;
14718                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14719                    }
14720                }
14721
14722                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14723                    canvas.translate(-transX, -transY);
14724                    canvas.concat(getMatrix());
14725                    canvas.translate(transX, transY);
14726                }
14727            }
14728
14729            // Deal with alpha if it is or used to be <1
14730            if (alpha < 1 ||
14731                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14732                if (alpha < 1) {
14733                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14734                } else {
14735                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14736                }
14737                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14738                if (hasNoCache) {
14739                    final int multipliedAlpha = (int) (255 * alpha);
14740                    if (!onSetAlpha(multipliedAlpha)) {
14741                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14742                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14743                                layerType != LAYER_TYPE_NONE) {
14744                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14745                        }
14746                        if (useDisplayListProperties) {
14747                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14748                        } else  if (layerType == LAYER_TYPE_NONE) {
14749                            final int scrollX = hasDisplayList ? 0 : sx;
14750                            final int scrollY = hasDisplayList ? 0 : sy;
14751                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14752                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14753                        }
14754                    } else {
14755                        // Alpha is handled by the child directly, clobber the layer's alpha
14756                        mPrivateFlags |= PFLAG_ALPHA_SET;
14757                    }
14758                }
14759            }
14760        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14761            onSetAlpha(255);
14762            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14763        }
14764
14765        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14766                !useDisplayListProperties && cache == null) {
14767            if (offsetForScroll) {
14768                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14769            } else {
14770                if (!scalingRequired || cache == null) {
14771                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14772                } else {
14773                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14774                }
14775            }
14776        }
14777
14778        if (!useDisplayListProperties && hasDisplayList) {
14779            displayList = getDisplayList();
14780            if (!displayList.isValid()) {
14781                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14782                // to getDisplayList(), the display list will be marked invalid and we should not
14783                // try to use it again.
14784                displayList = null;
14785                hasDisplayList = false;
14786            }
14787        }
14788
14789        if (hasNoCache) {
14790            boolean layerRendered = false;
14791            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14792                final HardwareLayer layer = getHardwareLayer();
14793                if (layer != null && layer.isValid()) {
14794                    mLayerPaint.setAlpha((int) (alpha * 255));
14795                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14796                    layerRendered = true;
14797                } else {
14798                    final int scrollX = hasDisplayList ? 0 : sx;
14799                    final int scrollY = hasDisplayList ? 0 : sy;
14800                    canvas.saveLayer(scrollX, scrollY,
14801                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14802                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14803                }
14804            }
14805
14806            if (!layerRendered) {
14807                if (!hasDisplayList) {
14808                    // Fast path for layouts with no backgrounds
14809                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14810                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14811                        dispatchDraw(canvas);
14812                    } else {
14813                        draw(canvas);
14814                    }
14815                } else {
14816                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14817                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14818                }
14819            }
14820        } else if (cache != null) {
14821            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14822            Paint cachePaint;
14823
14824            if (layerType == LAYER_TYPE_NONE) {
14825                cachePaint = parent.mCachePaint;
14826                if (cachePaint == null) {
14827                    cachePaint = new Paint();
14828                    cachePaint.setDither(false);
14829                    parent.mCachePaint = cachePaint;
14830                }
14831                if (alpha < 1) {
14832                    cachePaint.setAlpha((int) (alpha * 255));
14833                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14834                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14835                    cachePaint.setAlpha(255);
14836                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14837                }
14838            } else {
14839                cachePaint = mLayerPaint;
14840                cachePaint.setAlpha((int) (alpha * 255));
14841            }
14842            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14843        }
14844
14845        if (restoreTo >= 0) {
14846            canvas.restoreToCount(restoreTo);
14847        }
14848
14849        if (a != null && !more) {
14850            if (!hardwareAccelerated && !a.getFillAfter()) {
14851                onSetAlpha(255);
14852            }
14853            parent.finishAnimatingView(this, a);
14854        }
14855
14856        if (more && hardwareAccelerated) {
14857            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14858                // alpha animations should cause the child to recreate its display list
14859                invalidate(true);
14860            }
14861        }
14862
14863        mRecreateDisplayList = false;
14864
14865        return more;
14866    }
14867
14868    /**
14869     * Manually render this view (and all of its children) to the given Canvas.
14870     * The view must have already done a full layout before this function is
14871     * called.  When implementing a view, implement
14872     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14873     * If you do need to override this method, call the superclass version.
14874     *
14875     * @param canvas The Canvas to which the View is rendered.
14876     */
14877    public void draw(Canvas canvas) {
14878        if (mClipBounds != null) {
14879            canvas.clipRect(mClipBounds);
14880        }
14881        final int privateFlags = mPrivateFlags;
14882        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14883                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14884        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14885
14886        /*
14887         * Draw traversal performs several drawing steps which must be executed
14888         * in the appropriate order:
14889         *
14890         *      1. Draw the background
14891         *      2. If necessary, save the canvas' layers to prepare for fading
14892         *      3. Draw view's content
14893         *      4. Draw children
14894         *      5. If necessary, draw the fading edges and restore layers
14895         *      6. Draw decorations (scrollbars for instance)
14896         */
14897
14898        // Step 1, draw the background, if needed
14899        int saveCount;
14900
14901        if (!dirtyOpaque) {
14902            drawBackground(canvas);
14903        }
14904
14905        // skip step 2 & 5 if possible (common case)
14906        final int viewFlags = mViewFlags;
14907        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14908        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14909        if (!verticalEdges && !horizontalEdges) {
14910            // Step 3, draw the content
14911            if (!dirtyOpaque) onDraw(canvas);
14912
14913            // Step 4, draw the children
14914            dispatchDraw(canvas);
14915
14916            // Step 6, draw decorations (scrollbars)
14917            onDrawScrollBars(canvas);
14918
14919            if (mOverlay != null && !mOverlay.isEmpty()) {
14920                mOverlay.getOverlayView().dispatchDraw(canvas);
14921            }
14922
14923            // we're done...
14924            return;
14925        }
14926
14927        /*
14928         * Here we do the full fledged routine...
14929         * (this is an uncommon case where speed matters less,
14930         * this is why we repeat some of the tests that have been
14931         * done above)
14932         */
14933
14934        boolean drawTop = false;
14935        boolean drawBottom = false;
14936        boolean drawLeft = false;
14937        boolean drawRight = false;
14938
14939        float topFadeStrength = 0.0f;
14940        float bottomFadeStrength = 0.0f;
14941        float leftFadeStrength = 0.0f;
14942        float rightFadeStrength = 0.0f;
14943
14944        // Step 2, save the canvas' layers
14945        int paddingLeft = mPaddingLeft;
14946
14947        final boolean offsetRequired = isPaddingOffsetRequired();
14948        if (offsetRequired) {
14949            paddingLeft += getLeftPaddingOffset();
14950        }
14951
14952        int left = mScrollX + paddingLeft;
14953        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14954        int top = mScrollY + getFadeTop(offsetRequired);
14955        int bottom = top + getFadeHeight(offsetRequired);
14956
14957        if (offsetRequired) {
14958            right += getRightPaddingOffset();
14959            bottom += getBottomPaddingOffset();
14960        }
14961
14962        final ScrollabilityCache scrollabilityCache = mScrollCache;
14963        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14964        int length = (int) fadeHeight;
14965
14966        // clip the fade length if top and bottom fades overlap
14967        // overlapping fades produce odd-looking artifacts
14968        if (verticalEdges && (top + length > bottom - length)) {
14969            length = (bottom - top) / 2;
14970        }
14971
14972        // also clip horizontal fades if necessary
14973        if (horizontalEdges && (left + length > right - length)) {
14974            length = (right - left) / 2;
14975        }
14976
14977        if (verticalEdges) {
14978            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14979            drawTop = topFadeStrength * fadeHeight > 1.0f;
14980            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14981            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14982        }
14983
14984        if (horizontalEdges) {
14985            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14986            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14987            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14988            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14989        }
14990
14991        saveCount = canvas.getSaveCount();
14992
14993        int solidColor = getSolidColor();
14994        if (solidColor == 0) {
14995            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14996
14997            if (drawTop) {
14998                canvas.saveLayer(left, top, right, top + length, null, flags);
14999            }
15000
15001            if (drawBottom) {
15002                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15003            }
15004
15005            if (drawLeft) {
15006                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15007            }
15008
15009            if (drawRight) {
15010                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15011            }
15012        } else {
15013            scrollabilityCache.setFadeColor(solidColor);
15014        }
15015
15016        // Step 3, draw the content
15017        if (!dirtyOpaque) onDraw(canvas);
15018
15019        // Step 4, draw the children
15020        dispatchDraw(canvas);
15021
15022        // Step 5, draw the fade effect and restore layers
15023        final Paint p = scrollabilityCache.paint;
15024        final Matrix matrix = scrollabilityCache.matrix;
15025        final Shader fade = scrollabilityCache.shader;
15026
15027        if (drawTop) {
15028            matrix.setScale(1, fadeHeight * topFadeStrength);
15029            matrix.postTranslate(left, top);
15030            fade.setLocalMatrix(matrix);
15031            canvas.drawRect(left, top, right, top + length, p);
15032        }
15033
15034        if (drawBottom) {
15035            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15036            matrix.postRotate(180);
15037            matrix.postTranslate(left, bottom);
15038            fade.setLocalMatrix(matrix);
15039            canvas.drawRect(left, bottom - length, right, bottom, p);
15040        }
15041
15042        if (drawLeft) {
15043            matrix.setScale(1, fadeHeight * leftFadeStrength);
15044            matrix.postRotate(-90);
15045            matrix.postTranslate(left, top);
15046            fade.setLocalMatrix(matrix);
15047            canvas.drawRect(left, top, left + length, bottom, p);
15048        }
15049
15050        if (drawRight) {
15051            matrix.setScale(1, fadeHeight * rightFadeStrength);
15052            matrix.postRotate(90);
15053            matrix.postTranslate(right, top);
15054            fade.setLocalMatrix(matrix);
15055            canvas.drawRect(right - length, top, right, bottom, p);
15056        }
15057
15058        canvas.restoreToCount(saveCount);
15059
15060        // Step 6, draw decorations (scrollbars)
15061        onDrawScrollBars(canvas);
15062
15063        if (mOverlay != null && !mOverlay.isEmpty()) {
15064            mOverlay.getOverlayView().dispatchDraw(canvas);
15065        }
15066    }
15067
15068    /**
15069     * Draws the background onto the specified canvas.
15070     *
15071     * @param canvas Canvas on which to draw the background
15072     */
15073    private void drawBackground(Canvas canvas) {
15074        final Drawable background = mBackground;
15075        if (background == null) {
15076            return;
15077        }
15078
15079        if (mBackgroundSizeChanged) {
15080            // We should see the background invalidate itself, but just to be
15081            // careful we're going to clear the display list and force redraw.
15082            if (mBackgroundDisplayList != null) {
15083                mBackgroundDisplayList.clear();
15084            }
15085
15086            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15087            mBackgroundSizeChanged = false;
15088        }
15089
15090
15091        // Attempt to use a display list if requested.
15092        if (canvas != null && canvas.isHardwareAccelerated()) {
15093            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
15094
15095            final DisplayList displayList = mBackgroundDisplayList;
15096            if (displayList != null && displayList.isValid()) {
15097                setBackgroundDisplayListProperties(displayList);
15098                ((HardwareCanvas) canvas).drawDisplayList(displayList);
15099                return;
15100            }
15101        }
15102
15103        final int scrollX = mScrollX;
15104        final int scrollY = mScrollY;
15105        if ((scrollX | scrollY) == 0) {
15106            background.draw(canvas);
15107        } else {
15108            canvas.translate(scrollX, scrollY);
15109            background.draw(canvas);
15110            canvas.translate(-scrollX, -scrollY);
15111        }
15112    }
15113
15114    /**
15115     * Set up background drawable display list properties.
15116     *
15117     * @param displayList Valid display list for the background drawable
15118     */
15119    private void setBackgroundDisplayListProperties(DisplayList displayList) {
15120        displayList.setTranslationX(mScrollX);
15121        displayList.setTranslationY(mScrollY);
15122    }
15123
15124    /**
15125     * Creates a new display list or updates the existing display list for the
15126     * specified Drawable.
15127     *
15128     * @param drawable Drawable for which to create a display list
15129     * @param displayList Existing display list, or {@code null}
15130     * @return A valid display list for the specified drawable
15131     */
15132    private static DisplayList getDrawableDisplayList(Drawable drawable, DisplayList displayList) {
15133        if (displayList != null && displayList.isValid()) {
15134            return displayList;
15135        }
15136
15137        if (displayList == null) {
15138            displayList = DisplayList.create(drawable.getClass().getName());
15139        }
15140
15141        final Rect bounds = drawable.getBounds();
15142        final int width = bounds.width();
15143        final int height = bounds.height();
15144        final HardwareCanvas canvas = displayList.start(width, height);
15145        drawable.draw(canvas);
15146        displayList.end();
15147
15148        // Set up drawable properties that are view-independent.
15149        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15150        displayList.setProjectBackwards(drawable.isProjected());
15151        displayList.setClipToBounds(false);
15152        return displayList;
15153    }
15154
15155    /**
15156     * Returns the overlay for this view, creating it if it does not yet exist.
15157     * Adding drawables to the overlay will cause them to be displayed whenever
15158     * the view itself is redrawn. Objects in the overlay should be actively
15159     * managed: remove them when they should not be displayed anymore. The
15160     * overlay will always have the same size as its host view.
15161     *
15162     * <p>Note: Overlays do not currently work correctly with {@link
15163     * SurfaceView} or {@link TextureView}; contents in overlays for these
15164     * types of views may not display correctly.</p>
15165     *
15166     * @return The ViewOverlay object for this view.
15167     * @see ViewOverlay
15168     */
15169    public ViewOverlay getOverlay() {
15170        if (mOverlay == null) {
15171            mOverlay = new ViewOverlay(mContext, this);
15172        }
15173        return mOverlay;
15174    }
15175
15176    /**
15177     * Override this if your view is known to always be drawn on top of a solid color background,
15178     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15179     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15180     * should be set to 0xFF.
15181     *
15182     * @see #setVerticalFadingEdgeEnabled(boolean)
15183     * @see #setHorizontalFadingEdgeEnabled(boolean)
15184     *
15185     * @return The known solid color background for this view, or 0 if the color may vary
15186     */
15187    @ViewDebug.ExportedProperty(category = "drawing")
15188    public int getSolidColor() {
15189        return 0;
15190    }
15191
15192    /**
15193     * Build a human readable string representation of the specified view flags.
15194     *
15195     * @param flags the view flags to convert to a string
15196     * @return a String representing the supplied flags
15197     */
15198    private static String printFlags(int flags) {
15199        String output = "";
15200        int numFlags = 0;
15201        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15202            output += "TAKES_FOCUS";
15203            numFlags++;
15204        }
15205
15206        switch (flags & VISIBILITY_MASK) {
15207        case INVISIBLE:
15208            if (numFlags > 0) {
15209                output += " ";
15210            }
15211            output += "INVISIBLE";
15212            // USELESS HERE numFlags++;
15213            break;
15214        case GONE:
15215            if (numFlags > 0) {
15216                output += " ";
15217            }
15218            output += "GONE";
15219            // USELESS HERE numFlags++;
15220            break;
15221        default:
15222            break;
15223        }
15224        return output;
15225    }
15226
15227    /**
15228     * Build a human readable string representation of the specified private
15229     * view flags.
15230     *
15231     * @param privateFlags the private view flags to convert to a string
15232     * @return a String representing the supplied flags
15233     */
15234    private static String printPrivateFlags(int privateFlags) {
15235        String output = "";
15236        int numFlags = 0;
15237
15238        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15239            output += "WANTS_FOCUS";
15240            numFlags++;
15241        }
15242
15243        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15244            if (numFlags > 0) {
15245                output += " ";
15246            }
15247            output += "FOCUSED";
15248            numFlags++;
15249        }
15250
15251        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15252            if (numFlags > 0) {
15253                output += " ";
15254            }
15255            output += "SELECTED";
15256            numFlags++;
15257        }
15258
15259        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15260            if (numFlags > 0) {
15261                output += " ";
15262            }
15263            output += "IS_ROOT_NAMESPACE";
15264            numFlags++;
15265        }
15266
15267        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15268            if (numFlags > 0) {
15269                output += " ";
15270            }
15271            output += "HAS_BOUNDS";
15272            numFlags++;
15273        }
15274
15275        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15276            if (numFlags > 0) {
15277                output += " ";
15278            }
15279            output += "DRAWN";
15280            // USELESS HERE numFlags++;
15281        }
15282        return output;
15283    }
15284
15285    /**
15286     * <p>Indicates whether or not this view's layout will be requested during
15287     * the next hierarchy layout pass.</p>
15288     *
15289     * @return true if the layout will be forced during next layout pass
15290     */
15291    public boolean isLayoutRequested() {
15292        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15293    }
15294
15295    /**
15296     * Return true if o is a ViewGroup that is laying out using optical bounds.
15297     * @hide
15298     */
15299    public static boolean isLayoutModeOptical(Object o) {
15300        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15301    }
15302
15303    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15304        Insets parentInsets = mParent instanceof View ?
15305                ((View) mParent).getOpticalInsets() : Insets.NONE;
15306        Insets childInsets = getOpticalInsets();
15307        return setFrame(
15308                left   + parentInsets.left - childInsets.left,
15309                top    + parentInsets.top  - childInsets.top,
15310                right  + parentInsets.left + childInsets.right,
15311                bottom + parentInsets.top  + childInsets.bottom);
15312    }
15313
15314    /**
15315     * Assign a size and position to a view and all of its
15316     * descendants
15317     *
15318     * <p>This is the second phase of the layout mechanism.
15319     * (The first is measuring). In this phase, each parent calls
15320     * layout on all of its children to position them.
15321     * This is typically done using the child measurements
15322     * that were stored in the measure pass().</p>
15323     *
15324     * <p>Derived classes should not override this method.
15325     * Derived classes with children should override
15326     * onLayout. In that method, they should
15327     * call layout on each of their children.</p>
15328     *
15329     * @param l Left position, relative to parent
15330     * @param t Top position, relative to parent
15331     * @param r Right position, relative to parent
15332     * @param b Bottom position, relative to parent
15333     */
15334    @SuppressWarnings({"unchecked"})
15335    public void layout(int l, int t, int r, int b) {
15336        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15337            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15338            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15339        }
15340
15341        int oldL = mLeft;
15342        int oldT = mTop;
15343        int oldB = mBottom;
15344        int oldR = mRight;
15345
15346        boolean changed = isLayoutModeOptical(mParent) ?
15347                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15348
15349        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15350            onLayout(changed, l, t, r, b);
15351            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15352
15353            ListenerInfo li = mListenerInfo;
15354            if (li != null && li.mOnLayoutChangeListeners != null) {
15355                ArrayList<OnLayoutChangeListener> listenersCopy =
15356                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15357                int numListeners = listenersCopy.size();
15358                for (int i = 0; i < numListeners; ++i) {
15359                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15360                }
15361            }
15362        }
15363
15364        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15365        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15366    }
15367
15368    /**
15369     * Called from layout when this view should
15370     * assign a size and position to each of its children.
15371     *
15372     * Derived classes with children should override
15373     * this method and call layout on each of
15374     * their children.
15375     * @param changed This is a new size or position for this view
15376     * @param left Left position, relative to parent
15377     * @param top Top position, relative to parent
15378     * @param right Right position, relative to parent
15379     * @param bottom Bottom position, relative to parent
15380     */
15381    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15382    }
15383
15384    /**
15385     * Assign a size and position to this view.
15386     *
15387     * This is called from layout.
15388     *
15389     * @param left Left position, relative to parent
15390     * @param top Top position, relative to parent
15391     * @param right Right position, relative to parent
15392     * @param bottom Bottom position, relative to parent
15393     * @return true if the new size and position are different than the
15394     *         previous ones
15395     * {@hide}
15396     */
15397    protected boolean setFrame(int left, int top, int right, int bottom) {
15398        boolean changed = false;
15399
15400        if (DBG) {
15401            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15402                    + right + "," + bottom + ")");
15403        }
15404
15405        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15406            changed = true;
15407
15408            // Remember our drawn bit
15409            int drawn = mPrivateFlags & PFLAG_DRAWN;
15410
15411            int oldWidth = mRight - mLeft;
15412            int oldHeight = mBottom - mTop;
15413            int newWidth = right - left;
15414            int newHeight = bottom - top;
15415            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15416
15417            // Invalidate our old position
15418            invalidate(sizeChanged);
15419
15420            mLeft = left;
15421            mTop = top;
15422            mRight = right;
15423            mBottom = bottom;
15424            if (mDisplayList != null) {
15425                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15426            }
15427
15428            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15429
15430
15431            if (sizeChanged) {
15432                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
15433                    // A change in dimension means an auto-centered pivot point changes, too
15434                    if (mTransformationInfo != null) {
15435                        mTransformationInfo.mMatrixDirty = true;
15436                    }
15437                }
15438                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15439            }
15440
15441            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15442                // If we are visible, force the DRAWN bit to on so that
15443                // this invalidate will go through (at least to our parent).
15444                // This is because someone may have invalidated this view
15445                // before this call to setFrame came in, thereby clearing
15446                // the DRAWN bit.
15447                mPrivateFlags |= PFLAG_DRAWN;
15448                invalidate(sizeChanged);
15449                // parent display list may need to be recreated based on a change in the bounds
15450                // of any child
15451                invalidateParentCaches();
15452            }
15453
15454            // Reset drawn bit to original value (invalidate turns it off)
15455            mPrivateFlags |= drawn;
15456
15457            mBackgroundSizeChanged = true;
15458
15459            notifySubtreeAccessibilityStateChangedIfNeeded();
15460        }
15461        return changed;
15462    }
15463
15464    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15465        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15466        if (mOverlay != null) {
15467            mOverlay.getOverlayView().setRight(newWidth);
15468            mOverlay.getOverlayView().setBottom(newHeight);
15469        }
15470    }
15471
15472    /**
15473     * Finalize inflating a view from XML.  This is called as the last phase
15474     * of inflation, after all child views have been added.
15475     *
15476     * <p>Even if the subclass overrides onFinishInflate, they should always be
15477     * sure to call the super method, so that we get called.
15478     */
15479    protected void onFinishInflate() {
15480    }
15481
15482    /**
15483     * Returns the resources associated with this view.
15484     *
15485     * @return Resources object.
15486     */
15487    public Resources getResources() {
15488        return mResources;
15489    }
15490
15491    /**
15492     * Invalidates the specified Drawable.
15493     *
15494     * @param drawable the drawable to invalidate
15495     */
15496    @Override
15497    public void invalidateDrawable(Drawable drawable) {
15498        if (verifyDrawable(drawable)) {
15499            if (drawable == mBackground && mBackgroundDisplayList != null) {
15500                // We'll need to redraw the display list.
15501                mBackgroundDisplayList.clear();
15502            }
15503
15504            final Rect dirty = drawable.getDirtyBounds();
15505            final int scrollX = mScrollX;
15506            final int scrollY = mScrollY;
15507
15508            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15509                    dirty.right + scrollX, dirty.bottom + scrollY);
15510        }
15511    }
15512
15513    /**
15514     * Schedules an action on a drawable to occur at a specified time.
15515     *
15516     * @param who the recipient of the action
15517     * @param what the action to run on the drawable
15518     * @param when the time at which the action must occur. Uses the
15519     *        {@link SystemClock#uptimeMillis} timebase.
15520     */
15521    @Override
15522    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15523        if (verifyDrawable(who) && what != null) {
15524            final long delay = when - SystemClock.uptimeMillis();
15525            if (mAttachInfo != null) {
15526                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15527                        Choreographer.CALLBACK_ANIMATION, what, who,
15528                        Choreographer.subtractFrameDelay(delay));
15529            } else {
15530                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15531            }
15532        }
15533    }
15534
15535    /**
15536     * Cancels a scheduled action on a drawable.
15537     *
15538     * @param who the recipient of the action
15539     * @param what the action to cancel
15540     */
15541    @Override
15542    public void unscheduleDrawable(Drawable who, Runnable what) {
15543        if (verifyDrawable(who) && what != null) {
15544            if (mAttachInfo != null) {
15545                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15546                        Choreographer.CALLBACK_ANIMATION, what, who);
15547            }
15548            ViewRootImpl.getRunQueue().removeCallbacks(what);
15549        }
15550    }
15551
15552    /**
15553     * Unschedule any events associated with the given Drawable.  This can be
15554     * used when selecting a new Drawable into a view, so that the previous
15555     * one is completely unscheduled.
15556     *
15557     * @param who The Drawable to unschedule.
15558     *
15559     * @see #drawableStateChanged
15560     */
15561    public void unscheduleDrawable(Drawable who) {
15562        if (mAttachInfo != null && who != null) {
15563            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15564                    Choreographer.CALLBACK_ANIMATION, null, who);
15565        }
15566    }
15567
15568    /**
15569     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15570     * that the View directionality can and will be resolved before its Drawables.
15571     *
15572     * Will call {@link View#onResolveDrawables} when resolution is done.
15573     *
15574     * @hide
15575     */
15576    protected void resolveDrawables() {
15577        // Drawables resolution may need to happen before resolving the layout direction (which is
15578        // done only during the measure() call).
15579        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15580        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15581        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15582        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15583        // direction to be resolved as its resolved value will be the same as its raw value.
15584        if (!isLayoutDirectionResolved() &&
15585                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15586            return;
15587        }
15588
15589        final int layoutDirection = isLayoutDirectionResolved() ?
15590                getLayoutDirection() : getRawLayoutDirection();
15591
15592        if (mBackground != null) {
15593            mBackground.setLayoutDirection(layoutDirection);
15594        }
15595        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15596        onResolveDrawables(layoutDirection);
15597    }
15598
15599    /**
15600     * Called when layout direction has been resolved.
15601     *
15602     * The default implementation does nothing.
15603     *
15604     * @param layoutDirection The resolved layout direction.
15605     *
15606     * @see #LAYOUT_DIRECTION_LTR
15607     * @see #LAYOUT_DIRECTION_RTL
15608     *
15609     * @hide
15610     */
15611    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15612    }
15613
15614    /**
15615     * @hide
15616     */
15617    protected void resetResolvedDrawables() {
15618        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15619    }
15620
15621    private boolean isDrawablesResolved() {
15622        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15623    }
15624
15625    /**
15626     * If your view subclass is displaying its own Drawable objects, it should
15627     * override this function and return true for any Drawable it is
15628     * displaying.  This allows animations for those drawables to be
15629     * scheduled.
15630     *
15631     * <p>Be sure to call through to the super class when overriding this
15632     * function.
15633     *
15634     * @param who The Drawable to verify.  Return true if it is one you are
15635     *            displaying, else return the result of calling through to the
15636     *            super class.
15637     *
15638     * @return boolean If true than the Drawable is being displayed in the
15639     *         view; else false and it is not allowed to animate.
15640     *
15641     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15642     * @see #drawableStateChanged()
15643     */
15644    protected boolean verifyDrawable(Drawable who) {
15645        return who == mBackground;
15646    }
15647
15648    /**
15649     * This function is called whenever the state of the view changes in such
15650     * a way that it impacts the state of drawables being shown.
15651     *
15652     * <p>Be sure to call through to the superclass when overriding this
15653     * function.
15654     *
15655     * @see Drawable#setState(int[])
15656     */
15657    protected void drawableStateChanged() {
15658        final Drawable d = mBackground;
15659        if (d != null && d.isStateful()) {
15660            d.setState(getDrawableState());
15661        }
15662    }
15663
15664    /**
15665     * Call this to force a view to update its drawable state. This will cause
15666     * drawableStateChanged to be called on this view. Views that are interested
15667     * in the new state should call getDrawableState.
15668     *
15669     * @see #drawableStateChanged
15670     * @see #getDrawableState
15671     */
15672    public void refreshDrawableState() {
15673        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15674        drawableStateChanged();
15675
15676        ViewParent parent = mParent;
15677        if (parent != null) {
15678            parent.childDrawableStateChanged(this);
15679        }
15680    }
15681
15682    /**
15683     * Return an array of resource IDs of the drawable states representing the
15684     * current state of the view.
15685     *
15686     * @return The current drawable state
15687     *
15688     * @see Drawable#setState(int[])
15689     * @see #drawableStateChanged()
15690     * @see #onCreateDrawableState(int)
15691     */
15692    public final int[] getDrawableState() {
15693        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15694            return mDrawableState;
15695        } else {
15696            mDrawableState = onCreateDrawableState(0);
15697            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15698            return mDrawableState;
15699        }
15700    }
15701
15702    /**
15703     * Generate the new {@link android.graphics.drawable.Drawable} state for
15704     * this view. This is called by the view
15705     * system when the cached Drawable state is determined to be invalid.  To
15706     * retrieve the current state, you should use {@link #getDrawableState}.
15707     *
15708     * @param extraSpace if non-zero, this is the number of extra entries you
15709     * would like in the returned array in which you can place your own
15710     * states.
15711     *
15712     * @return Returns an array holding the current {@link Drawable} state of
15713     * the view.
15714     *
15715     * @see #mergeDrawableStates(int[], int[])
15716     */
15717    protected int[] onCreateDrawableState(int extraSpace) {
15718        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15719                mParent instanceof View) {
15720            return ((View) mParent).onCreateDrawableState(extraSpace);
15721        }
15722
15723        int[] drawableState;
15724
15725        int privateFlags = mPrivateFlags;
15726
15727        int viewStateIndex = 0;
15728        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15729        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15730        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15731        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15732        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15733        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15734        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15735                HardwareRenderer.isAvailable()) {
15736            // This is set if HW acceleration is requested, even if the current
15737            // process doesn't allow it.  This is just to allow app preview
15738            // windows to better match their app.
15739            viewStateIndex |= VIEW_STATE_ACCELERATED;
15740        }
15741        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15742
15743        final int privateFlags2 = mPrivateFlags2;
15744        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15745        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15746
15747        drawableState = VIEW_STATE_SETS[viewStateIndex];
15748
15749        //noinspection ConstantIfStatement
15750        if (false) {
15751            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15752            Log.i("View", toString()
15753                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15754                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15755                    + " fo=" + hasFocus()
15756                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15757                    + " wf=" + hasWindowFocus()
15758                    + ": " + Arrays.toString(drawableState));
15759        }
15760
15761        if (extraSpace == 0) {
15762            return drawableState;
15763        }
15764
15765        final int[] fullState;
15766        if (drawableState != null) {
15767            fullState = new int[drawableState.length + extraSpace];
15768            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15769        } else {
15770            fullState = new int[extraSpace];
15771        }
15772
15773        return fullState;
15774    }
15775
15776    /**
15777     * Merge your own state values in <var>additionalState</var> into the base
15778     * state values <var>baseState</var> that were returned by
15779     * {@link #onCreateDrawableState(int)}.
15780     *
15781     * @param baseState The base state values returned by
15782     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15783     * own additional state values.
15784     *
15785     * @param additionalState The additional state values you would like
15786     * added to <var>baseState</var>; this array is not modified.
15787     *
15788     * @return As a convenience, the <var>baseState</var> array you originally
15789     * passed into the function is returned.
15790     *
15791     * @see #onCreateDrawableState(int)
15792     */
15793    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15794        final int N = baseState.length;
15795        int i = N - 1;
15796        while (i >= 0 && baseState[i] == 0) {
15797            i--;
15798        }
15799        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15800        return baseState;
15801    }
15802
15803    /**
15804     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15805     * on all Drawable objects associated with this view.
15806     */
15807    public void jumpDrawablesToCurrentState() {
15808        if (mBackground != null) {
15809            mBackground.jumpToCurrentState();
15810        }
15811    }
15812
15813    /**
15814     * Sets the background color for this view.
15815     * @param color the color of the background
15816     */
15817    @RemotableViewMethod
15818    public void setBackgroundColor(int color) {
15819        if (mBackground instanceof ColorDrawable) {
15820            ((ColorDrawable) mBackground.mutate()).setColor(color);
15821            computeOpaqueFlags();
15822            mBackgroundResource = 0;
15823        } else {
15824            setBackground(new ColorDrawable(color));
15825        }
15826    }
15827
15828    /**
15829     * Set the background to a given resource. The resource should refer to
15830     * a Drawable object or 0 to remove the background.
15831     * @param resid The identifier of the resource.
15832     *
15833     * @attr ref android.R.styleable#View_background
15834     */
15835    @RemotableViewMethod
15836    public void setBackgroundResource(int resid) {
15837        if (resid != 0 && resid == mBackgroundResource) {
15838            return;
15839        }
15840
15841        Drawable d= null;
15842        if (resid != 0) {
15843            d = mContext.getDrawable(resid);
15844        }
15845        setBackground(d);
15846
15847        mBackgroundResource = resid;
15848    }
15849
15850    /**
15851     * Set the background to a given Drawable, or remove the background. If the
15852     * background has padding, this View's padding is set to the background's
15853     * padding. However, when a background is removed, this View's padding isn't
15854     * touched. If setting the padding is desired, please use
15855     * {@link #setPadding(int, int, int, int)}.
15856     *
15857     * @param background The Drawable to use as the background, or null to remove the
15858     *        background
15859     */
15860    public void setBackground(Drawable background) {
15861        //noinspection deprecation
15862        setBackgroundDrawable(background);
15863    }
15864
15865    /**
15866     * @deprecated use {@link #setBackground(Drawable)} instead
15867     */
15868    @Deprecated
15869    public void setBackgroundDrawable(Drawable background) {
15870        computeOpaqueFlags();
15871
15872        if (background == mBackground) {
15873            return;
15874        }
15875
15876        boolean requestLayout = false;
15877
15878        mBackgroundResource = 0;
15879
15880        /*
15881         * Regardless of whether we're setting a new background or not, we want
15882         * to clear the previous drawable.
15883         */
15884        if (mBackground != null) {
15885            mBackground.setCallback(null);
15886            unscheduleDrawable(mBackground);
15887        }
15888
15889        if (background != null) {
15890            Rect padding = sThreadLocal.get();
15891            if (padding == null) {
15892                padding = new Rect();
15893                sThreadLocal.set(padding);
15894            }
15895            resetResolvedDrawables();
15896            background.setLayoutDirection(getLayoutDirection());
15897            if (background.getPadding(padding)) {
15898                resetResolvedPadding();
15899                switch (background.getLayoutDirection()) {
15900                    case LAYOUT_DIRECTION_RTL:
15901                        mUserPaddingLeftInitial = padding.right;
15902                        mUserPaddingRightInitial = padding.left;
15903                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15904                        break;
15905                    case LAYOUT_DIRECTION_LTR:
15906                    default:
15907                        mUserPaddingLeftInitial = padding.left;
15908                        mUserPaddingRightInitial = padding.right;
15909                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15910                }
15911                mLeftPaddingDefined = false;
15912                mRightPaddingDefined = false;
15913            }
15914
15915            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15916            // if it has a different minimum size, we should layout again
15917            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15918                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15919                requestLayout = true;
15920            }
15921
15922            background.setCallback(this);
15923            if (background.isStateful()) {
15924                background.setState(getDrawableState());
15925            }
15926            background.setVisible(getVisibility() == VISIBLE, false);
15927            mBackground = background;
15928
15929            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15930                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15931                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15932                requestLayout = true;
15933            }
15934        } else {
15935            /* Remove the background */
15936            mBackground = null;
15937
15938            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15939                /*
15940                 * This view ONLY drew the background before and we're removing
15941                 * the background, so now it won't draw anything
15942                 * (hence we SKIP_DRAW)
15943                 */
15944                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15945                mPrivateFlags |= PFLAG_SKIP_DRAW;
15946            }
15947
15948            /*
15949             * When the background is set, we try to apply its padding to this
15950             * View. When the background is removed, we don't touch this View's
15951             * padding. This is noted in the Javadocs. Hence, we don't need to
15952             * requestLayout(), the invalidate() below is sufficient.
15953             */
15954
15955            // The old background's minimum size could have affected this
15956            // View's layout, so let's requestLayout
15957            requestLayout = true;
15958        }
15959
15960        computeOpaqueFlags();
15961
15962        if (requestLayout) {
15963            requestLayout();
15964        }
15965
15966        mBackgroundSizeChanged = true;
15967        invalidate(true);
15968    }
15969
15970    /**
15971     * Gets the background drawable
15972     *
15973     * @return The drawable used as the background for this view, if any.
15974     *
15975     * @see #setBackground(Drawable)
15976     *
15977     * @attr ref android.R.styleable#View_background
15978     */
15979    public Drawable getBackground() {
15980        return mBackground;
15981    }
15982
15983    /**
15984     * Sets the padding. The view may add on the space required to display
15985     * the scrollbars, depending on the style and visibility of the scrollbars.
15986     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15987     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15988     * from the values set in this call.
15989     *
15990     * @attr ref android.R.styleable#View_padding
15991     * @attr ref android.R.styleable#View_paddingBottom
15992     * @attr ref android.R.styleable#View_paddingLeft
15993     * @attr ref android.R.styleable#View_paddingRight
15994     * @attr ref android.R.styleable#View_paddingTop
15995     * @param left the left padding in pixels
15996     * @param top the top padding in pixels
15997     * @param right the right padding in pixels
15998     * @param bottom the bottom padding in pixels
15999     */
16000    public void setPadding(int left, int top, int right, int bottom) {
16001        resetResolvedPadding();
16002
16003        mUserPaddingStart = UNDEFINED_PADDING;
16004        mUserPaddingEnd = UNDEFINED_PADDING;
16005
16006        mUserPaddingLeftInitial = left;
16007        mUserPaddingRightInitial = right;
16008
16009        mLeftPaddingDefined = true;
16010        mRightPaddingDefined = true;
16011
16012        internalSetPadding(left, top, right, bottom);
16013    }
16014
16015    /**
16016     * @hide
16017     */
16018    protected void internalSetPadding(int left, int top, int right, int bottom) {
16019        mUserPaddingLeft = left;
16020        mUserPaddingRight = right;
16021        mUserPaddingBottom = bottom;
16022
16023        final int viewFlags = mViewFlags;
16024        boolean changed = false;
16025
16026        // Common case is there are no scroll bars.
16027        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16028            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16029                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16030                        ? 0 : getVerticalScrollbarWidth();
16031                switch (mVerticalScrollbarPosition) {
16032                    case SCROLLBAR_POSITION_DEFAULT:
16033                        if (isLayoutRtl()) {
16034                            left += offset;
16035                        } else {
16036                            right += offset;
16037                        }
16038                        break;
16039                    case SCROLLBAR_POSITION_RIGHT:
16040                        right += offset;
16041                        break;
16042                    case SCROLLBAR_POSITION_LEFT:
16043                        left += offset;
16044                        break;
16045                }
16046            }
16047            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16048                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16049                        ? 0 : getHorizontalScrollbarHeight();
16050            }
16051        }
16052
16053        if (mPaddingLeft != left) {
16054            changed = true;
16055            mPaddingLeft = left;
16056        }
16057        if (mPaddingTop != top) {
16058            changed = true;
16059            mPaddingTop = top;
16060        }
16061        if (mPaddingRight != right) {
16062            changed = true;
16063            mPaddingRight = right;
16064        }
16065        if (mPaddingBottom != bottom) {
16066            changed = true;
16067            mPaddingBottom = bottom;
16068        }
16069
16070        if (changed) {
16071            requestLayout();
16072        }
16073    }
16074
16075    /**
16076     * Sets the relative padding. The view may add on the space required to display
16077     * the scrollbars, depending on the style and visibility of the scrollbars.
16078     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16079     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16080     * from the values set in this call.
16081     *
16082     * @attr ref android.R.styleable#View_padding
16083     * @attr ref android.R.styleable#View_paddingBottom
16084     * @attr ref android.R.styleable#View_paddingStart
16085     * @attr ref android.R.styleable#View_paddingEnd
16086     * @attr ref android.R.styleable#View_paddingTop
16087     * @param start the start padding in pixels
16088     * @param top the top padding in pixels
16089     * @param end the end padding in pixels
16090     * @param bottom the bottom padding in pixels
16091     */
16092    public void setPaddingRelative(int start, int top, int end, int bottom) {
16093        resetResolvedPadding();
16094
16095        mUserPaddingStart = start;
16096        mUserPaddingEnd = end;
16097        mLeftPaddingDefined = true;
16098        mRightPaddingDefined = true;
16099
16100        switch(getLayoutDirection()) {
16101            case LAYOUT_DIRECTION_RTL:
16102                mUserPaddingLeftInitial = end;
16103                mUserPaddingRightInitial = start;
16104                internalSetPadding(end, top, start, bottom);
16105                break;
16106            case LAYOUT_DIRECTION_LTR:
16107            default:
16108                mUserPaddingLeftInitial = start;
16109                mUserPaddingRightInitial = end;
16110                internalSetPadding(start, top, end, bottom);
16111        }
16112    }
16113
16114    /**
16115     * Returns the top padding of this view.
16116     *
16117     * @return the top padding in pixels
16118     */
16119    public int getPaddingTop() {
16120        return mPaddingTop;
16121    }
16122
16123    /**
16124     * Returns the bottom padding of this view. If there are inset and enabled
16125     * scrollbars, this value may include the space required to display the
16126     * scrollbars as well.
16127     *
16128     * @return the bottom padding in pixels
16129     */
16130    public int getPaddingBottom() {
16131        return mPaddingBottom;
16132    }
16133
16134    /**
16135     * Returns the left padding of this view. If there are inset and enabled
16136     * scrollbars, this value may include the space required to display the
16137     * scrollbars as well.
16138     *
16139     * @return the left padding in pixels
16140     */
16141    public int getPaddingLeft() {
16142        if (!isPaddingResolved()) {
16143            resolvePadding();
16144        }
16145        return mPaddingLeft;
16146    }
16147
16148    /**
16149     * Returns the start padding of this view depending on its resolved layout direction.
16150     * If there are inset and enabled scrollbars, this value may include the space
16151     * required to display the scrollbars as well.
16152     *
16153     * @return the start padding in pixels
16154     */
16155    public int getPaddingStart() {
16156        if (!isPaddingResolved()) {
16157            resolvePadding();
16158        }
16159        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16160                mPaddingRight : mPaddingLeft;
16161    }
16162
16163    /**
16164     * Returns the right padding of this view. If there are inset and enabled
16165     * scrollbars, this value may include the space required to display the
16166     * scrollbars as well.
16167     *
16168     * @return the right padding in pixels
16169     */
16170    public int getPaddingRight() {
16171        if (!isPaddingResolved()) {
16172            resolvePadding();
16173        }
16174        return mPaddingRight;
16175    }
16176
16177    /**
16178     * Returns the end padding of this view depending on its resolved layout direction.
16179     * If there are inset and enabled scrollbars, this value may include the space
16180     * required to display the scrollbars as well.
16181     *
16182     * @return the end padding in pixels
16183     */
16184    public int getPaddingEnd() {
16185        if (!isPaddingResolved()) {
16186            resolvePadding();
16187        }
16188        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16189                mPaddingLeft : mPaddingRight;
16190    }
16191
16192    /**
16193     * Return if the padding as been set thru relative values
16194     * {@link #setPaddingRelative(int, int, int, int)} or thru
16195     * @attr ref android.R.styleable#View_paddingStart or
16196     * @attr ref android.R.styleable#View_paddingEnd
16197     *
16198     * @return true if the padding is relative or false if it is not.
16199     */
16200    public boolean isPaddingRelative() {
16201        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16202    }
16203
16204    Insets computeOpticalInsets() {
16205        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16206    }
16207
16208    /**
16209     * @hide
16210     */
16211    public void resetPaddingToInitialValues() {
16212        if (isRtlCompatibilityMode()) {
16213            mPaddingLeft = mUserPaddingLeftInitial;
16214            mPaddingRight = mUserPaddingRightInitial;
16215            return;
16216        }
16217        if (isLayoutRtl()) {
16218            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16219            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16220        } else {
16221            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16222            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16223        }
16224    }
16225
16226    /**
16227     * @hide
16228     */
16229    public Insets getOpticalInsets() {
16230        if (mLayoutInsets == null) {
16231            mLayoutInsets = computeOpticalInsets();
16232        }
16233        return mLayoutInsets;
16234    }
16235
16236    /**
16237     * Changes the selection state of this view. A view can be selected or not.
16238     * Note that selection is not the same as focus. Views are typically
16239     * selected in the context of an AdapterView like ListView or GridView;
16240     * the selected view is the view that is highlighted.
16241     *
16242     * @param selected true if the view must be selected, false otherwise
16243     */
16244    public void setSelected(boolean selected) {
16245        //noinspection DoubleNegation
16246        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16247            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16248            if (!selected) resetPressedState();
16249            invalidate(true);
16250            refreshDrawableState();
16251            dispatchSetSelected(selected);
16252            notifyViewAccessibilityStateChangedIfNeeded(
16253                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16254        }
16255    }
16256
16257    /**
16258     * Dispatch setSelected to all of this View's children.
16259     *
16260     * @see #setSelected(boolean)
16261     *
16262     * @param selected The new selected state
16263     */
16264    protected void dispatchSetSelected(boolean selected) {
16265    }
16266
16267    /**
16268     * Indicates the selection state of this view.
16269     *
16270     * @return true if the view is selected, false otherwise
16271     */
16272    @ViewDebug.ExportedProperty
16273    public boolean isSelected() {
16274        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16275    }
16276
16277    /**
16278     * Changes the activated state of this view. A view can be activated or not.
16279     * Note that activation is not the same as selection.  Selection is
16280     * a transient property, representing the view (hierarchy) the user is
16281     * currently interacting with.  Activation is a longer-term state that the
16282     * user can move views in and out of.  For example, in a list view with
16283     * single or multiple selection enabled, the views in the current selection
16284     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16285     * here.)  The activated state is propagated down to children of the view it
16286     * is set on.
16287     *
16288     * @param activated true if the view must be activated, false otherwise
16289     */
16290    public void setActivated(boolean activated) {
16291        //noinspection DoubleNegation
16292        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16293            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16294            invalidate(true);
16295            refreshDrawableState();
16296            dispatchSetActivated(activated);
16297        }
16298    }
16299
16300    /**
16301     * Dispatch setActivated to all of this View's children.
16302     *
16303     * @see #setActivated(boolean)
16304     *
16305     * @param activated The new activated state
16306     */
16307    protected void dispatchSetActivated(boolean activated) {
16308    }
16309
16310    /**
16311     * Indicates the activation state of this view.
16312     *
16313     * @return true if the view is activated, false otherwise
16314     */
16315    @ViewDebug.ExportedProperty
16316    public boolean isActivated() {
16317        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16318    }
16319
16320    /**
16321     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16322     * observer can be used to get notifications when global events, like
16323     * layout, happen.
16324     *
16325     * The returned ViewTreeObserver observer is not guaranteed to remain
16326     * valid for the lifetime of this View. If the caller of this method keeps
16327     * a long-lived reference to ViewTreeObserver, it should always check for
16328     * the return value of {@link ViewTreeObserver#isAlive()}.
16329     *
16330     * @return The ViewTreeObserver for this view's hierarchy.
16331     */
16332    public ViewTreeObserver getViewTreeObserver() {
16333        if (mAttachInfo != null) {
16334            return mAttachInfo.mTreeObserver;
16335        }
16336        if (mFloatingTreeObserver == null) {
16337            mFloatingTreeObserver = new ViewTreeObserver();
16338        }
16339        return mFloatingTreeObserver;
16340    }
16341
16342    /**
16343     * <p>Finds the topmost view in the current view hierarchy.</p>
16344     *
16345     * @return the topmost view containing this view
16346     */
16347    public View getRootView() {
16348        if (mAttachInfo != null) {
16349            final View v = mAttachInfo.mRootView;
16350            if (v != null) {
16351                return v;
16352            }
16353        }
16354
16355        View parent = this;
16356
16357        while (parent.mParent != null && parent.mParent instanceof View) {
16358            parent = (View) parent.mParent;
16359        }
16360
16361        return parent;
16362    }
16363
16364    /**
16365     * Transforms a motion event from view-local coordinates to on-screen
16366     * coordinates.
16367     *
16368     * @param ev the view-local motion event
16369     * @return false if the transformation could not be applied
16370     * @hide
16371     */
16372    public boolean toGlobalMotionEvent(MotionEvent ev) {
16373        final AttachInfo info = mAttachInfo;
16374        if (info == null) {
16375            return false;
16376        }
16377
16378        final Matrix m = info.mTmpMatrix;
16379        m.set(Matrix.IDENTITY_MATRIX);
16380        transformMatrixToGlobal(m);
16381        ev.transform(m);
16382        return true;
16383    }
16384
16385    /**
16386     * Transforms a motion event from on-screen coordinates to view-local
16387     * coordinates.
16388     *
16389     * @param ev the on-screen motion event
16390     * @return false if the transformation could not be applied
16391     * @hide
16392     */
16393    public boolean toLocalMotionEvent(MotionEvent ev) {
16394        final AttachInfo info = mAttachInfo;
16395        if (info == null) {
16396            return false;
16397        }
16398
16399        final Matrix m = info.mTmpMatrix;
16400        m.set(Matrix.IDENTITY_MATRIX);
16401        transformMatrixToLocal(m);
16402        ev.transform(m);
16403        return true;
16404    }
16405
16406    /**
16407     * Modifies the input matrix such that it maps view-local coordinates to
16408     * on-screen coordinates.
16409     *
16410     * @param m input matrix to modify
16411     */
16412    void transformMatrixToGlobal(Matrix m) {
16413        final ViewParent parent = mParent;
16414        if (parent instanceof View) {
16415            final View vp = (View) parent;
16416            vp.transformMatrixToGlobal(m);
16417            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16418        } else if (parent instanceof ViewRootImpl) {
16419            final ViewRootImpl vr = (ViewRootImpl) parent;
16420            vr.transformMatrixToGlobal(m);
16421            m.postTranslate(0, -vr.mCurScrollY);
16422        }
16423
16424        m.postTranslate(mLeft, mTop);
16425
16426        if (!hasIdentityMatrix()) {
16427            m.postConcat(getMatrix());
16428        }
16429    }
16430
16431    /**
16432     * Modifies the input matrix such that it maps on-screen coordinates to
16433     * view-local coordinates.
16434     *
16435     * @param m input matrix to modify
16436     */
16437    void transformMatrixToLocal(Matrix m) {
16438        final ViewParent parent = mParent;
16439        if (parent instanceof View) {
16440            final View vp = (View) parent;
16441            vp.transformMatrixToLocal(m);
16442            m.preTranslate(vp.mScrollX, vp.mScrollY);
16443        } else if (parent instanceof ViewRootImpl) {
16444            final ViewRootImpl vr = (ViewRootImpl) parent;
16445            vr.transformMatrixToLocal(m);
16446            m.preTranslate(0, vr.mCurScrollY);
16447        }
16448
16449        m.preTranslate(-mLeft, -mTop);
16450
16451        if (!hasIdentityMatrix()) {
16452            m.preConcat(getInverseMatrix());
16453        }
16454    }
16455
16456    /**
16457     * <p>Computes the coordinates of this view on the screen. The argument
16458     * must be an array of two integers. After the method returns, the array
16459     * contains the x and y location in that order.</p>
16460     *
16461     * @param location an array of two integers in which to hold the coordinates
16462     */
16463    public void getLocationOnScreen(int[] location) {
16464        getLocationInWindow(location);
16465
16466        final AttachInfo info = mAttachInfo;
16467        if (info != null) {
16468            location[0] += info.mWindowLeft;
16469            location[1] += info.mWindowTop;
16470        }
16471    }
16472
16473    /**
16474     * <p>Computes the coordinates of this view in its window. The argument
16475     * must be an array of two integers. After the method returns, the array
16476     * contains the x and y location in that order.</p>
16477     *
16478     * @param location an array of two integers in which to hold the coordinates
16479     */
16480    public void getLocationInWindow(int[] location) {
16481        if (location == null || location.length < 2) {
16482            throw new IllegalArgumentException("location must be an array of two integers");
16483        }
16484
16485        if (mAttachInfo == null) {
16486            // When the view is not attached to a window, this method does not make sense
16487            location[0] = location[1] = 0;
16488            return;
16489        }
16490
16491        float[] position = mAttachInfo.mTmpTransformLocation;
16492        position[0] = position[1] = 0.0f;
16493
16494        if (!hasIdentityMatrix()) {
16495            getMatrix().mapPoints(position);
16496        }
16497
16498        position[0] += mLeft;
16499        position[1] += mTop;
16500
16501        ViewParent viewParent = mParent;
16502        while (viewParent instanceof View) {
16503            final View view = (View) viewParent;
16504
16505            position[0] -= view.mScrollX;
16506            position[1] -= view.mScrollY;
16507
16508            if (!view.hasIdentityMatrix()) {
16509                view.getMatrix().mapPoints(position);
16510            }
16511
16512            position[0] += view.mLeft;
16513            position[1] += view.mTop;
16514
16515            viewParent = view.mParent;
16516         }
16517
16518        if (viewParent instanceof ViewRootImpl) {
16519            // *cough*
16520            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16521            position[1] -= vr.mCurScrollY;
16522        }
16523
16524        location[0] = (int) (position[0] + 0.5f);
16525        location[1] = (int) (position[1] + 0.5f);
16526    }
16527
16528    /**
16529     * {@hide}
16530     * @param id the id of the view to be found
16531     * @return the view of the specified id, null if cannot be found
16532     */
16533    protected View findViewTraversal(int id) {
16534        if (id == mID) {
16535            return this;
16536        }
16537        return null;
16538    }
16539
16540    /**
16541     * {@hide}
16542     * @param tag the tag of the view to be found
16543     * @return the view of specified tag, null if cannot be found
16544     */
16545    protected View findViewWithTagTraversal(Object tag) {
16546        if (tag != null && tag.equals(mTag)) {
16547            return this;
16548        }
16549        return null;
16550    }
16551
16552    /**
16553     * {@hide}
16554     * @param predicate The predicate to evaluate.
16555     * @param childToSkip If not null, ignores this child during the recursive traversal.
16556     * @return The first view that matches the predicate or null.
16557     */
16558    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16559        if (predicate.apply(this)) {
16560            return this;
16561        }
16562        return null;
16563    }
16564
16565    /**
16566     * Look for a child view with the given id.  If this view has the given
16567     * id, return this view.
16568     *
16569     * @param id The id to search for.
16570     * @return The view that has the given id in the hierarchy or null
16571     */
16572    public final View findViewById(int id) {
16573        if (id < 0) {
16574            return null;
16575        }
16576        return findViewTraversal(id);
16577    }
16578
16579    /**
16580     * Finds a view by its unuque and stable accessibility id.
16581     *
16582     * @param accessibilityId The searched accessibility id.
16583     * @return The found view.
16584     */
16585    final View findViewByAccessibilityId(int accessibilityId) {
16586        if (accessibilityId < 0) {
16587            return null;
16588        }
16589        return findViewByAccessibilityIdTraversal(accessibilityId);
16590    }
16591
16592    /**
16593     * Performs the traversal to find a view by its unuque and stable accessibility id.
16594     *
16595     * <strong>Note:</strong>This method does not stop at the root namespace
16596     * boundary since the user can touch the screen at an arbitrary location
16597     * potentially crossing the root namespace bounday which will send an
16598     * accessibility event to accessibility services and they should be able
16599     * to obtain the event source. Also accessibility ids are guaranteed to be
16600     * unique in the window.
16601     *
16602     * @param accessibilityId The accessibility id.
16603     * @return The found view.
16604     *
16605     * @hide
16606     */
16607    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16608        if (getAccessibilityViewId() == accessibilityId) {
16609            return this;
16610        }
16611        return null;
16612    }
16613
16614    /**
16615     * Look for a child view with the given tag.  If this view has the given
16616     * tag, return this view.
16617     *
16618     * @param tag The tag to search for, using "tag.equals(getTag())".
16619     * @return The View that has the given tag in the hierarchy or null
16620     */
16621    public final View findViewWithTag(Object tag) {
16622        if (tag == null) {
16623            return null;
16624        }
16625        return findViewWithTagTraversal(tag);
16626    }
16627
16628    /**
16629     * {@hide}
16630     * Look for a child view that matches the specified predicate.
16631     * If this view matches the predicate, return this view.
16632     *
16633     * @param predicate The predicate to evaluate.
16634     * @return The first view that matches the predicate or null.
16635     */
16636    public final View findViewByPredicate(Predicate<View> predicate) {
16637        return findViewByPredicateTraversal(predicate, null);
16638    }
16639
16640    /**
16641     * {@hide}
16642     * Look for a child view that matches the specified predicate,
16643     * starting with the specified view and its descendents and then
16644     * recusively searching the ancestors and siblings of that view
16645     * until this view is reached.
16646     *
16647     * This method is useful in cases where the predicate does not match
16648     * a single unique view (perhaps multiple views use the same id)
16649     * and we are trying to find the view that is "closest" in scope to the
16650     * starting view.
16651     *
16652     * @param start The view to start from.
16653     * @param predicate The predicate to evaluate.
16654     * @return The first view that matches the predicate or null.
16655     */
16656    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16657        View childToSkip = null;
16658        for (;;) {
16659            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16660            if (view != null || start == this) {
16661                return view;
16662            }
16663
16664            ViewParent parent = start.getParent();
16665            if (parent == null || !(parent instanceof View)) {
16666                return null;
16667            }
16668
16669            childToSkip = start;
16670            start = (View) parent;
16671        }
16672    }
16673
16674    /**
16675     * Sets the identifier for this view. The identifier does not have to be
16676     * unique in this view's hierarchy. The identifier should be a positive
16677     * number.
16678     *
16679     * @see #NO_ID
16680     * @see #getId()
16681     * @see #findViewById(int)
16682     *
16683     * @param id a number used to identify the view
16684     *
16685     * @attr ref android.R.styleable#View_id
16686     */
16687    public void setId(int id) {
16688        mID = id;
16689        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16690            mID = generateViewId();
16691        }
16692    }
16693
16694    /**
16695     * {@hide}
16696     *
16697     * @param isRoot true if the view belongs to the root namespace, false
16698     *        otherwise
16699     */
16700    public void setIsRootNamespace(boolean isRoot) {
16701        if (isRoot) {
16702            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16703        } else {
16704            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16705        }
16706    }
16707
16708    /**
16709     * {@hide}
16710     *
16711     * @return true if the view belongs to the root namespace, false otherwise
16712     */
16713    public boolean isRootNamespace() {
16714        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16715    }
16716
16717    /**
16718     * Returns this view's identifier.
16719     *
16720     * @return a positive integer used to identify the view or {@link #NO_ID}
16721     *         if the view has no ID
16722     *
16723     * @see #setId(int)
16724     * @see #findViewById(int)
16725     * @attr ref android.R.styleable#View_id
16726     */
16727    @ViewDebug.CapturedViewProperty
16728    public int getId() {
16729        return mID;
16730    }
16731
16732    /**
16733     * Returns this view's tag.
16734     *
16735     * @return the Object stored in this view as a tag, or {@code null} if not
16736     *         set
16737     *
16738     * @see #setTag(Object)
16739     * @see #getTag(int)
16740     */
16741    @ViewDebug.ExportedProperty
16742    public Object getTag() {
16743        return mTag;
16744    }
16745
16746    /**
16747     * Sets the tag associated with this view. A tag can be used to mark
16748     * a view in its hierarchy and does not have to be unique within the
16749     * hierarchy. Tags can also be used to store data within a view without
16750     * resorting to another data structure.
16751     *
16752     * @param tag an Object to tag the view with
16753     *
16754     * @see #getTag()
16755     * @see #setTag(int, Object)
16756     */
16757    public void setTag(final Object tag) {
16758        mTag = tag;
16759    }
16760
16761    /**
16762     * Returns the tag associated with this view and the specified key.
16763     *
16764     * @param key The key identifying the tag
16765     *
16766     * @return the Object stored in this view as a tag, or {@code null} if not
16767     *         set
16768     *
16769     * @see #setTag(int, Object)
16770     * @see #getTag()
16771     */
16772    public Object getTag(int key) {
16773        if (mKeyedTags != null) return mKeyedTags.get(key);
16774        return null;
16775    }
16776
16777    /**
16778     * Sets a tag associated with this view and a key. A tag can be used
16779     * to mark a view in its hierarchy and does not have to be unique within
16780     * the hierarchy. Tags can also be used to store data within a view
16781     * without resorting to another data structure.
16782     *
16783     * The specified key should be an id declared in the resources of the
16784     * application to ensure it is unique (see the <a
16785     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16786     * Keys identified as belonging to
16787     * the Android framework or not associated with any package will cause
16788     * an {@link IllegalArgumentException} to be thrown.
16789     *
16790     * @param key The key identifying the tag
16791     * @param tag An Object to tag the view with
16792     *
16793     * @throws IllegalArgumentException If they specified key is not valid
16794     *
16795     * @see #setTag(Object)
16796     * @see #getTag(int)
16797     */
16798    public void setTag(int key, final Object tag) {
16799        // If the package id is 0x00 or 0x01, it's either an undefined package
16800        // or a framework id
16801        if ((key >>> 24) < 2) {
16802            throw new IllegalArgumentException("The key must be an application-specific "
16803                    + "resource id.");
16804        }
16805
16806        setKeyedTag(key, tag);
16807    }
16808
16809    /**
16810     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16811     * framework id.
16812     *
16813     * @hide
16814     */
16815    public void setTagInternal(int key, Object tag) {
16816        if ((key >>> 24) != 0x1) {
16817            throw new IllegalArgumentException("The key must be a framework-specific "
16818                    + "resource id.");
16819        }
16820
16821        setKeyedTag(key, tag);
16822    }
16823
16824    private void setKeyedTag(int key, Object tag) {
16825        if (mKeyedTags == null) {
16826            mKeyedTags = new SparseArray<Object>(2);
16827        }
16828
16829        mKeyedTags.put(key, tag);
16830    }
16831
16832    /**
16833     * Prints information about this view in the log output, with the tag
16834     * {@link #VIEW_LOG_TAG}.
16835     *
16836     * @hide
16837     */
16838    public void debug() {
16839        debug(0);
16840    }
16841
16842    /**
16843     * Prints information about this view in the log output, with the tag
16844     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16845     * indentation defined by the <code>depth</code>.
16846     *
16847     * @param depth the indentation level
16848     *
16849     * @hide
16850     */
16851    protected void debug(int depth) {
16852        String output = debugIndent(depth - 1);
16853
16854        output += "+ " + this;
16855        int id = getId();
16856        if (id != -1) {
16857            output += " (id=" + id + ")";
16858        }
16859        Object tag = getTag();
16860        if (tag != null) {
16861            output += " (tag=" + tag + ")";
16862        }
16863        Log.d(VIEW_LOG_TAG, output);
16864
16865        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16866            output = debugIndent(depth) + " FOCUSED";
16867            Log.d(VIEW_LOG_TAG, output);
16868        }
16869
16870        output = debugIndent(depth);
16871        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16872                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16873                + "} ";
16874        Log.d(VIEW_LOG_TAG, output);
16875
16876        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16877                || mPaddingBottom != 0) {
16878            output = debugIndent(depth);
16879            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16880                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16881            Log.d(VIEW_LOG_TAG, output);
16882        }
16883
16884        output = debugIndent(depth);
16885        output += "mMeasureWidth=" + mMeasuredWidth +
16886                " mMeasureHeight=" + mMeasuredHeight;
16887        Log.d(VIEW_LOG_TAG, output);
16888
16889        output = debugIndent(depth);
16890        if (mLayoutParams == null) {
16891            output += "BAD! no layout params";
16892        } else {
16893            output = mLayoutParams.debug(output);
16894        }
16895        Log.d(VIEW_LOG_TAG, output);
16896
16897        output = debugIndent(depth);
16898        output += "flags={";
16899        output += View.printFlags(mViewFlags);
16900        output += "}";
16901        Log.d(VIEW_LOG_TAG, output);
16902
16903        output = debugIndent(depth);
16904        output += "privateFlags={";
16905        output += View.printPrivateFlags(mPrivateFlags);
16906        output += "}";
16907        Log.d(VIEW_LOG_TAG, output);
16908    }
16909
16910    /**
16911     * Creates a string of whitespaces used for indentation.
16912     *
16913     * @param depth the indentation level
16914     * @return a String containing (depth * 2 + 3) * 2 white spaces
16915     *
16916     * @hide
16917     */
16918    protected static String debugIndent(int depth) {
16919        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16920        for (int i = 0; i < (depth * 2) + 3; i++) {
16921            spaces.append(' ').append(' ');
16922        }
16923        return spaces.toString();
16924    }
16925
16926    /**
16927     * <p>Return the offset of the widget's text baseline from the widget's top
16928     * boundary. If this widget does not support baseline alignment, this
16929     * method returns -1. </p>
16930     *
16931     * @return the offset of the baseline within the widget's bounds or -1
16932     *         if baseline alignment is not supported
16933     */
16934    @ViewDebug.ExportedProperty(category = "layout")
16935    public int getBaseline() {
16936        return -1;
16937    }
16938
16939    /**
16940     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16941     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16942     * a layout pass.
16943     *
16944     * @return whether the view hierarchy is currently undergoing a layout pass
16945     */
16946    public boolean isInLayout() {
16947        ViewRootImpl viewRoot = getViewRootImpl();
16948        return (viewRoot != null && viewRoot.isInLayout());
16949    }
16950
16951    /**
16952     * Call this when something has changed which has invalidated the
16953     * layout of this view. This will schedule a layout pass of the view
16954     * tree. This should not be called while the view hierarchy is currently in a layout
16955     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16956     * end of the current layout pass (and then layout will run again) or after the current
16957     * frame is drawn and the next layout occurs.
16958     *
16959     * <p>Subclasses which override this method should call the superclass method to
16960     * handle possible request-during-layout errors correctly.</p>
16961     */
16962    public void requestLayout() {
16963        if (mMeasureCache != null) mMeasureCache.clear();
16964
16965        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16966            // Only trigger request-during-layout logic if this is the view requesting it,
16967            // not the views in its parent hierarchy
16968            ViewRootImpl viewRoot = getViewRootImpl();
16969            if (viewRoot != null && viewRoot.isInLayout()) {
16970                if (!viewRoot.requestLayoutDuringLayout(this)) {
16971                    return;
16972                }
16973            }
16974            mAttachInfo.mViewRequestingLayout = this;
16975        }
16976
16977        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16978        mPrivateFlags |= PFLAG_INVALIDATED;
16979
16980        if (mParent != null && !mParent.isLayoutRequested()) {
16981            mParent.requestLayout();
16982        }
16983        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16984            mAttachInfo.mViewRequestingLayout = null;
16985        }
16986    }
16987
16988    /**
16989     * Forces this view to be laid out during the next layout pass.
16990     * This method does not call requestLayout() or forceLayout()
16991     * on the parent.
16992     */
16993    public void forceLayout() {
16994        if (mMeasureCache != null) mMeasureCache.clear();
16995
16996        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16997        mPrivateFlags |= PFLAG_INVALIDATED;
16998    }
16999
17000    /**
17001     * <p>
17002     * This is called to find out how big a view should be. The parent
17003     * supplies constraint information in the width and height parameters.
17004     * </p>
17005     *
17006     * <p>
17007     * The actual measurement work of a view is performed in
17008     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17009     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17010     * </p>
17011     *
17012     *
17013     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17014     *        parent
17015     * @param heightMeasureSpec Vertical space requirements as imposed by the
17016     *        parent
17017     *
17018     * @see #onMeasure(int, int)
17019     */
17020    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17021        boolean optical = isLayoutModeOptical(this);
17022        if (optical != isLayoutModeOptical(mParent)) {
17023            Insets insets = getOpticalInsets();
17024            int oWidth  = insets.left + insets.right;
17025            int oHeight = insets.top  + insets.bottom;
17026            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17027            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17028        }
17029
17030        // Suppress sign extension for the low bytes
17031        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17032        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17033
17034        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17035                widthMeasureSpec != mOldWidthMeasureSpec ||
17036                heightMeasureSpec != mOldHeightMeasureSpec) {
17037
17038            // first clears the measured dimension flag
17039            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17040
17041            resolveRtlPropertiesIfNeeded();
17042
17043            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17044                    mMeasureCache.indexOfKey(key);
17045            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17046                // measure ourselves, this should set the measured dimension flag back
17047                onMeasure(widthMeasureSpec, heightMeasureSpec);
17048                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17049            } else {
17050                long value = mMeasureCache.valueAt(cacheIndex);
17051                // Casting a long to int drops the high 32 bits, no mask needed
17052                setMeasuredDimension((int) (value >> 32), (int) value);
17053                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17054            }
17055
17056            // flag not set, setMeasuredDimension() was not invoked, we raise
17057            // an exception to warn the developer
17058            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17059                throw new IllegalStateException("onMeasure() did not set the"
17060                        + " measured dimension by calling"
17061                        + " setMeasuredDimension()");
17062            }
17063
17064            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17065        }
17066
17067        mOldWidthMeasureSpec = widthMeasureSpec;
17068        mOldHeightMeasureSpec = heightMeasureSpec;
17069
17070        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17071                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17072    }
17073
17074    /**
17075     * <p>
17076     * Measure the view and its content to determine the measured width and the
17077     * measured height. This method is invoked by {@link #measure(int, int)} and
17078     * should be overriden by subclasses to provide accurate and efficient
17079     * measurement of their contents.
17080     * </p>
17081     *
17082     * <p>
17083     * <strong>CONTRACT:</strong> When overriding this method, you
17084     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17085     * measured width and height of this view. Failure to do so will trigger an
17086     * <code>IllegalStateException</code>, thrown by
17087     * {@link #measure(int, int)}. Calling the superclass'
17088     * {@link #onMeasure(int, int)} is a valid use.
17089     * </p>
17090     *
17091     * <p>
17092     * The base class implementation of measure defaults to the background size,
17093     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17094     * override {@link #onMeasure(int, int)} to provide better measurements of
17095     * their content.
17096     * </p>
17097     *
17098     * <p>
17099     * If this method is overridden, it is the subclass's responsibility to make
17100     * sure the measured height and width are at least the view's minimum height
17101     * and width ({@link #getSuggestedMinimumHeight()} and
17102     * {@link #getSuggestedMinimumWidth()}).
17103     * </p>
17104     *
17105     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17106     *                         The requirements are encoded with
17107     *                         {@link android.view.View.MeasureSpec}.
17108     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17109     *                         The requirements are encoded with
17110     *                         {@link android.view.View.MeasureSpec}.
17111     *
17112     * @see #getMeasuredWidth()
17113     * @see #getMeasuredHeight()
17114     * @see #setMeasuredDimension(int, int)
17115     * @see #getSuggestedMinimumHeight()
17116     * @see #getSuggestedMinimumWidth()
17117     * @see android.view.View.MeasureSpec#getMode(int)
17118     * @see android.view.View.MeasureSpec#getSize(int)
17119     */
17120    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17121        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17122                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17123    }
17124
17125    /**
17126     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17127     * measured width and measured height. Failing to do so will trigger an
17128     * exception at measurement time.</p>
17129     *
17130     * @param measuredWidth The measured width of this view.  May be a complex
17131     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17132     * {@link #MEASURED_STATE_TOO_SMALL}.
17133     * @param measuredHeight The measured height of this view.  May be a complex
17134     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17135     * {@link #MEASURED_STATE_TOO_SMALL}.
17136     */
17137    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17138        boolean optical = isLayoutModeOptical(this);
17139        if (optical != isLayoutModeOptical(mParent)) {
17140            Insets insets = getOpticalInsets();
17141            int opticalWidth  = insets.left + insets.right;
17142            int opticalHeight = insets.top  + insets.bottom;
17143
17144            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17145            measuredHeight += optical ? opticalHeight : -opticalHeight;
17146        }
17147        mMeasuredWidth = measuredWidth;
17148        mMeasuredHeight = measuredHeight;
17149
17150        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17151    }
17152
17153    /**
17154     * Merge two states as returned by {@link #getMeasuredState()}.
17155     * @param curState The current state as returned from a view or the result
17156     * of combining multiple views.
17157     * @param newState The new view state to combine.
17158     * @return Returns a new integer reflecting the combination of the two
17159     * states.
17160     */
17161    public static int combineMeasuredStates(int curState, int newState) {
17162        return curState | newState;
17163    }
17164
17165    /**
17166     * Version of {@link #resolveSizeAndState(int, int, int)}
17167     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17168     */
17169    public static int resolveSize(int size, int measureSpec) {
17170        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17171    }
17172
17173    /**
17174     * Utility to reconcile a desired size and state, with constraints imposed
17175     * by a MeasureSpec.  Will take the desired size, unless a different size
17176     * is imposed by the constraints.  The returned value is a compound integer,
17177     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17178     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17179     * size is smaller than the size the view wants to be.
17180     *
17181     * @param size How big the view wants to be
17182     * @param measureSpec Constraints imposed by the parent
17183     * @return Size information bit mask as defined by
17184     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17185     */
17186    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17187        int result = size;
17188        int specMode = MeasureSpec.getMode(measureSpec);
17189        int specSize =  MeasureSpec.getSize(measureSpec);
17190        switch (specMode) {
17191        case MeasureSpec.UNSPECIFIED:
17192            result = size;
17193            break;
17194        case MeasureSpec.AT_MOST:
17195            if (specSize < size) {
17196                result = specSize | MEASURED_STATE_TOO_SMALL;
17197            } else {
17198                result = size;
17199            }
17200            break;
17201        case MeasureSpec.EXACTLY:
17202            result = specSize;
17203            break;
17204        }
17205        return result | (childMeasuredState&MEASURED_STATE_MASK);
17206    }
17207
17208    /**
17209     * Utility to return a default size. Uses the supplied size if the
17210     * MeasureSpec imposed no constraints. Will get larger if allowed
17211     * by the MeasureSpec.
17212     *
17213     * @param size Default size for this view
17214     * @param measureSpec Constraints imposed by the parent
17215     * @return The size this view should be.
17216     */
17217    public static int getDefaultSize(int size, int measureSpec) {
17218        int result = size;
17219        int specMode = MeasureSpec.getMode(measureSpec);
17220        int specSize = MeasureSpec.getSize(measureSpec);
17221
17222        switch (specMode) {
17223        case MeasureSpec.UNSPECIFIED:
17224            result = size;
17225            break;
17226        case MeasureSpec.AT_MOST:
17227        case MeasureSpec.EXACTLY:
17228            result = specSize;
17229            break;
17230        }
17231        return result;
17232    }
17233
17234    /**
17235     * Returns the suggested minimum height that the view should use. This
17236     * returns the maximum of the view's minimum height
17237     * and the background's minimum height
17238     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17239     * <p>
17240     * When being used in {@link #onMeasure(int, int)}, the caller should still
17241     * ensure the returned height is within the requirements of the parent.
17242     *
17243     * @return The suggested minimum height of the view.
17244     */
17245    protected int getSuggestedMinimumHeight() {
17246        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17247
17248    }
17249
17250    /**
17251     * Returns the suggested minimum width that the view should use. This
17252     * returns the maximum of the view's minimum width)
17253     * and the background's minimum width
17254     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17255     * <p>
17256     * When being used in {@link #onMeasure(int, int)}, the caller should still
17257     * ensure the returned width is within the requirements of the parent.
17258     *
17259     * @return The suggested minimum width of the view.
17260     */
17261    protected int getSuggestedMinimumWidth() {
17262        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17263    }
17264
17265    /**
17266     * Returns the minimum height of the view.
17267     *
17268     * @return the minimum height the view will try to be.
17269     *
17270     * @see #setMinimumHeight(int)
17271     *
17272     * @attr ref android.R.styleable#View_minHeight
17273     */
17274    public int getMinimumHeight() {
17275        return mMinHeight;
17276    }
17277
17278    /**
17279     * Sets the minimum height of the view. It is not guaranteed the view will
17280     * be able to achieve this minimum height (for example, if its parent layout
17281     * constrains it with less available height).
17282     *
17283     * @param minHeight The minimum height the view will try to be.
17284     *
17285     * @see #getMinimumHeight()
17286     *
17287     * @attr ref android.R.styleable#View_minHeight
17288     */
17289    public void setMinimumHeight(int minHeight) {
17290        mMinHeight = minHeight;
17291        requestLayout();
17292    }
17293
17294    /**
17295     * Returns the minimum width of the view.
17296     *
17297     * @return the minimum width the view will try to be.
17298     *
17299     * @see #setMinimumWidth(int)
17300     *
17301     * @attr ref android.R.styleable#View_minWidth
17302     */
17303    public int getMinimumWidth() {
17304        return mMinWidth;
17305    }
17306
17307    /**
17308     * Sets the minimum width of the view. It is not guaranteed the view will
17309     * be able to achieve this minimum width (for example, if its parent layout
17310     * constrains it with less available width).
17311     *
17312     * @param minWidth The minimum width the view will try to be.
17313     *
17314     * @see #getMinimumWidth()
17315     *
17316     * @attr ref android.R.styleable#View_minWidth
17317     */
17318    public void setMinimumWidth(int minWidth) {
17319        mMinWidth = minWidth;
17320        requestLayout();
17321
17322    }
17323
17324    /**
17325     * Get the animation currently associated with this view.
17326     *
17327     * @return The animation that is currently playing or
17328     *         scheduled to play for this view.
17329     */
17330    public Animation getAnimation() {
17331        return mCurrentAnimation;
17332    }
17333
17334    /**
17335     * Start the specified animation now.
17336     *
17337     * @param animation the animation to start now
17338     */
17339    public void startAnimation(Animation animation) {
17340        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17341        setAnimation(animation);
17342        invalidateParentCaches();
17343        invalidate(true);
17344    }
17345
17346    /**
17347     * Cancels any animations for this view.
17348     */
17349    public void clearAnimation() {
17350        if (mCurrentAnimation != null) {
17351            mCurrentAnimation.detach();
17352        }
17353        mCurrentAnimation = null;
17354        invalidateParentIfNeeded();
17355    }
17356
17357    /**
17358     * Sets the next animation to play for this view.
17359     * If you want the animation to play immediately, use
17360     * {@link #startAnimation(android.view.animation.Animation)} instead.
17361     * This method provides allows fine-grained
17362     * control over the start time and invalidation, but you
17363     * must make sure that 1) the animation has a start time set, and
17364     * 2) the view's parent (which controls animations on its children)
17365     * will be invalidated when the animation is supposed to
17366     * start.
17367     *
17368     * @param animation The next animation, or null.
17369     */
17370    public void setAnimation(Animation animation) {
17371        mCurrentAnimation = animation;
17372
17373        if (animation != null) {
17374            // If the screen is off assume the animation start time is now instead of
17375            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17376            // would cause the animation to start when the screen turns back on
17377            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
17378                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17379                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17380            }
17381            animation.reset();
17382        }
17383    }
17384
17385    /**
17386     * Invoked by a parent ViewGroup to notify the start of the animation
17387     * currently associated with this view. If you override this method,
17388     * always call super.onAnimationStart();
17389     *
17390     * @see #setAnimation(android.view.animation.Animation)
17391     * @see #getAnimation()
17392     */
17393    protected void onAnimationStart() {
17394        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17395    }
17396
17397    /**
17398     * Invoked by a parent ViewGroup to notify the end of the animation
17399     * currently associated with this view. If you override this method,
17400     * always call super.onAnimationEnd();
17401     *
17402     * @see #setAnimation(android.view.animation.Animation)
17403     * @see #getAnimation()
17404     */
17405    protected void onAnimationEnd() {
17406        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17407    }
17408
17409    /**
17410     * Invoked if there is a Transform that involves alpha. Subclass that can
17411     * draw themselves with the specified alpha should return true, and then
17412     * respect that alpha when their onDraw() is called. If this returns false
17413     * then the view may be redirected to draw into an offscreen buffer to
17414     * fulfill the request, which will look fine, but may be slower than if the
17415     * subclass handles it internally. The default implementation returns false.
17416     *
17417     * @param alpha The alpha (0..255) to apply to the view's drawing
17418     * @return true if the view can draw with the specified alpha.
17419     */
17420    protected boolean onSetAlpha(int alpha) {
17421        return false;
17422    }
17423
17424    /**
17425     * This is used by the RootView to perform an optimization when
17426     * the view hierarchy contains one or several SurfaceView.
17427     * SurfaceView is always considered transparent, but its children are not,
17428     * therefore all View objects remove themselves from the global transparent
17429     * region (passed as a parameter to this function).
17430     *
17431     * @param region The transparent region for this ViewAncestor (window).
17432     *
17433     * @return Returns true if the effective visibility of the view at this
17434     * point is opaque, regardless of the transparent region; returns false
17435     * if it is possible for underlying windows to be seen behind the view.
17436     *
17437     * {@hide}
17438     */
17439    public boolean gatherTransparentRegion(Region region) {
17440        final AttachInfo attachInfo = mAttachInfo;
17441        if (region != null && attachInfo != null) {
17442            final int pflags = mPrivateFlags;
17443            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17444                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17445                // remove it from the transparent region.
17446                final int[] location = attachInfo.mTransparentLocation;
17447                getLocationInWindow(location);
17448                region.op(location[0], location[1], location[0] + mRight - mLeft,
17449                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17450            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17451                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17452                // exists, so we remove the background drawable's non-transparent
17453                // parts from this transparent region.
17454                applyDrawableToTransparentRegion(mBackground, region);
17455            }
17456        }
17457        return true;
17458    }
17459
17460    /**
17461     * Play a sound effect for this view.
17462     *
17463     * <p>The framework will play sound effects for some built in actions, such as
17464     * clicking, but you may wish to play these effects in your widget,
17465     * for instance, for internal navigation.
17466     *
17467     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17468     * {@link #isSoundEffectsEnabled()} is true.
17469     *
17470     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17471     */
17472    public void playSoundEffect(int soundConstant) {
17473        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17474            return;
17475        }
17476        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17477    }
17478
17479    /**
17480     * BZZZTT!!1!
17481     *
17482     * <p>Provide haptic feedback to the user for this view.
17483     *
17484     * <p>The framework will provide haptic feedback for some built in actions,
17485     * such as long presses, but you may wish to provide feedback for your
17486     * own widget.
17487     *
17488     * <p>The feedback will only be performed if
17489     * {@link #isHapticFeedbackEnabled()} is true.
17490     *
17491     * @param feedbackConstant One of the constants defined in
17492     * {@link HapticFeedbackConstants}
17493     */
17494    public boolean performHapticFeedback(int feedbackConstant) {
17495        return performHapticFeedback(feedbackConstant, 0);
17496    }
17497
17498    /**
17499     * BZZZTT!!1!
17500     *
17501     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17502     *
17503     * @param feedbackConstant One of the constants defined in
17504     * {@link HapticFeedbackConstants}
17505     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17506     */
17507    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17508        if (mAttachInfo == null) {
17509            return false;
17510        }
17511        //noinspection SimplifiableIfStatement
17512        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17513                && !isHapticFeedbackEnabled()) {
17514            return false;
17515        }
17516        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17517                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17518    }
17519
17520    /**
17521     * Request that the visibility of the status bar or other screen/window
17522     * decorations be changed.
17523     *
17524     * <p>This method is used to put the over device UI into temporary modes
17525     * where the user's attention is focused more on the application content,
17526     * by dimming or hiding surrounding system affordances.  This is typically
17527     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17528     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17529     * to be placed behind the action bar (and with these flags other system
17530     * affordances) so that smooth transitions between hiding and showing them
17531     * can be done.
17532     *
17533     * <p>Two representative examples of the use of system UI visibility is
17534     * implementing a content browsing application (like a magazine reader)
17535     * and a video playing application.
17536     *
17537     * <p>The first code shows a typical implementation of a View in a content
17538     * browsing application.  In this implementation, the application goes
17539     * into a content-oriented mode by hiding the status bar and action bar,
17540     * and putting the navigation elements into lights out mode.  The user can
17541     * then interact with content while in this mode.  Such an application should
17542     * provide an easy way for the user to toggle out of the mode (such as to
17543     * check information in the status bar or access notifications).  In the
17544     * implementation here, this is done simply by tapping on the content.
17545     *
17546     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17547     *      content}
17548     *
17549     * <p>This second code sample shows a typical implementation of a View
17550     * in a video playing application.  In this situation, while the video is
17551     * playing the application would like to go into a complete full-screen mode,
17552     * to use as much of the display as possible for the video.  When in this state
17553     * the user can not interact with the application; the system intercepts
17554     * touching on the screen to pop the UI out of full screen mode.  See
17555     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17556     *
17557     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17558     *      content}
17559     *
17560     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17561     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17562     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17563     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17564     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17565     */
17566    public void setSystemUiVisibility(int visibility) {
17567        if (visibility != mSystemUiVisibility) {
17568            mSystemUiVisibility = visibility;
17569            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17570                mParent.recomputeViewAttributes(this);
17571            }
17572        }
17573    }
17574
17575    /**
17576     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17577     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17578     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17579     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17580     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17581     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17582     */
17583    public int getSystemUiVisibility() {
17584        return mSystemUiVisibility;
17585    }
17586
17587    /**
17588     * Returns the current system UI visibility that is currently set for
17589     * the entire window.  This is the combination of the
17590     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17591     * views in the window.
17592     */
17593    public int getWindowSystemUiVisibility() {
17594        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17595    }
17596
17597    /**
17598     * Override to find out when the window's requested system UI visibility
17599     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17600     * This is different from the callbacks received through
17601     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17602     * in that this is only telling you about the local request of the window,
17603     * not the actual values applied by the system.
17604     */
17605    public void onWindowSystemUiVisibilityChanged(int visible) {
17606    }
17607
17608    /**
17609     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17610     * the view hierarchy.
17611     */
17612    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17613        onWindowSystemUiVisibilityChanged(visible);
17614    }
17615
17616    /**
17617     * Set a listener to receive callbacks when the visibility of the system bar changes.
17618     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17619     */
17620    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17621        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17622        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17623            mParent.recomputeViewAttributes(this);
17624        }
17625    }
17626
17627    /**
17628     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17629     * the view hierarchy.
17630     */
17631    public void dispatchSystemUiVisibilityChanged(int visibility) {
17632        ListenerInfo li = mListenerInfo;
17633        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17634            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17635                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17636        }
17637    }
17638
17639    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17640        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17641        if (val != mSystemUiVisibility) {
17642            setSystemUiVisibility(val);
17643            return true;
17644        }
17645        return false;
17646    }
17647
17648    /** @hide */
17649    public void setDisabledSystemUiVisibility(int flags) {
17650        if (mAttachInfo != null) {
17651            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17652                mAttachInfo.mDisabledSystemUiVisibility = flags;
17653                if (mParent != null) {
17654                    mParent.recomputeViewAttributes(this);
17655                }
17656            }
17657        }
17658    }
17659
17660    /**
17661     * Creates an image that the system displays during the drag and drop
17662     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17663     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17664     * appearance as the given View. The default also positions the center of the drag shadow
17665     * directly under the touch point. If no View is provided (the constructor with no parameters
17666     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17667     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17668     * default is an invisible drag shadow.
17669     * <p>
17670     * You are not required to use the View you provide to the constructor as the basis of the
17671     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17672     * anything you want as the drag shadow.
17673     * </p>
17674     * <p>
17675     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17676     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17677     *  size and position of the drag shadow. It uses this data to construct a
17678     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17679     *  so that your application can draw the shadow image in the Canvas.
17680     * </p>
17681     *
17682     * <div class="special reference">
17683     * <h3>Developer Guides</h3>
17684     * <p>For a guide to implementing drag and drop features, read the
17685     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17686     * </div>
17687     */
17688    public static class DragShadowBuilder {
17689        private final WeakReference<View> mView;
17690
17691        /**
17692         * Constructs a shadow image builder based on a View. By default, the resulting drag
17693         * shadow will have the same appearance and dimensions as the View, with the touch point
17694         * over the center of the View.
17695         * @param view A View. Any View in scope can be used.
17696         */
17697        public DragShadowBuilder(View view) {
17698            mView = new WeakReference<View>(view);
17699        }
17700
17701        /**
17702         * Construct a shadow builder object with no associated View.  This
17703         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17704         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17705         * to supply the drag shadow's dimensions and appearance without
17706         * reference to any View object. If they are not overridden, then the result is an
17707         * invisible drag shadow.
17708         */
17709        public DragShadowBuilder() {
17710            mView = new WeakReference<View>(null);
17711        }
17712
17713        /**
17714         * Returns the View object that had been passed to the
17715         * {@link #View.DragShadowBuilder(View)}
17716         * constructor.  If that View parameter was {@code null} or if the
17717         * {@link #View.DragShadowBuilder()}
17718         * constructor was used to instantiate the builder object, this method will return
17719         * null.
17720         *
17721         * @return The View object associate with this builder object.
17722         */
17723        @SuppressWarnings({"JavadocReference"})
17724        final public View getView() {
17725            return mView.get();
17726        }
17727
17728        /**
17729         * Provides the metrics for the shadow image. These include the dimensions of
17730         * the shadow image, and the point within that shadow that should
17731         * be centered under the touch location while dragging.
17732         * <p>
17733         * The default implementation sets the dimensions of the shadow to be the
17734         * same as the dimensions of the View itself and centers the shadow under
17735         * the touch point.
17736         * </p>
17737         *
17738         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17739         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17740         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17741         * image.
17742         *
17743         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17744         * shadow image that should be underneath the touch point during the drag and drop
17745         * operation. Your application must set {@link android.graphics.Point#x} to the
17746         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17747         */
17748        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17749            final View view = mView.get();
17750            if (view != null) {
17751                shadowSize.set(view.getWidth(), view.getHeight());
17752                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17753            } else {
17754                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17755            }
17756        }
17757
17758        /**
17759         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17760         * based on the dimensions it received from the
17761         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17762         *
17763         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17764         */
17765        public void onDrawShadow(Canvas canvas) {
17766            final View view = mView.get();
17767            if (view != null) {
17768                view.draw(canvas);
17769            } else {
17770                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17771            }
17772        }
17773    }
17774
17775    /**
17776     * Starts a drag and drop operation. When your application calls this method, it passes a
17777     * {@link android.view.View.DragShadowBuilder} object to the system. The
17778     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17779     * to get metrics for the drag shadow, and then calls the object's
17780     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17781     * <p>
17782     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17783     *  drag events to all the View objects in your application that are currently visible. It does
17784     *  this either by calling the View object's drag listener (an implementation of
17785     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17786     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17787     *  Both are passed a {@link android.view.DragEvent} object that has a
17788     *  {@link android.view.DragEvent#getAction()} value of
17789     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17790     * </p>
17791     * <p>
17792     * Your application can invoke startDrag() on any attached View object. The View object does not
17793     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17794     * be related to the View the user selected for dragging.
17795     * </p>
17796     * @param data A {@link android.content.ClipData} object pointing to the data to be
17797     * transferred by the drag and drop operation.
17798     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17799     * drag shadow.
17800     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17801     * drop operation. This Object is put into every DragEvent object sent by the system during the
17802     * current drag.
17803     * <p>
17804     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17805     * to the target Views. For example, it can contain flags that differentiate between a
17806     * a copy operation and a move operation.
17807     * </p>
17808     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17809     * so the parameter should be set to 0.
17810     * @return {@code true} if the method completes successfully, or
17811     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17812     * do a drag, and so no drag operation is in progress.
17813     */
17814    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17815            Object myLocalState, int flags) {
17816        if (ViewDebug.DEBUG_DRAG) {
17817            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17818        }
17819        boolean okay = false;
17820
17821        Point shadowSize = new Point();
17822        Point shadowTouchPoint = new Point();
17823        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17824
17825        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17826                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17827            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17828        }
17829
17830        if (ViewDebug.DEBUG_DRAG) {
17831            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17832                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17833        }
17834        Surface surface = new Surface();
17835        try {
17836            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17837                    flags, shadowSize.x, shadowSize.y, surface);
17838            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17839                    + " surface=" + surface);
17840            if (token != null) {
17841                Canvas canvas = surface.lockCanvas(null);
17842                try {
17843                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17844                    shadowBuilder.onDrawShadow(canvas);
17845                } finally {
17846                    surface.unlockCanvasAndPost(canvas);
17847                }
17848
17849                final ViewRootImpl root = getViewRootImpl();
17850
17851                // Cache the local state object for delivery with DragEvents
17852                root.setLocalDragState(myLocalState);
17853
17854                // repurpose 'shadowSize' for the last touch point
17855                root.getLastTouchPoint(shadowSize);
17856
17857                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17858                        shadowSize.x, shadowSize.y,
17859                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17860                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17861
17862                // Off and running!  Release our local surface instance; the drag
17863                // shadow surface is now managed by the system process.
17864                surface.release();
17865            }
17866        } catch (Exception e) {
17867            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17868            surface.destroy();
17869        }
17870
17871        return okay;
17872    }
17873
17874    /**
17875     * Handles drag events sent by the system following a call to
17876     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17877     *<p>
17878     * When the system calls this method, it passes a
17879     * {@link android.view.DragEvent} object. A call to
17880     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17881     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17882     * operation.
17883     * @param event The {@link android.view.DragEvent} sent by the system.
17884     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17885     * in DragEvent, indicating the type of drag event represented by this object.
17886     * @return {@code true} if the method was successful, otherwise {@code false}.
17887     * <p>
17888     *  The method should return {@code true} in response to an action type of
17889     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17890     *  operation.
17891     * </p>
17892     * <p>
17893     *  The method should also return {@code true} in response to an action type of
17894     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17895     *  {@code false} if it didn't.
17896     * </p>
17897     */
17898    public boolean onDragEvent(DragEvent event) {
17899        return false;
17900    }
17901
17902    /**
17903     * Detects if this View is enabled and has a drag event listener.
17904     * If both are true, then it calls the drag event listener with the
17905     * {@link android.view.DragEvent} it received. If the drag event listener returns
17906     * {@code true}, then dispatchDragEvent() returns {@code true}.
17907     * <p>
17908     * For all other cases, the method calls the
17909     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17910     * method and returns its result.
17911     * </p>
17912     * <p>
17913     * This ensures that a drag event is always consumed, even if the View does not have a drag
17914     * event listener. However, if the View has a listener and the listener returns true, then
17915     * onDragEvent() is not called.
17916     * </p>
17917     */
17918    public boolean dispatchDragEvent(DragEvent event) {
17919        ListenerInfo li = mListenerInfo;
17920        //noinspection SimplifiableIfStatement
17921        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17922                && li.mOnDragListener.onDrag(this, event)) {
17923            return true;
17924        }
17925        return onDragEvent(event);
17926    }
17927
17928    boolean canAcceptDrag() {
17929        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17930    }
17931
17932    /**
17933     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17934     * it is ever exposed at all.
17935     * @hide
17936     */
17937    public void onCloseSystemDialogs(String reason) {
17938    }
17939
17940    /**
17941     * Given a Drawable whose bounds have been set to draw into this view,
17942     * update a Region being computed for
17943     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17944     * that any non-transparent parts of the Drawable are removed from the
17945     * given transparent region.
17946     *
17947     * @param dr The Drawable whose transparency is to be applied to the region.
17948     * @param region A Region holding the current transparency information,
17949     * where any parts of the region that are set are considered to be
17950     * transparent.  On return, this region will be modified to have the
17951     * transparency information reduced by the corresponding parts of the
17952     * Drawable that are not transparent.
17953     * {@hide}
17954     */
17955    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17956        if (DBG) {
17957            Log.i("View", "Getting transparent region for: " + this);
17958        }
17959        final Region r = dr.getTransparentRegion();
17960        final Rect db = dr.getBounds();
17961        final AttachInfo attachInfo = mAttachInfo;
17962        if (r != null && attachInfo != null) {
17963            final int w = getRight()-getLeft();
17964            final int h = getBottom()-getTop();
17965            if (db.left > 0) {
17966                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17967                r.op(0, 0, db.left, h, Region.Op.UNION);
17968            }
17969            if (db.right < w) {
17970                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17971                r.op(db.right, 0, w, h, Region.Op.UNION);
17972            }
17973            if (db.top > 0) {
17974                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17975                r.op(0, 0, w, db.top, Region.Op.UNION);
17976            }
17977            if (db.bottom < h) {
17978                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17979                r.op(0, db.bottom, w, h, Region.Op.UNION);
17980            }
17981            final int[] location = attachInfo.mTransparentLocation;
17982            getLocationInWindow(location);
17983            r.translate(location[0], location[1]);
17984            region.op(r, Region.Op.INTERSECT);
17985        } else {
17986            region.op(db, Region.Op.DIFFERENCE);
17987        }
17988    }
17989
17990    private void checkForLongClick(int delayOffset) {
17991        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17992            mHasPerformedLongPress = false;
17993
17994            if (mPendingCheckForLongPress == null) {
17995                mPendingCheckForLongPress = new CheckForLongPress();
17996            }
17997            mPendingCheckForLongPress.rememberWindowAttachCount();
17998            postDelayed(mPendingCheckForLongPress,
17999                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18000        }
18001    }
18002
18003    /**
18004     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18005     * LayoutInflater} class, which provides a full range of options for view inflation.
18006     *
18007     * @param context The Context object for your activity or application.
18008     * @param resource The resource ID to inflate
18009     * @param root A view group that will be the parent.  Used to properly inflate the
18010     * layout_* parameters.
18011     * @see LayoutInflater
18012     */
18013    public static View inflate(Context context, int resource, ViewGroup root) {
18014        LayoutInflater factory = LayoutInflater.from(context);
18015        return factory.inflate(resource, root);
18016    }
18017
18018    /**
18019     * Scroll the view with standard behavior for scrolling beyond the normal
18020     * content boundaries. Views that call this method should override
18021     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18022     * results of an over-scroll operation.
18023     *
18024     * Views can use this method to handle any touch or fling-based scrolling.
18025     *
18026     * @param deltaX Change in X in pixels
18027     * @param deltaY Change in Y in pixels
18028     * @param scrollX Current X scroll value in pixels before applying deltaX
18029     * @param scrollY Current Y scroll value in pixels before applying deltaY
18030     * @param scrollRangeX Maximum content scroll range along the X axis
18031     * @param scrollRangeY Maximum content scroll range along the Y axis
18032     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18033     *          along the X axis.
18034     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18035     *          along the Y axis.
18036     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18037     * @return true if scrolling was clamped to an over-scroll boundary along either
18038     *          axis, false otherwise.
18039     */
18040    @SuppressWarnings({"UnusedParameters"})
18041    protected boolean overScrollBy(int deltaX, int deltaY,
18042            int scrollX, int scrollY,
18043            int scrollRangeX, int scrollRangeY,
18044            int maxOverScrollX, int maxOverScrollY,
18045            boolean isTouchEvent) {
18046        final int overScrollMode = mOverScrollMode;
18047        final boolean canScrollHorizontal =
18048                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18049        final boolean canScrollVertical =
18050                computeVerticalScrollRange() > computeVerticalScrollExtent();
18051        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18052                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18053        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18054                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18055
18056        int newScrollX = scrollX + deltaX;
18057        if (!overScrollHorizontal) {
18058            maxOverScrollX = 0;
18059        }
18060
18061        int newScrollY = scrollY + deltaY;
18062        if (!overScrollVertical) {
18063            maxOverScrollY = 0;
18064        }
18065
18066        // Clamp values if at the limits and record
18067        final int left = -maxOverScrollX;
18068        final int right = maxOverScrollX + scrollRangeX;
18069        final int top = -maxOverScrollY;
18070        final int bottom = maxOverScrollY + scrollRangeY;
18071
18072        boolean clampedX = false;
18073        if (newScrollX > right) {
18074            newScrollX = right;
18075            clampedX = true;
18076        } else if (newScrollX < left) {
18077            newScrollX = left;
18078            clampedX = true;
18079        }
18080
18081        boolean clampedY = false;
18082        if (newScrollY > bottom) {
18083            newScrollY = bottom;
18084            clampedY = true;
18085        } else if (newScrollY < top) {
18086            newScrollY = top;
18087            clampedY = true;
18088        }
18089
18090        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18091
18092        return clampedX || clampedY;
18093    }
18094
18095    /**
18096     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18097     * respond to the results of an over-scroll operation.
18098     *
18099     * @param scrollX New X scroll value in pixels
18100     * @param scrollY New Y scroll value in pixels
18101     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18102     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18103     */
18104    protected void onOverScrolled(int scrollX, int scrollY,
18105            boolean clampedX, boolean clampedY) {
18106        // Intentionally empty.
18107    }
18108
18109    /**
18110     * Returns the over-scroll mode for this view. The result will be
18111     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18112     * (allow over-scrolling only if the view content is larger than the container),
18113     * or {@link #OVER_SCROLL_NEVER}.
18114     *
18115     * @return This view's over-scroll mode.
18116     */
18117    public int getOverScrollMode() {
18118        return mOverScrollMode;
18119    }
18120
18121    /**
18122     * Set the over-scroll mode for this view. Valid over-scroll modes are
18123     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18124     * (allow over-scrolling only if the view content is larger than the container),
18125     * or {@link #OVER_SCROLL_NEVER}.
18126     *
18127     * Setting the over-scroll mode of a view will have an effect only if the
18128     * view is capable of scrolling.
18129     *
18130     * @param overScrollMode The new over-scroll mode for this view.
18131     */
18132    public void setOverScrollMode(int overScrollMode) {
18133        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18134                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18135                overScrollMode != OVER_SCROLL_NEVER) {
18136            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18137        }
18138        mOverScrollMode = overScrollMode;
18139    }
18140
18141    /**
18142     * Gets a scale factor that determines the distance the view should scroll
18143     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18144     * @return The vertical scroll scale factor.
18145     * @hide
18146     */
18147    protected float getVerticalScrollFactor() {
18148        if (mVerticalScrollFactor == 0) {
18149            TypedValue outValue = new TypedValue();
18150            if (!mContext.getTheme().resolveAttribute(
18151                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18152                throw new IllegalStateException(
18153                        "Expected theme to define listPreferredItemHeight.");
18154            }
18155            mVerticalScrollFactor = outValue.getDimension(
18156                    mContext.getResources().getDisplayMetrics());
18157        }
18158        return mVerticalScrollFactor;
18159    }
18160
18161    /**
18162     * Gets a scale factor that determines the distance the view should scroll
18163     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18164     * @return The horizontal scroll scale factor.
18165     * @hide
18166     */
18167    protected float getHorizontalScrollFactor() {
18168        // TODO: Should use something else.
18169        return getVerticalScrollFactor();
18170    }
18171
18172    /**
18173     * Return the value specifying the text direction or policy that was set with
18174     * {@link #setTextDirection(int)}.
18175     *
18176     * @return the defined text direction. It can be one of:
18177     *
18178     * {@link #TEXT_DIRECTION_INHERIT},
18179     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18180     * {@link #TEXT_DIRECTION_ANY_RTL},
18181     * {@link #TEXT_DIRECTION_LTR},
18182     * {@link #TEXT_DIRECTION_RTL},
18183     * {@link #TEXT_DIRECTION_LOCALE}
18184     *
18185     * @attr ref android.R.styleable#View_textDirection
18186     *
18187     * @hide
18188     */
18189    @ViewDebug.ExportedProperty(category = "text", mapping = {
18190            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18191            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18192            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18193            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18194            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18195            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18196    })
18197    public int getRawTextDirection() {
18198        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18199    }
18200
18201    /**
18202     * Set the text direction.
18203     *
18204     * @param textDirection the direction to set. Should be one of:
18205     *
18206     * {@link #TEXT_DIRECTION_INHERIT},
18207     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18208     * {@link #TEXT_DIRECTION_ANY_RTL},
18209     * {@link #TEXT_DIRECTION_LTR},
18210     * {@link #TEXT_DIRECTION_RTL},
18211     * {@link #TEXT_DIRECTION_LOCALE}
18212     *
18213     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18214     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18215     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18216     *
18217     * @attr ref android.R.styleable#View_textDirection
18218     */
18219    public void setTextDirection(int textDirection) {
18220        if (getRawTextDirection() != textDirection) {
18221            // Reset the current text direction and the resolved one
18222            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18223            resetResolvedTextDirection();
18224            // Set the new text direction
18225            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18226            // Do resolution
18227            resolveTextDirection();
18228            // Notify change
18229            onRtlPropertiesChanged(getLayoutDirection());
18230            // Refresh
18231            requestLayout();
18232            invalidate(true);
18233        }
18234    }
18235
18236    /**
18237     * Return the resolved text direction.
18238     *
18239     * @return the resolved text direction. Returns one of:
18240     *
18241     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18242     * {@link #TEXT_DIRECTION_ANY_RTL},
18243     * {@link #TEXT_DIRECTION_LTR},
18244     * {@link #TEXT_DIRECTION_RTL},
18245     * {@link #TEXT_DIRECTION_LOCALE}
18246     *
18247     * @attr ref android.R.styleable#View_textDirection
18248     */
18249    @ViewDebug.ExportedProperty(category = "text", mapping = {
18250            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18251            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18252            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18253            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18254            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18255            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18256    })
18257    public int getTextDirection() {
18258        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18259    }
18260
18261    /**
18262     * Resolve the text direction.
18263     *
18264     * @return true if resolution has been done, false otherwise.
18265     *
18266     * @hide
18267     */
18268    public boolean resolveTextDirection() {
18269        // Reset any previous text direction resolution
18270        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18271
18272        if (hasRtlSupport()) {
18273            // Set resolved text direction flag depending on text direction flag
18274            final int textDirection = getRawTextDirection();
18275            switch(textDirection) {
18276                case TEXT_DIRECTION_INHERIT:
18277                    if (!canResolveTextDirection()) {
18278                        // We cannot do the resolution if there is no parent, so use the default one
18279                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18280                        // Resolution will need to happen again later
18281                        return false;
18282                    }
18283
18284                    // Parent has not yet resolved, so we still return the default
18285                    try {
18286                        if (!mParent.isTextDirectionResolved()) {
18287                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18288                            // Resolution will need to happen again later
18289                            return false;
18290                        }
18291                    } catch (AbstractMethodError e) {
18292                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18293                                " does not fully implement ViewParent", e);
18294                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18295                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18296                        return true;
18297                    }
18298
18299                    // Set current resolved direction to the same value as the parent's one
18300                    int parentResolvedDirection;
18301                    try {
18302                        parentResolvedDirection = mParent.getTextDirection();
18303                    } catch (AbstractMethodError e) {
18304                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18305                                " does not fully implement ViewParent", e);
18306                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18307                    }
18308                    switch (parentResolvedDirection) {
18309                        case TEXT_DIRECTION_FIRST_STRONG:
18310                        case TEXT_DIRECTION_ANY_RTL:
18311                        case TEXT_DIRECTION_LTR:
18312                        case TEXT_DIRECTION_RTL:
18313                        case TEXT_DIRECTION_LOCALE:
18314                            mPrivateFlags2 |=
18315                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18316                            break;
18317                        default:
18318                            // Default resolved direction is "first strong" heuristic
18319                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18320                    }
18321                    break;
18322                case TEXT_DIRECTION_FIRST_STRONG:
18323                case TEXT_DIRECTION_ANY_RTL:
18324                case TEXT_DIRECTION_LTR:
18325                case TEXT_DIRECTION_RTL:
18326                case TEXT_DIRECTION_LOCALE:
18327                    // Resolved direction is the same as text direction
18328                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18329                    break;
18330                default:
18331                    // Default resolved direction is "first strong" heuristic
18332                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18333            }
18334        } else {
18335            // Default resolved direction is "first strong" heuristic
18336            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18337        }
18338
18339        // Set to resolved
18340        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18341        return true;
18342    }
18343
18344    /**
18345     * Check if text direction resolution can be done.
18346     *
18347     * @return true if text direction resolution can be done otherwise return false.
18348     */
18349    public boolean canResolveTextDirection() {
18350        switch (getRawTextDirection()) {
18351            case TEXT_DIRECTION_INHERIT:
18352                if (mParent != null) {
18353                    try {
18354                        return mParent.canResolveTextDirection();
18355                    } catch (AbstractMethodError e) {
18356                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18357                                " does not fully implement ViewParent", e);
18358                    }
18359                }
18360                return false;
18361
18362            default:
18363                return true;
18364        }
18365    }
18366
18367    /**
18368     * Reset resolved text direction. Text direction will be resolved during a call to
18369     * {@link #onMeasure(int, int)}.
18370     *
18371     * @hide
18372     */
18373    public void resetResolvedTextDirection() {
18374        // Reset any previous text direction resolution
18375        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18376        // Set to default value
18377        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18378    }
18379
18380    /**
18381     * @return true if text direction is inherited.
18382     *
18383     * @hide
18384     */
18385    public boolean isTextDirectionInherited() {
18386        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18387    }
18388
18389    /**
18390     * @return true if text direction is resolved.
18391     */
18392    public boolean isTextDirectionResolved() {
18393        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18394    }
18395
18396    /**
18397     * Return the value specifying the text alignment or policy that was set with
18398     * {@link #setTextAlignment(int)}.
18399     *
18400     * @return the defined text alignment. It can be one of:
18401     *
18402     * {@link #TEXT_ALIGNMENT_INHERIT},
18403     * {@link #TEXT_ALIGNMENT_GRAVITY},
18404     * {@link #TEXT_ALIGNMENT_CENTER},
18405     * {@link #TEXT_ALIGNMENT_TEXT_START},
18406     * {@link #TEXT_ALIGNMENT_TEXT_END},
18407     * {@link #TEXT_ALIGNMENT_VIEW_START},
18408     * {@link #TEXT_ALIGNMENT_VIEW_END}
18409     *
18410     * @attr ref android.R.styleable#View_textAlignment
18411     *
18412     * @hide
18413     */
18414    @ViewDebug.ExportedProperty(category = "text", mapping = {
18415            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18416            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18417            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18418            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18419            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18420            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18421            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18422    })
18423    @TextAlignment
18424    public int getRawTextAlignment() {
18425        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18426    }
18427
18428    /**
18429     * Set the text alignment.
18430     *
18431     * @param textAlignment The text alignment to set. Should be one of
18432     *
18433     * {@link #TEXT_ALIGNMENT_INHERIT},
18434     * {@link #TEXT_ALIGNMENT_GRAVITY},
18435     * {@link #TEXT_ALIGNMENT_CENTER},
18436     * {@link #TEXT_ALIGNMENT_TEXT_START},
18437     * {@link #TEXT_ALIGNMENT_TEXT_END},
18438     * {@link #TEXT_ALIGNMENT_VIEW_START},
18439     * {@link #TEXT_ALIGNMENT_VIEW_END}
18440     *
18441     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18442     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18443     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18444     *
18445     * @attr ref android.R.styleable#View_textAlignment
18446     */
18447    public void setTextAlignment(@TextAlignment int textAlignment) {
18448        if (textAlignment != getRawTextAlignment()) {
18449            // Reset the current and resolved text alignment
18450            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18451            resetResolvedTextAlignment();
18452            // Set the new text alignment
18453            mPrivateFlags2 |=
18454                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18455            // Do resolution
18456            resolveTextAlignment();
18457            // Notify change
18458            onRtlPropertiesChanged(getLayoutDirection());
18459            // Refresh
18460            requestLayout();
18461            invalidate(true);
18462        }
18463    }
18464
18465    /**
18466     * Return the resolved text alignment.
18467     *
18468     * @return the resolved text alignment. Returns one of:
18469     *
18470     * {@link #TEXT_ALIGNMENT_GRAVITY},
18471     * {@link #TEXT_ALIGNMENT_CENTER},
18472     * {@link #TEXT_ALIGNMENT_TEXT_START},
18473     * {@link #TEXT_ALIGNMENT_TEXT_END},
18474     * {@link #TEXT_ALIGNMENT_VIEW_START},
18475     * {@link #TEXT_ALIGNMENT_VIEW_END}
18476     *
18477     * @attr ref android.R.styleable#View_textAlignment
18478     */
18479    @ViewDebug.ExportedProperty(category = "text", mapping = {
18480            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18481            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18482            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18483            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18484            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18485            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18486            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18487    })
18488    @TextAlignment
18489    public int getTextAlignment() {
18490        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18491                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18492    }
18493
18494    /**
18495     * Resolve the text alignment.
18496     *
18497     * @return true if resolution has been done, false otherwise.
18498     *
18499     * @hide
18500     */
18501    public boolean resolveTextAlignment() {
18502        // Reset any previous text alignment resolution
18503        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18504
18505        if (hasRtlSupport()) {
18506            // Set resolved text alignment flag depending on text alignment flag
18507            final int textAlignment = getRawTextAlignment();
18508            switch (textAlignment) {
18509                case TEXT_ALIGNMENT_INHERIT:
18510                    // Check if we can resolve the text alignment
18511                    if (!canResolveTextAlignment()) {
18512                        // We cannot do the resolution if there is no parent so use the default
18513                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18514                        // Resolution will need to happen again later
18515                        return false;
18516                    }
18517
18518                    // Parent has not yet resolved, so we still return the default
18519                    try {
18520                        if (!mParent.isTextAlignmentResolved()) {
18521                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18522                            // Resolution will need to happen again later
18523                            return false;
18524                        }
18525                    } catch (AbstractMethodError e) {
18526                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18527                                " does not fully implement ViewParent", e);
18528                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18529                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18530                        return true;
18531                    }
18532
18533                    int parentResolvedTextAlignment;
18534                    try {
18535                        parentResolvedTextAlignment = mParent.getTextAlignment();
18536                    } catch (AbstractMethodError e) {
18537                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18538                                " does not fully implement ViewParent", e);
18539                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18540                    }
18541                    switch (parentResolvedTextAlignment) {
18542                        case TEXT_ALIGNMENT_GRAVITY:
18543                        case TEXT_ALIGNMENT_TEXT_START:
18544                        case TEXT_ALIGNMENT_TEXT_END:
18545                        case TEXT_ALIGNMENT_CENTER:
18546                        case TEXT_ALIGNMENT_VIEW_START:
18547                        case TEXT_ALIGNMENT_VIEW_END:
18548                            // Resolved text alignment is the same as the parent resolved
18549                            // text alignment
18550                            mPrivateFlags2 |=
18551                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18552                            break;
18553                        default:
18554                            // Use default resolved text alignment
18555                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18556                    }
18557                    break;
18558                case TEXT_ALIGNMENT_GRAVITY:
18559                case TEXT_ALIGNMENT_TEXT_START:
18560                case TEXT_ALIGNMENT_TEXT_END:
18561                case TEXT_ALIGNMENT_CENTER:
18562                case TEXT_ALIGNMENT_VIEW_START:
18563                case TEXT_ALIGNMENT_VIEW_END:
18564                    // Resolved text alignment is the same as text alignment
18565                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18566                    break;
18567                default:
18568                    // Use default resolved text alignment
18569                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18570            }
18571        } else {
18572            // Use default resolved text alignment
18573            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18574        }
18575
18576        // Set the resolved
18577        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18578        return true;
18579    }
18580
18581    /**
18582     * Check if text alignment resolution can be done.
18583     *
18584     * @return true if text alignment resolution can be done otherwise return false.
18585     */
18586    public boolean canResolveTextAlignment() {
18587        switch (getRawTextAlignment()) {
18588            case TEXT_DIRECTION_INHERIT:
18589                if (mParent != null) {
18590                    try {
18591                        return mParent.canResolveTextAlignment();
18592                    } catch (AbstractMethodError e) {
18593                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18594                                " does not fully implement ViewParent", e);
18595                    }
18596                }
18597                return false;
18598
18599            default:
18600                return true;
18601        }
18602    }
18603
18604    /**
18605     * Reset resolved text alignment. Text alignment will be resolved during a call to
18606     * {@link #onMeasure(int, int)}.
18607     *
18608     * @hide
18609     */
18610    public void resetResolvedTextAlignment() {
18611        // Reset any previous text alignment resolution
18612        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18613        // Set to default
18614        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18615    }
18616
18617    /**
18618     * @return true if text alignment is inherited.
18619     *
18620     * @hide
18621     */
18622    public boolean isTextAlignmentInherited() {
18623        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18624    }
18625
18626    /**
18627     * @return true if text alignment is resolved.
18628     */
18629    public boolean isTextAlignmentResolved() {
18630        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18631    }
18632
18633    /**
18634     * Generate a value suitable for use in {@link #setId(int)}.
18635     * This value will not collide with ID values generated at build time by aapt for R.id.
18636     *
18637     * @return a generated ID value
18638     */
18639    public static int generateViewId() {
18640        for (;;) {
18641            final int result = sNextGeneratedId.get();
18642            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18643            int newValue = result + 1;
18644            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18645            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18646                return result;
18647            }
18648        }
18649    }
18650
18651    //
18652    // Properties
18653    //
18654    /**
18655     * A Property wrapper around the <code>alpha</code> functionality handled by the
18656     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18657     */
18658    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18659        @Override
18660        public void setValue(View object, float value) {
18661            object.setAlpha(value);
18662        }
18663
18664        @Override
18665        public Float get(View object) {
18666            return object.getAlpha();
18667        }
18668    };
18669
18670    /**
18671     * A Property wrapper around the <code>translationX</code> functionality handled by the
18672     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18673     */
18674    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18675        @Override
18676        public void setValue(View object, float value) {
18677            object.setTranslationX(value);
18678        }
18679
18680                @Override
18681        public Float get(View object) {
18682            return object.getTranslationX();
18683        }
18684    };
18685
18686    /**
18687     * A Property wrapper around the <code>translationY</code> functionality handled by the
18688     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18689     */
18690    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18691        @Override
18692        public void setValue(View object, float value) {
18693            object.setTranslationY(value);
18694        }
18695
18696        @Override
18697        public Float get(View object) {
18698            return object.getTranslationY();
18699        }
18700    };
18701
18702    /**
18703     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18704     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18705     */
18706    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18707        @Override
18708        public void setValue(View object, float value) {
18709            object.setTranslationZ(value);
18710        }
18711
18712        @Override
18713        public Float get(View object) {
18714            return object.getTranslationZ();
18715        }
18716    };
18717
18718    /**
18719     * A Property wrapper around the <code>x</code> functionality handled by the
18720     * {@link View#setX(float)} and {@link View#getX()} methods.
18721     */
18722    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18723        @Override
18724        public void setValue(View object, float value) {
18725            object.setX(value);
18726        }
18727
18728        @Override
18729        public Float get(View object) {
18730            return object.getX();
18731        }
18732    };
18733
18734    /**
18735     * A Property wrapper around the <code>y</code> functionality handled by the
18736     * {@link View#setY(float)} and {@link View#getY()} methods.
18737     */
18738    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18739        @Override
18740        public void setValue(View object, float value) {
18741            object.setY(value);
18742        }
18743
18744        @Override
18745        public Float get(View object) {
18746            return object.getY();
18747        }
18748    };
18749
18750    /**
18751     * A Property wrapper around the <code>rotation</code> functionality handled by the
18752     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18753     */
18754    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18755        @Override
18756        public void setValue(View object, float value) {
18757            object.setRotation(value);
18758        }
18759
18760        @Override
18761        public Float get(View object) {
18762            return object.getRotation();
18763        }
18764    };
18765
18766    /**
18767     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18768     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18769     */
18770    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18771        @Override
18772        public void setValue(View object, float value) {
18773            object.setRotationX(value);
18774        }
18775
18776        @Override
18777        public Float get(View object) {
18778            return object.getRotationX();
18779        }
18780    };
18781
18782    /**
18783     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18784     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18785     */
18786    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18787        @Override
18788        public void setValue(View object, float value) {
18789            object.setRotationY(value);
18790        }
18791
18792        @Override
18793        public Float get(View object) {
18794            return object.getRotationY();
18795        }
18796    };
18797
18798    /**
18799     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18800     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18801     */
18802    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18803        @Override
18804        public void setValue(View object, float value) {
18805            object.setScaleX(value);
18806        }
18807
18808        @Override
18809        public Float get(View object) {
18810            return object.getScaleX();
18811        }
18812    };
18813
18814    /**
18815     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18816     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18817     */
18818    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18819        @Override
18820        public void setValue(View object, float value) {
18821            object.setScaleY(value);
18822        }
18823
18824        @Override
18825        public Float get(View object) {
18826            return object.getScaleY();
18827        }
18828    };
18829
18830    /**
18831     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18832     * Each MeasureSpec represents a requirement for either the width or the height.
18833     * A MeasureSpec is comprised of a size and a mode. There are three possible
18834     * modes:
18835     * <dl>
18836     * <dt>UNSPECIFIED</dt>
18837     * <dd>
18838     * The parent has not imposed any constraint on the child. It can be whatever size
18839     * it wants.
18840     * </dd>
18841     *
18842     * <dt>EXACTLY</dt>
18843     * <dd>
18844     * The parent has determined an exact size for the child. The child is going to be
18845     * given those bounds regardless of how big it wants to be.
18846     * </dd>
18847     *
18848     * <dt>AT_MOST</dt>
18849     * <dd>
18850     * The child can be as large as it wants up to the specified size.
18851     * </dd>
18852     * </dl>
18853     *
18854     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18855     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18856     */
18857    public static class MeasureSpec {
18858        private static final int MODE_SHIFT = 30;
18859        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18860
18861        /**
18862         * Measure specification mode: The parent has not imposed any constraint
18863         * on the child. It can be whatever size it wants.
18864         */
18865        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18866
18867        /**
18868         * Measure specification mode: The parent has determined an exact size
18869         * for the child. The child is going to be given those bounds regardless
18870         * of how big it wants to be.
18871         */
18872        public static final int EXACTLY     = 1 << MODE_SHIFT;
18873
18874        /**
18875         * Measure specification mode: The child can be as large as it wants up
18876         * to the specified size.
18877         */
18878        public static final int AT_MOST     = 2 << MODE_SHIFT;
18879
18880        /**
18881         * Creates a measure specification based on the supplied size and mode.
18882         *
18883         * The mode must always be one of the following:
18884         * <ul>
18885         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18886         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18887         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18888         * </ul>
18889         *
18890         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
18891         * implementation was such that the order of arguments did not matter
18892         * and overflow in either value could impact the resulting MeasureSpec.
18893         * {@link android.widget.RelativeLayout} was affected by this bug.
18894         * Apps targeting API levels greater than 17 will get the fixed, more strict
18895         * behavior.</p>
18896         *
18897         * @param size the size of the measure specification
18898         * @param mode the mode of the measure specification
18899         * @return the measure specification based on size and mode
18900         */
18901        public static int makeMeasureSpec(int size, int mode) {
18902            if (sUseBrokenMakeMeasureSpec) {
18903                return size + mode;
18904            } else {
18905                return (size & ~MODE_MASK) | (mode & MODE_MASK);
18906            }
18907        }
18908
18909        /**
18910         * Extracts the mode from the supplied measure specification.
18911         *
18912         * @param measureSpec the measure specification to extract the mode from
18913         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
18914         *         {@link android.view.View.MeasureSpec#AT_MOST} or
18915         *         {@link android.view.View.MeasureSpec#EXACTLY}
18916         */
18917        public static int getMode(int measureSpec) {
18918            return (measureSpec & MODE_MASK);
18919        }
18920
18921        /**
18922         * Extracts the size from the supplied measure specification.
18923         *
18924         * @param measureSpec the measure specification to extract the size from
18925         * @return the size in pixels defined in the supplied measure specification
18926         */
18927        public static int getSize(int measureSpec) {
18928            return (measureSpec & ~MODE_MASK);
18929        }
18930
18931        static int adjust(int measureSpec, int delta) {
18932            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18933        }
18934
18935        /**
18936         * Returns a String representation of the specified measure
18937         * specification.
18938         *
18939         * @param measureSpec the measure specification to convert to a String
18940         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18941         */
18942        public static String toString(int measureSpec) {
18943            int mode = getMode(measureSpec);
18944            int size = getSize(measureSpec);
18945
18946            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18947
18948            if (mode == UNSPECIFIED)
18949                sb.append("UNSPECIFIED ");
18950            else if (mode == EXACTLY)
18951                sb.append("EXACTLY ");
18952            else if (mode == AT_MOST)
18953                sb.append("AT_MOST ");
18954            else
18955                sb.append(mode).append(" ");
18956
18957            sb.append(size);
18958            return sb.toString();
18959        }
18960    }
18961
18962    class CheckForLongPress implements Runnable {
18963
18964        private int mOriginalWindowAttachCount;
18965
18966        public void run() {
18967            if (isPressed() && (mParent != null)
18968                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18969                if (performLongClick()) {
18970                    mHasPerformedLongPress = true;
18971                }
18972            }
18973        }
18974
18975        public void rememberWindowAttachCount() {
18976            mOriginalWindowAttachCount = mWindowAttachCount;
18977        }
18978    }
18979
18980    private final class CheckForTap implements Runnable {
18981        public void run() {
18982            mPrivateFlags &= ~PFLAG_PREPRESSED;
18983            setPressed(true);
18984            checkForLongClick(ViewConfiguration.getTapTimeout());
18985        }
18986    }
18987
18988    private final class PerformClick implements Runnable {
18989        public void run() {
18990            performClick();
18991        }
18992    }
18993
18994    /** @hide */
18995    public void hackTurnOffWindowResizeAnim(boolean off) {
18996        mAttachInfo.mTurnOffWindowResizeAnim = off;
18997    }
18998
18999    /**
19000     * This method returns a ViewPropertyAnimator object, which can be used to animate
19001     * specific properties on this View.
19002     *
19003     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19004     */
19005    public ViewPropertyAnimator animate() {
19006        if (mAnimator == null) {
19007            mAnimator = new ViewPropertyAnimator(this);
19008        }
19009        return mAnimator;
19010    }
19011
19012    /**
19013     * Specifies that the shared name of the View to be shared with another Activity.
19014     * When transitioning between Activities, the name links a UI element in the starting
19015     * Activity to UI element in the called Activity. Names should be unique in the
19016     * View hierarchy.
19017     *
19018     * @param sharedElementName The cross-Activity View identifier. The called Activity will use
19019     *                 the name to match the location with a View in its layout.
19020     * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle)
19021     */
19022    public void setSharedElementName(String sharedElementName) {
19023        setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName);
19024    }
19025
19026    /**
19027     * Returns the shared name of the View to be shared with another Activity.
19028     * When transitioning between Activities, the name links a UI element in the starting
19029     * Activity to UI element in the called Activity. Names should be unique in the
19030     * View hierarchy.
19031     *
19032     * <p>This returns null if the View is not a shared element or the name if it is.</p>
19033     *
19034     * @return The name used for this View for cross-Activity transitions or null if
19035     * this View has not been identified as shared.
19036     */
19037    public String getSharedElementName() {
19038        return (String) getTag(com.android.internal.R.id.shared_element_name);
19039    }
19040
19041    /**
19042     * Interface definition for a callback to be invoked when a hardware key event is
19043     * dispatched to this view. The callback will be invoked before the key event is
19044     * given to the view. This is only useful for hardware keyboards; a software input
19045     * method has no obligation to trigger this listener.
19046     */
19047    public interface OnKeyListener {
19048        /**
19049         * Called when a hardware key is dispatched to a view. This allows listeners to
19050         * get a chance to respond before the target view.
19051         * <p>Key presses in software keyboards will generally NOT trigger this method,
19052         * although some may elect to do so in some situations. Do not assume a
19053         * software input method has to be key-based; even if it is, it may use key presses
19054         * in a different way than you expect, so there is no way to reliably catch soft
19055         * input key presses.
19056         *
19057         * @param v The view the key has been dispatched to.
19058         * @param keyCode The code for the physical key that was pressed
19059         * @param event The KeyEvent object containing full information about
19060         *        the event.
19061         * @return True if the listener has consumed the event, false otherwise.
19062         */
19063        boolean onKey(View v, int keyCode, KeyEvent event);
19064    }
19065
19066    /**
19067     * Interface definition for a callback to be invoked when a touch event is
19068     * dispatched to this view. The callback will be invoked before the touch
19069     * event is given to the view.
19070     */
19071    public interface OnTouchListener {
19072        /**
19073         * Called when a touch event is dispatched to a view. This allows listeners to
19074         * get a chance to respond before the target view.
19075         *
19076         * @param v The view the touch event has been dispatched to.
19077         * @param event The MotionEvent object containing full information about
19078         *        the event.
19079         * @return True if the listener has consumed the event, false otherwise.
19080         */
19081        boolean onTouch(View v, MotionEvent event);
19082    }
19083
19084    /**
19085     * Interface definition for a callback to be invoked when a hover event is
19086     * dispatched to this view. The callback will be invoked before the hover
19087     * event is given to the view.
19088     */
19089    public interface OnHoverListener {
19090        /**
19091         * Called when a hover event is dispatched to a view. This allows listeners to
19092         * get a chance to respond before the target view.
19093         *
19094         * @param v The view the hover event has been dispatched to.
19095         * @param event The MotionEvent object containing full information about
19096         *        the event.
19097         * @return True if the listener has consumed the event, false otherwise.
19098         */
19099        boolean onHover(View v, MotionEvent event);
19100    }
19101
19102    /**
19103     * Interface definition for a callback to be invoked when a generic motion event is
19104     * dispatched to this view. The callback will be invoked before the generic motion
19105     * event is given to the view.
19106     */
19107    public interface OnGenericMotionListener {
19108        /**
19109         * Called when a generic motion event is dispatched to a view. This allows listeners to
19110         * get a chance to respond before the target view.
19111         *
19112         * @param v The view the generic motion event has been dispatched to.
19113         * @param event The MotionEvent object containing full information about
19114         *        the event.
19115         * @return True if the listener has consumed the event, false otherwise.
19116         */
19117        boolean onGenericMotion(View v, MotionEvent event);
19118    }
19119
19120    /**
19121     * Interface definition for a callback to be invoked when a view has been clicked and held.
19122     */
19123    public interface OnLongClickListener {
19124        /**
19125         * Called when a view has been clicked and held.
19126         *
19127         * @param v The view that was clicked and held.
19128         *
19129         * @return true if the callback consumed the long click, false otherwise.
19130         */
19131        boolean onLongClick(View v);
19132    }
19133
19134    /**
19135     * Interface definition for a callback to be invoked when a drag is being dispatched
19136     * to this view.  The callback will be invoked before the hosting view's own
19137     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19138     * onDrag(event) behavior, it should return 'false' from this callback.
19139     *
19140     * <div class="special reference">
19141     * <h3>Developer Guides</h3>
19142     * <p>For a guide to implementing drag and drop features, read the
19143     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19144     * </div>
19145     */
19146    public interface OnDragListener {
19147        /**
19148         * Called when a drag event is dispatched to a view. This allows listeners
19149         * to get a chance to override base View behavior.
19150         *
19151         * @param v The View that received the drag event.
19152         * @param event The {@link android.view.DragEvent} object for the drag event.
19153         * @return {@code true} if the drag event was handled successfully, or {@code false}
19154         * if the drag event was not handled. Note that {@code false} will trigger the View
19155         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19156         */
19157        boolean onDrag(View v, DragEvent event);
19158    }
19159
19160    /**
19161     * Interface definition for a callback to be invoked when the focus state of
19162     * a view changed.
19163     */
19164    public interface OnFocusChangeListener {
19165        /**
19166         * Called when the focus state of a view has changed.
19167         *
19168         * @param v The view whose state has changed.
19169         * @param hasFocus The new focus state of v.
19170         */
19171        void onFocusChange(View v, boolean hasFocus);
19172    }
19173
19174    /**
19175     * Interface definition for a callback to be invoked when a view is clicked.
19176     */
19177    public interface OnClickListener {
19178        /**
19179         * Called when a view has been clicked.
19180         *
19181         * @param v The view that was clicked.
19182         */
19183        void onClick(View v);
19184    }
19185
19186    /**
19187     * Interface definition for a callback to be invoked when the context menu
19188     * for this view is being built.
19189     */
19190    public interface OnCreateContextMenuListener {
19191        /**
19192         * Called when the context menu for this view is being built. It is not
19193         * safe to hold onto the menu after this method returns.
19194         *
19195         * @param menu The context menu that is being built
19196         * @param v The view for which the context menu is being built
19197         * @param menuInfo Extra information about the item for which the
19198         *            context menu should be shown. This information will vary
19199         *            depending on the class of v.
19200         */
19201        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19202    }
19203
19204    /**
19205     * Interface definition for a callback to be invoked when the status bar changes
19206     * visibility.  This reports <strong>global</strong> changes to the system UI
19207     * state, not what the application is requesting.
19208     *
19209     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19210     */
19211    public interface OnSystemUiVisibilityChangeListener {
19212        /**
19213         * Called when the status bar changes visibility because of a call to
19214         * {@link View#setSystemUiVisibility(int)}.
19215         *
19216         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19217         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19218         * This tells you the <strong>global</strong> state of these UI visibility
19219         * flags, not what your app is currently applying.
19220         */
19221        public void onSystemUiVisibilityChange(int visibility);
19222    }
19223
19224    /**
19225     * Interface definition for a callback to be invoked when this view is attached
19226     * or detached from its window.
19227     */
19228    public interface OnAttachStateChangeListener {
19229        /**
19230         * Called when the view is attached to a window.
19231         * @param v The view that was attached
19232         */
19233        public void onViewAttachedToWindow(View v);
19234        /**
19235         * Called when the view is detached from a window.
19236         * @param v The view that was detached
19237         */
19238        public void onViewDetachedFromWindow(View v);
19239    }
19240
19241    /**
19242     * Listener for applying window insets on a view in a custom way.
19243     *
19244     * <p>Apps may choose to implement this interface if they want to apply custom policy
19245     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19246     * is set, its
19247     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19248     * method will be called instead of the View's own
19249     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19250     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19251     * the View's normal behavior as part of its own.</p>
19252     */
19253    public interface OnApplyWindowInsetsListener {
19254        /**
19255         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19256         * on a View, this listener method will be called instead of the view's own
19257         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19258         *
19259         * @param v The view applying window insets
19260         * @param insets The insets to apply
19261         * @return The insets supplied, minus any insets that were consumed
19262         */
19263        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19264    }
19265
19266    private final class UnsetPressedState implements Runnable {
19267        public void run() {
19268            setPressed(false);
19269        }
19270    }
19271
19272    /**
19273     * Base class for derived classes that want to save and restore their own
19274     * state in {@link android.view.View#onSaveInstanceState()}.
19275     */
19276    public static class BaseSavedState extends AbsSavedState {
19277        /**
19278         * Constructor used when reading from a parcel. Reads the state of the superclass.
19279         *
19280         * @param source
19281         */
19282        public BaseSavedState(Parcel source) {
19283            super(source);
19284        }
19285
19286        /**
19287         * Constructor called by derived classes when creating their SavedState objects
19288         *
19289         * @param superState The state of the superclass of this view
19290         */
19291        public BaseSavedState(Parcelable superState) {
19292            super(superState);
19293        }
19294
19295        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19296                new Parcelable.Creator<BaseSavedState>() {
19297            public BaseSavedState createFromParcel(Parcel in) {
19298                return new BaseSavedState(in);
19299            }
19300
19301            public BaseSavedState[] newArray(int size) {
19302                return new BaseSavedState[size];
19303            }
19304        };
19305    }
19306
19307    /**
19308     * A set of information given to a view when it is attached to its parent
19309     * window.
19310     */
19311    static class AttachInfo {
19312        interface Callbacks {
19313            void playSoundEffect(int effectId);
19314            boolean performHapticFeedback(int effectId, boolean always);
19315        }
19316
19317        /**
19318         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19319         * to a Handler. This class contains the target (View) to invalidate and
19320         * the coordinates of the dirty rectangle.
19321         *
19322         * For performance purposes, this class also implements a pool of up to
19323         * POOL_LIMIT objects that get reused. This reduces memory allocations
19324         * whenever possible.
19325         */
19326        static class InvalidateInfo {
19327            private static final int POOL_LIMIT = 10;
19328
19329            private static final SynchronizedPool<InvalidateInfo> sPool =
19330                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19331
19332            View target;
19333
19334            int left;
19335            int top;
19336            int right;
19337            int bottom;
19338
19339            public static InvalidateInfo obtain() {
19340                InvalidateInfo instance = sPool.acquire();
19341                return (instance != null) ? instance : new InvalidateInfo();
19342            }
19343
19344            public void recycle() {
19345                target = null;
19346                sPool.release(this);
19347            }
19348        }
19349
19350        final IWindowSession mSession;
19351
19352        final IWindow mWindow;
19353
19354        final IBinder mWindowToken;
19355
19356        final Display mDisplay;
19357
19358        final Callbacks mRootCallbacks;
19359
19360        IWindowId mIWindowId;
19361        WindowId mWindowId;
19362
19363        /**
19364         * The top view of the hierarchy.
19365         */
19366        View mRootView;
19367
19368        IBinder mPanelParentWindowToken;
19369
19370        boolean mHardwareAccelerated;
19371        boolean mHardwareAccelerationRequested;
19372        HardwareRenderer mHardwareRenderer;
19373
19374        boolean mScreenOn;
19375
19376        /**
19377         * Scale factor used by the compatibility mode
19378         */
19379        float mApplicationScale;
19380
19381        /**
19382         * Indicates whether the application is in compatibility mode
19383         */
19384        boolean mScalingRequired;
19385
19386        /**
19387         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19388         */
19389        boolean mTurnOffWindowResizeAnim;
19390
19391        /**
19392         * Left position of this view's window
19393         */
19394        int mWindowLeft;
19395
19396        /**
19397         * Top position of this view's window
19398         */
19399        int mWindowTop;
19400
19401        /**
19402         * Indicates whether views need to use 32-bit drawing caches
19403         */
19404        boolean mUse32BitDrawingCache;
19405
19406        /**
19407         * For windows that are full-screen but using insets to layout inside
19408         * of the screen areas, these are the current insets to appear inside
19409         * the overscan area of the display.
19410         */
19411        final Rect mOverscanInsets = new Rect();
19412
19413        /**
19414         * For windows that are full-screen but using insets to layout inside
19415         * of the screen decorations, these are the current insets for the
19416         * content of the window.
19417         */
19418        final Rect mContentInsets = new Rect();
19419
19420        /**
19421         * For windows that are full-screen but using insets to layout inside
19422         * of the screen decorations, these are the current insets for the
19423         * actual visible parts of the window.
19424         */
19425        final Rect mVisibleInsets = new Rect();
19426
19427        /**
19428         * The internal insets given by this window.  This value is
19429         * supplied by the client (through
19430         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19431         * be given to the window manager when changed to be used in laying
19432         * out windows behind it.
19433         */
19434        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19435                = new ViewTreeObserver.InternalInsetsInfo();
19436
19437        /**
19438         * Set to true when mGivenInternalInsets is non-empty.
19439         */
19440        boolean mHasNonEmptyGivenInternalInsets;
19441
19442        /**
19443         * All views in the window's hierarchy that serve as scroll containers,
19444         * used to determine if the window can be resized or must be panned
19445         * to adjust for a soft input area.
19446         */
19447        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19448
19449        final KeyEvent.DispatcherState mKeyDispatchState
19450                = new KeyEvent.DispatcherState();
19451
19452        /**
19453         * Indicates whether the view's window currently has the focus.
19454         */
19455        boolean mHasWindowFocus;
19456
19457        /**
19458         * The current visibility of the window.
19459         */
19460        int mWindowVisibility;
19461
19462        /**
19463         * Indicates the time at which drawing started to occur.
19464         */
19465        long mDrawingTime;
19466
19467        /**
19468         * Indicates whether or not ignoring the DIRTY_MASK flags.
19469         */
19470        boolean mIgnoreDirtyState;
19471
19472        /**
19473         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19474         * to avoid clearing that flag prematurely.
19475         */
19476        boolean mSetIgnoreDirtyState = false;
19477
19478        /**
19479         * Indicates whether the view's window is currently in touch mode.
19480         */
19481        boolean mInTouchMode;
19482
19483        /**
19484         * Indicates that ViewAncestor should trigger a global layout change
19485         * the next time it performs a traversal
19486         */
19487        boolean mRecomputeGlobalAttributes;
19488
19489        /**
19490         * Always report new attributes at next traversal.
19491         */
19492        boolean mForceReportNewAttributes;
19493
19494        /**
19495         * Set during a traveral if any views want to keep the screen on.
19496         */
19497        boolean mKeepScreenOn;
19498
19499        /**
19500         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19501         */
19502        int mSystemUiVisibility;
19503
19504        /**
19505         * Hack to force certain system UI visibility flags to be cleared.
19506         */
19507        int mDisabledSystemUiVisibility;
19508
19509        /**
19510         * Last global system UI visibility reported by the window manager.
19511         */
19512        int mGlobalSystemUiVisibility;
19513
19514        /**
19515         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19516         * attached.
19517         */
19518        boolean mHasSystemUiListeners;
19519
19520        /**
19521         * Set if the window has requested to extend into the overscan region
19522         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19523         */
19524        boolean mOverscanRequested;
19525
19526        /**
19527         * Set if the visibility of any views has changed.
19528         */
19529        boolean mViewVisibilityChanged;
19530
19531        /**
19532         * Set to true if a view has been scrolled.
19533         */
19534        boolean mViewScrollChanged;
19535
19536        /**
19537         * Global to the view hierarchy used as a temporary for dealing with
19538         * x/y points in the transparent region computations.
19539         */
19540        final int[] mTransparentLocation = new int[2];
19541
19542        /**
19543         * Global to the view hierarchy used as a temporary for dealing with
19544         * x/y points in the ViewGroup.invalidateChild implementation.
19545         */
19546        final int[] mInvalidateChildLocation = new int[2];
19547
19548
19549        /**
19550         * Global to the view hierarchy used as a temporary for dealing with
19551         * x/y location when view is transformed.
19552         */
19553        final float[] mTmpTransformLocation = new float[2];
19554
19555        /**
19556         * The view tree observer used to dispatch global events like
19557         * layout, pre-draw, touch mode change, etc.
19558         */
19559        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19560
19561        /**
19562         * A Canvas used by the view hierarchy to perform bitmap caching.
19563         */
19564        Canvas mCanvas;
19565
19566        /**
19567         * The view root impl.
19568         */
19569        final ViewRootImpl mViewRootImpl;
19570
19571        /**
19572         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19573         * handler can be used to pump events in the UI events queue.
19574         */
19575        final Handler mHandler;
19576
19577        /**
19578         * Temporary for use in computing invalidate rectangles while
19579         * calling up the hierarchy.
19580         */
19581        final Rect mTmpInvalRect = new Rect();
19582
19583        /**
19584         * Temporary for use in computing hit areas with transformed views
19585         */
19586        final RectF mTmpTransformRect = new RectF();
19587
19588        /**
19589         * Temporary for use in transforming invalidation rect
19590         */
19591        final Matrix mTmpMatrix = new Matrix();
19592
19593        /**
19594         * Temporary for use in transforming invalidation rect
19595         */
19596        final Transformation mTmpTransformation = new Transformation();
19597
19598        /**
19599         * Temporary list for use in collecting focusable descendents of a view.
19600         */
19601        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19602
19603        /**
19604         * The id of the window for accessibility purposes.
19605         */
19606        int mAccessibilityWindowId = View.NO_ID;
19607
19608        /**
19609         * Flags related to accessibility processing.
19610         *
19611         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19612         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19613         */
19614        int mAccessibilityFetchFlags;
19615
19616        /**
19617         * The drawable for highlighting accessibility focus.
19618         */
19619        Drawable mAccessibilityFocusDrawable;
19620
19621        /**
19622         * Show where the margins, bounds and layout bounds are for each view.
19623         */
19624        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19625
19626        /**
19627         * Point used to compute visible regions.
19628         */
19629        final Point mPoint = new Point();
19630
19631        /**
19632         * Used to track which View originated a requestLayout() call, used when
19633         * requestLayout() is called during layout.
19634         */
19635        View mViewRequestingLayout;
19636
19637        /**
19638         * Creates a new set of attachment information with the specified
19639         * events handler and thread.
19640         *
19641         * @param handler the events handler the view must use
19642         */
19643        AttachInfo(IWindowSession session, IWindow window, Display display,
19644                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19645            mSession = session;
19646            mWindow = window;
19647            mWindowToken = window.asBinder();
19648            mDisplay = display;
19649            mViewRootImpl = viewRootImpl;
19650            mHandler = handler;
19651            mRootCallbacks = effectPlayer;
19652        }
19653    }
19654
19655    /**
19656     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19657     * is supported. This avoids keeping too many unused fields in most
19658     * instances of View.</p>
19659     */
19660    private static class ScrollabilityCache implements Runnable {
19661
19662        /**
19663         * Scrollbars are not visible
19664         */
19665        public static final int OFF = 0;
19666
19667        /**
19668         * Scrollbars are visible
19669         */
19670        public static final int ON = 1;
19671
19672        /**
19673         * Scrollbars are fading away
19674         */
19675        public static final int FADING = 2;
19676
19677        public boolean fadeScrollBars;
19678
19679        public int fadingEdgeLength;
19680        public int scrollBarDefaultDelayBeforeFade;
19681        public int scrollBarFadeDuration;
19682
19683        public int scrollBarSize;
19684        public ScrollBarDrawable scrollBar;
19685        public float[] interpolatorValues;
19686        public View host;
19687
19688        public final Paint paint;
19689        public final Matrix matrix;
19690        public Shader shader;
19691
19692        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19693
19694        private static final float[] OPAQUE = { 255 };
19695        private static final float[] TRANSPARENT = { 0.0f };
19696
19697        /**
19698         * When fading should start. This time moves into the future every time
19699         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19700         */
19701        public long fadeStartTime;
19702
19703
19704        /**
19705         * The current state of the scrollbars: ON, OFF, or FADING
19706         */
19707        public int state = OFF;
19708
19709        private int mLastColor;
19710
19711        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19712            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19713            scrollBarSize = configuration.getScaledScrollBarSize();
19714            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19715            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19716
19717            paint = new Paint();
19718            matrix = new Matrix();
19719            // use use a height of 1, and then wack the matrix each time we
19720            // actually use it.
19721            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19722            paint.setShader(shader);
19723            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19724
19725            this.host = host;
19726        }
19727
19728        public void setFadeColor(int color) {
19729            if (color != mLastColor) {
19730                mLastColor = color;
19731
19732                if (color != 0) {
19733                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19734                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19735                    paint.setShader(shader);
19736                    // Restore the default transfer mode (src_over)
19737                    paint.setXfermode(null);
19738                } else {
19739                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19740                    paint.setShader(shader);
19741                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19742                }
19743            }
19744        }
19745
19746        public void run() {
19747            long now = AnimationUtils.currentAnimationTimeMillis();
19748            if (now >= fadeStartTime) {
19749
19750                // the animation fades the scrollbars out by changing
19751                // the opacity (alpha) from fully opaque to fully
19752                // transparent
19753                int nextFrame = (int) now;
19754                int framesCount = 0;
19755
19756                Interpolator interpolator = scrollBarInterpolator;
19757
19758                // Start opaque
19759                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19760
19761                // End transparent
19762                nextFrame += scrollBarFadeDuration;
19763                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19764
19765                state = FADING;
19766
19767                // Kick off the fade animation
19768                host.invalidate(true);
19769            }
19770        }
19771    }
19772
19773    /**
19774     * Resuable callback for sending
19775     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19776     */
19777    private class SendViewScrolledAccessibilityEvent implements Runnable {
19778        public volatile boolean mIsPending;
19779
19780        public void run() {
19781            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19782            mIsPending = false;
19783        }
19784    }
19785
19786    /**
19787     * <p>
19788     * This class represents a delegate that can be registered in a {@link View}
19789     * to enhance accessibility support via composition rather via inheritance.
19790     * It is specifically targeted to widget developers that extend basic View
19791     * classes i.e. classes in package android.view, that would like their
19792     * applications to be backwards compatible.
19793     * </p>
19794     * <div class="special reference">
19795     * <h3>Developer Guides</h3>
19796     * <p>For more information about making applications accessible, read the
19797     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19798     * developer guide.</p>
19799     * </div>
19800     * <p>
19801     * A scenario in which a developer would like to use an accessibility delegate
19802     * is overriding a method introduced in a later API version then the minimal API
19803     * version supported by the application. For example, the method
19804     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19805     * in API version 4 when the accessibility APIs were first introduced. If a
19806     * developer would like his application to run on API version 4 devices (assuming
19807     * all other APIs used by the application are version 4 or lower) and take advantage
19808     * of this method, instead of overriding the method which would break the application's
19809     * backwards compatibility, he can override the corresponding method in this
19810     * delegate and register the delegate in the target View if the API version of
19811     * the system is high enough i.e. the API version is same or higher to the API
19812     * version that introduced
19813     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19814     * </p>
19815     * <p>
19816     * Here is an example implementation:
19817     * </p>
19818     * <code><pre><p>
19819     * if (Build.VERSION.SDK_INT >= 14) {
19820     *     // If the API version is equal of higher than the version in
19821     *     // which onInitializeAccessibilityNodeInfo was introduced we
19822     *     // register a delegate with a customized implementation.
19823     *     View view = findViewById(R.id.view_id);
19824     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19825     *         public void onInitializeAccessibilityNodeInfo(View host,
19826     *                 AccessibilityNodeInfo info) {
19827     *             // Let the default implementation populate the info.
19828     *             super.onInitializeAccessibilityNodeInfo(host, info);
19829     *             // Set some other information.
19830     *             info.setEnabled(host.isEnabled());
19831     *         }
19832     *     });
19833     * }
19834     * </code></pre></p>
19835     * <p>
19836     * This delegate contains methods that correspond to the accessibility methods
19837     * in View. If a delegate has been specified the implementation in View hands
19838     * off handling to the corresponding method in this delegate. The default
19839     * implementation the delegate methods behaves exactly as the corresponding
19840     * method in View for the case of no accessibility delegate been set. Hence,
19841     * to customize the behavior of a View method, clients can override only the
19842     * corresponding delegate method without altering the behavior of the rest
19843     * accessibility related methods of the host view.
19844     * </p>
19845     */
19846    public static class AccessibilityDelegate {
19847
19848        /**
19849         * Sends an accessibility event of the given type. If accessibility is not
19850         * enabled this method has no effect.
19851         * <p>
19852         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19853         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19854         * been set.
19855         * </p>
19856         *
19857         * @param host The View hosting the delegate.
19858         * @param eventType The type of the event to send.
19859         *
19860         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
19861         */
19862        public void sendAccessibilityEvent(View host, int eventType) {
19863            host.sendAccessibilityEventInternal(eventType);
19864        }
19865
19866        /**
19867         * Performs the specified accessibility action on the view. For
19868         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
19869         * <p>
19870         * The default implementation behaves as
19871         * {@link View#performAccessibilityAction(int, Bundle)
19872         *  View#performAccessibilityAction(int, Bundle)} for the case of
19873         *  no accessibility delegate been set.
19874         * </p>
19875         *
19876         * @param action The action to perform.
19877         * @return Whether the action was performed.
19878         *
19879         * @see View#performAccessibilityAction(int, Bundle)
19880         *      View#performAccessibilityAction(int, Bundle)
19881         */
19882        public boolean performAccessibilityAction(View host, int action, Bundle args) {
19883            return host.performAccessibilityActionInternal(action, args);
19884        }
19885
19886        /**
19887         * Sends an accessibility event. This method behaves exactly as
19888         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
19889         * empty {@link AccessibilityEvent} and does not perform a check whether
19890         * accessibility is enabled.
19891         * <p>
19892         * The default implementation behaves as
19893         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19894         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
19895         * the case of no accessibility delegate been set.
19896         * </p>
19897         *
19898         * @param host The View hosting the delegate.
19899         * @param event The event to send.
19900         *
19901         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19902         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19903         */
19904        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
19905            host.sendAccessibilityEventUncheckedInternal(event);
19906        }
19907
19908        /**
19909         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
19910         * to its children for adding their text content to the event.
19911         * <p>
19912         * The default implementation behaves as
19913         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19914         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
19915         * the case of no accessibility delegate been set.
19916         * </p>
19917         *
19918         * @param host The View hosting the delegate.
19919         * @param event The event.
19920         * @return True if the event population was completed.
19921         *
19922         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19923         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19924         */
19925        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19926            return host.dispatchPopulateAccessibilityEventInternal(event);
19927        }
19928
19929        /**
19930         * Gives a chance to the host View to populate the accessibility event with its
19931         * text content.
19932         * <p>
19933         * The default implementation behaves as
19934         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
19935         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
19936         * the case of no accessibility delegate been set.
19937         * </p>
19938         *
19939         * @param host The View hosting the delegate.
19940         * @param event The accessibility event which to populate.
19941         *
19942         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
19943         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
19944         */
19945        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19946            host.onPopulateAccessibilityEventInternal(event);
19947        }
19948
19949        /**
19950         * Initializes an {@link AccessibilityEvent} with information about the
19951         * the host View which is the event source.
19952         * <p>
19953         * The default implementation behaves as
19954         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19955         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19956         * the case of no accessibility delegate been set.
19957         * </p>
19958         *
19959         * @param host The View hosting the delegate.
19960         * @param event The event to initialize.
19961         *
19962         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19963         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19964         */
19965        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19966            host.onInitializeAccessibilityEventInternal(event);
19967        }
19968
19969        /**
19970         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19971         * <p>
19972         * The default implementation behaves as
19973         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19974         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19975         * the case of no accessibility delegate been set.
19976         * </p>
19977         *
19978         * @param host The View hosting the delegate.
19979         * @param info The instance to initialize.
19980         *
19981         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19982         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19983         */
19984        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19985            host.onInitializeAccessibilityNodeInfoInternal(info);
19986        }
19987
19988        /**
19989         * Called when a child of the host View has requested sending an
19990         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19991         * to augment the event.
19992         * <p>
19993         * The default implementation behaves as
19994         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19995         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19996         * the case of no accessibility delegate been set.
19997         * </p>
19998         *
19999         * @param host The View hosting the delegate.
20000         * @param child The child which requests sending the event.
20001         * @param event The event to be sent.
20002         * @return True if the event should be sent
20003         *
20004         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20005         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20006         */
20007        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20008                AccessibilityEvent event) {
20009            return host.onRequestSendAccessibilityEventInternal(child, event);
20010        }
20011
20012        /**
20013         * Gets the provider for managing a virtual view hierarchy rooted at this View
20014         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20015         * that explore the window content.
20016         * <p>
20017         * The default implementation behaves as
20018         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20019         * the case of no accessibility delegate been set.
20020         * </p>
20021         *
20022         * @return The provider.
20023         *
20024         * @see AccessibilityNodeProvider
20025         */
20026        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20027            return null;
20028        }
20029
20030        /**
20031         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20032         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20033         * This method is responsible for obtaining an accessibility node info from a
20034         * pool of reusable instances and calling
20035         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20036         * view to initialize the former.
20037         * <p>
20038         * <strong>Note:</strong> The client is responsible for recycling the obtained
20039         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20040         * creation.
20041         * </p>
20042         * <p>
20043         * The default implementation behaves as
20044         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20045         * the case of no accessibility delegate been set.
20046         * </p>
20047         * @return A populated {@link AccessibilityNodeInfo}.
20048         *
20049         * @see AccessibilityNodeInfo
20050         *
20051         * @hide
20052         */
20053        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20054            return host.createAccessibilityNodeInfoInternal();
20055        }
20056    }
20057
20058    private class MatchIdPredicate implements Predicate<View> {
20059        public int mId;
20060
20061        @Override
20062        public boolean apply(View view) {
20063            return (view.mID == mId);
20064        }
20065    }
20066
20067    private class MatchLabelForPredicate implements Predicate<View> {
20068        private int mLabeledId;
20069
20070        @Override
20071        public boolean apply(View view) {
20072            return (view.mLabelForId == mLabeledId);
20073        }
20074    }
20075
20076    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20077        private int mChangeTypes = 0;
20078        private boolean mPosted;
20079        private boolean mPostedWithDelay;
20080        private long mLastEventTimeMillis;
20081
20082        @Override
20083        public void run() {
20084            mPosted = false;
20085            mPostedWithDelay = false;
20086            mLastEventTimeMillis = SystemClock.uptimeMillis();
20087            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20088                final AccessibilityEvent event = AccessibilityEvent.obtain();
20089                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20090                event.setContentChangeTypes(mChangeTypes);
20091                sendAccessibilityEventUnchecked(event);
20092            }
20093            mChangeTypes = 0;
20094        }
20095
20096        public void runOrPost(int changeType) {
20097            mChangeTypes |= changeType;
20098
20099            // If this is a live region or the child of a live region, collect
20100            // all events from this frame and send them on the next frame.
20101            if (inLiveRegion()) {
20102                // If we're already posted with a delay, remove that.
20103                if (mPostedWithDelay) {
20104                    removeCallbacks(this);
20105                    mPostedWithDelay = false;
20106                }
20107                // Only post if we're not already posted.
20108                if (!mPosted) {
20109                    post(this);
20110                    mPosted = true;
20111                }
20112                return;
20113            }
20114
20115            if (mPosted) {
20116                return;
20117            }
20118            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20119            final long minEventIntevalMillis =
20120                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20121            if (timeSinceLastMillis >= minEventIntevalMillis) {
20122                removeCallbacks(this);
20123                run();
20124            } else {
20125                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20126                mPosted = true;
20127                mPostedWithDelay = true;
20128            }
20129        }
20130    }
20131
20132    private boolean inLiveRegion() {
20133        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20134            return true;
20135        }
20136
20137        ViewParent parent = getParent();
20138        while (parent instanceof View) {
20139            if (((View) parent).getAccessibilityLiveRegion()
20140                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20141                return true;
20142            }
20143            parent = parent.getParent();
20144        }
20145
20146        return false;
20147    }
20148
20149    /**
20150     * Dump all private flags in readable format, useful for documentation and
20151     * sanity checking.
20152     */
20153    private static void dumpFlags() {
20154        final HashMap<String, String> found = Maps.newHashMap();
20155        try {
20156            for (Field field : View.class.getDeclaredFields()) {
20157                final int modifiers = field.getModifiers();
20158                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20159                    if (field.getType().equals(int.class)) {
20160                        final int value = field.getInt(null);
20161                        dumpFlag(found, field.getName(), value);
20162                    } else if (field.getType().equals(int[].class)) {
20163                        final int[] values = (int[]) field.get(null);
20164                        for (int i = 0; i < values.length; i++) {
20165                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20166                        }
20167                    }
20168                }
20169            }
20170        } catch (IllegalAccessException e) {
20171            throw new RuntimeException(e);
20172        }
20173
20174        final ArrayList<String> keys = Lists.newArrayList();
20175        keys.addAll(found.keySet());
20176        Collections.sort(keys);
20177        for (String key : keys) {
20178            Log.d(VIEW_LOG_TAG, found.get(key));
20179        }
20180    }
20181
20182    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20183        // Sort flags by prefix, then by bits, always keeping unique keys
20184        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20185        final int prefix = name.indexOf('_');
20186        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20187        final String output = bits + " " + name;
20188        found.put(key, output);
20189    }
20190}
20191