View.java revision f079a6d07f64045526a094077a1e9f4ceb40da76
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.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.hardware.display.DisplayManagerGlobal;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.IBinder;
46import android.os.Parcel;
47import android.os.Parcelable;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.text.TextUtils;
52import android.util.AttributeSet;
53import android.util.FloatProperty;
54import android.util.LayoutDirection;
55import android.util.Log;
56import android.util.LongSparseLongArray;
57import android.util.Pools.SynchronizedPool;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.SuperNotCalledException;
61import android.util.TypedValue;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.AccessibilityIterators.TextSegmentIterator;
64import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
65import android.view.AccessibilityIterators.WordTextSegmentIterator;
66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
67import android.view.accessibility.AccessibilityEvent;
68import android.view.accessibility.AccessibilityEventSource;
69import android.view.accessibility.AccessibilityManager;
70import android.view.accessibility.AccessibilityNodeInfo;
71import android.view.accessibility.AccessibilityNodeProvider;
72import android.view.animation.Animation;
73import android.view.animation.AnimationUtils;
74import android.view.animation.Transformation;
75import android.view.inputmethod.EditorInfo;
76import android.view.inputmethod.InputConnection;
77import android.view.inputmethod.InputMethodManager;
78import android.widget.ScrollBarDrawable;
79
80import static android.os.Build.VERSION_CODES.*;
81import static java.lang.Math.max;
82
83import com.android.internal.R;
84import com.android.internal.util.Predicate;
85import com.android.internal.view.menu.MenuBuilder;
86import com.google.android.collect.Lists;
87import com.google.android.collect.Maps;
88
89import java.lang.ref.WeakReference;
90import java.lang.reflect.Field;
91import java.lang.reflect.InvocationTargetException;
92import java.lang.reflect.Method;
93import java.lang.reflect.Modifier;
94import java.util.ArrayList;
95import java.util.Arrays;
96import java.util.Collections;
97import java.util.HashMap;
98import java.util.Locale;
99import java.util.concurrent.CopyOnWriteArrayList;
100import java.util.concurrent.atomic.AtomicInteger;
101
102/**
103 * <p>
104 * This class represents the basic building block for user interface components. A View
105 * occupies a rectangular area on the screen and is responsible for drawing and
106 * event handling. View is the base class for <em>widgets</em>, which are
107 * used to create interactive UI components (buttons, text fields, etc.). The
108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
109 * are invisible containers that hold other Views (or other ViewGroups) and define
110 * their layout properties.
111 * </p>
112 *
113 * <div class="special reference">
114 * <h3>Developer Guides</h3>
115 * <p>For information about using this class to develop your application's user interface,
116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
117 * </div>
118 *
119 * <a name="Using"></a>
120 * <h3>Using Views</h3>
121 * <p>
122 * All of the views in a window are arranged in a single tree. You can add views
123 * either from code or by specifying a tree of views in one or more XML layout
124 * files. There are many specialized subclasses of views that act as controls or
125 * are capable of displaying text, images, or other content.
126 * </p>
127 * <p>
128 * Once you have created a tree of views, there are typically a few types of
129 * common operations you may wish to perform:
130 * <ul>
131 * <li><strong>Set properties:</strong> for example setting the text of a
132 * {@link android.widget.TextView}. The available properties and the methods
133 * that set them will vary among the different subclasses of views. Note that
134 * properties that are known at build time can be set in the XML layout
135 * files.</li>
136 * <li><strong>Set focus:</strong> The framework will handled moving focus in
137 * response to user input. To force focus to a specific view, call
138 * {@link #requestFocus}.</li>
139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
140 * that will be notified when something interesting happens to the view. For
141 * example, all views will let you set a listener to be notified when the view
142 * gains or loses focus. You can register such a listener using
143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
144 * Other view subclasses offer more specialized listeners. For example, a Button
145 * exposes a listener to notify clients when the button is clicked.</li>
146 * <li><strong>Set visibility:</strong> You can hide or show views using
147 * {@link #setVisibility(int)}.</li>
148 * </ul>
149 * </p>
150 * <p><em>
151 * Note: The Android framework is responsible for measuring, laying out and
152 * drawing views. You should not call methods that perform these actions on
153 * views yourself unless you are actually implementing a
154 * {@link android.view.ViewGroup}.
155 * </em></p>
156 *
157 * <a name="Lifecycle"></a>
158 * <h3>Implementing a Custom View</h3>
159 *
160 * <p>
161 * To implement a custom view, you will usually begin by providing overrides for
162 * some of the standard methods that the framework calls on all views. You do
163 * not need to override all of these methods. In fact, you can start by just
164 * overriding {@link #onDraw(android.graphics.Canvas)}.
165 * <table border="2" width="85%" align="center" cellpadding="5">
166 *     <thead>
167 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
168 *     </thead>
169 *
170 *     <tbody>
171 *     <tr>
172 *         <td rowspan="2">Creation</td>
173 *         <td>Constructors</td>
174 *         <td>There is a form of the constructor that are called when the view
175 *         is created from code and a form that is called when the view is
176 *         inflated from a layout file. The second form should parse and apply
177 *         any attributes defined in the layout file.
178 *         </td>
179 *     </tr>
180 *     <tr>
181 *         <td><code>{@link #onFinishInflate()}</code></td>
182 *         <td>Called after a view and all of its children has been inflated
183 *         from XML.</td>
184 *     </tr>
185 *
186 *     <tr>
187 *         <td rowspan="3">Layout</td>
188 *         <td><code>{@link #onMeasure(int, int)}</code></td>
189 *         <td>Called to determine the size requirements for this view and all
190 *         of its children.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
195 *         <td>Called when this view should assign a size and position to all
196 *         of its children.
197 *         </td>
198 *     </tr>
199 *     <tr>
200 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
201 *         <td>Called when the size of this view has changed.
202 *         </td>
203 *     </tr>
204 *
205 *     <tr>
206 *         <td>Drawing</td>
207 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
208 *         <td>Called when the view should render its content.
209 *         </td>
210 *     </tr>
211 *
212 *     <tr>
213 *         <td rowspan="4">Event processing</td>
214 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
215 *         <td>Called when a new hardware key event occurs.
216 *         </td>
217 *     </tr>
218 *     <tr>
219 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
220 *         <td>Called when a hardware key up event occurs.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
225 *         <td>Called when a trackball motion event occurs.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
230 *         <td>Called when a touch screen motion event occurs.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="2">Focus</td>
236 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
237 *         <td>Called when the view gains or loses focus.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
243 *         <td>Called when the window containing the view gains or loses focus.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="3">Attaching</td>
249 *         <td><code>{@link #onAttachedToWindow()}</code></td>
250 *         <td>Called when the view is attached to a window.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onDetachedFromWindow}</code></td>
256 *         <td>Called when the view is detached from its window.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
262 *         <td>Called when the visibility of the window containing the view
263 *         has changed.
264 *         </td>
265 *     </tr>
266 *     </tbody>
267 *
268 * </table>
269 * </p>
270 *
271 * <a name="IDs"></a>
272 * <h3>IDs</h3>
273 * Views may have an integer id associated with them. These ids are typically
274 * assigned in the layout XML files, and are used to find specific views within
275 * the view tree. A common pattern is to:
276 * <ul>
277 * <li>Define a Button in the layout file and assign it a unique ID.
278 * <pre>
279 * &lt;Button
280 *     android:id="@+id/my_button"
281 *     android:layout_width="wrap_content"
282 *     android:layout_height="wrap_content"
283 *     android:text="@string/my_button_text"/&gt;
284 * </pre></li>
285 * <li>From the onCreate method of an Activity, find the Button
286 * <pre class="prettyprint">
287 *      Button myButton = (Button) findViewById(R.id.my_button);
288 * </pre></li>
289 * </ul>
290 * <p>
291 * View IDs need not be unique throughout the tree, but it is good practice to
292 * ensure that they are at least unique within the part of the tree you are
293 * searching.
294 * </p>
295 *
296 * <a name="Position"></a>
297 * <h3>Position</h3>
298 * <p>
299 * The geometry of a view is that of a rectangle. A view has a location,
300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
301 * two dimensions, expressed as a width and a height. The unit for location
302 * and dimensions is the pixel.
303 * </p>
304 *
305 * <p>
306 * It is possible to retrieve the location of a view by invoking the methods
307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
308 * coordinate of the rectangle representing the view. The latter returns the
309 * top, or Y, coordinate of the rectangle representing the view. These methods
310 * both return the location of the view relative to its parent. For instance,
311 * when getLeft() returns 20, that means the view is located 20 pixels to the
312 * right of the left edge of its direct parent.
313 * </p>
314 *
315 * <p>
316 * In addition, several convenience methods are offered to avoid unnecessary
317 * computations, namely {@link #getRight()} and {@link #getBottom()}.
318 * These methods return the coordinates of the right and bottom edges of the
319 * rectangle representing the view. For instance, calling {@link #getRight()}
320 * is similar to the following computation: <code>getLeft() + getWidth()</code>
321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
322 * </p>
323 *
324 * <a name="SizePaddingMargins"></a>
325 * <h3>Size, padding and margins</h3>
326 * <p>
327 * The size of a view is expressed with a width and a height. A view actually
328 * possess two pairs of width and height values.
329 * </p>
330 *
331 * <p>
332 * The first pair is known as <em>measured width</em> and
333 * <em>measured height</em>. These dimensions define how big a view wants to be
334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
336 * and {@link #getMeasuredHeight()}.
337 * </p>
338 *
339 * <p>
340 * The second pair is simply known as <em>width</em> and <em>height</em>, or
341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
342 * dimensions define the actual size of the view on screen, at drawing time and
343 * after layout. These values may, but do not have to, be different from the
344 * measured width and height. The width and height can be obtained by calling
345 * {@link #getWidth()} and {@link #getHeight()}.
346 * </p>
347 *
348 * <p>
349 * To measure its dimensions, a view takes into account its padding. The padding
350 * is expressed in pixels for the left, top, right and bottom parts of the view.
351 * Padding can be used to offset the content of the view by a specific amount of
352 * pixels. For instance, a left padding of 2 will push the view's content by
353 * 2 pixels to the right of the left edge. Padding can be set using the
354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
357 * {@link #getPaddingEnd()}.
358 * </p>
359 *
360 * <p>
361 * Even though a view can define a padding, it does not provide any support for
362 * margins. However, view groups provide such a support. Refer to
363 * {@link android.view.ViewGroup} and
364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
365 * </p>
366 *
367 * <a name="Layout"></a>
368 * <h3>Layout</h3>
369 * <p>
370 * Layout is a two pass process: a measure pass and a layout pass. The measuring
371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
372 * of the view tree. Each view pushes dimension specifications down the tree
373 * during the recursion. At the end of the measure pass, every view has stored
374 * its measurements. The second pass happens in
375 * {@link #layout(int,int,int,int)} and is also top-down. During
376 * this pass each parent is responsible for positioning all of its children
377 * using the sizes computed in the measure pass.
378 * </p>
379 *
380 * <p>
381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
382 * {@link #getMeasuredHeight()} values must be set, along with those for all of
383 * that view's descendants. A view's measured width and measured height values
384 * must respect the constraints imposed by the view's parents. This guarantees
385 * that at the end of the measure pass, all parents accept all of their
386 * children's measurements. A parent view may call measure() more than once on
387 * its children. For example, the parent may measure each child once with
388 * unspecified dimensions to find out how big they want to be, then call
389 * measure() on them again with actual numbers if the sum of all the children's
390 * unconstrained sizes is too big or too small.
391 * </p>
392 *
393 * <p>
394 * The measure pass uses two classes to communicate dimensions. The
395 * {@link MeasureSpec} class is used by views to tell their parents how they
396 * want to be measured and positioned. The base LayoutParams class just
397 * describes how big the view wants to be for both width and height. For each
398 * dimension, it can specify one of:
399 * <ul>
400 * <li> an exact number
401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
402 * (minus padding)
403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
404 * enclose its content (plus padding).
405 * </ul>
406 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
408 * an X and Y value.
409 * </p>
410 *
411 * <p>
412 * MeasureSpecs are used to push requirements down the tree from parent to
413 * child. A MeasureSpec can be in one of three modes:
414 * <ul>
415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
416 * of a child view. For example, a LinearLayout may call measure() on its child
417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
418 * tall the child view wants to be given a width of 240 pixels.
419 * <li>EXACTLY: This is used by the parent to impose an exact size on the
420 * child. The child must use this size, and guarantee that all of its
421 * descendants will fit within this size.
422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
423 * child. The child must gurantee that it and all of its descendants will fit
424 * within this size.
425 * </ul>
426 * </p>
427 *
428 * <p>
429 * To intiate a layout, call {@link #requestLayout}. This method is typically
430 * called by a view on itself when it believes that is can no longer fit within
431 * its current bounds.
432 * </p>
433 *
434 * <a name="Drawing"></a>
435 * <h3>Drawing</h3>
436 * <p>
437 * Drawing is handled by walking the tree and rendering each view that
438 * intersects the invalid region. Because the tree is traversed in-order,
439 * this means that parents will draw before (i.e., behind) their children, with
440 * siblings drawn in the order they appear in the tree.
441 * If you set a background drawable for a View, then the View will draw it for you
442 * before calling back to its <code>onDraw()</code> method.
443 * </p>
444 *
445 * <p>
446 * Note that the framework will not draw views that are not in the invalid region.
447 * </p>
448 *
449 * <p>
450 * To force a view to draw, call {@link #invalidate()}.
451 * </p>
452 *
453 * <a name="EventHandlingThreading"></a>
454 * <h3>Event Handling and Threading</h3>
455 * <p>
456 * The basic cycle of a view is as follows:
457 * <ol>
458 * <li>An event comes in and is dispatched to the appropriate view. The view
459 * handles the event and notifies any listeners.</li>
460 * <li>If in the course of processing the event, the view's bounds may need
461 * to be changed, the view will call {@link #requestLayout()}.</li>
462 * <li>Similarly, if in the course of processing the event the view's appearance
463 * may need to be changed, the view will call {@link #invalidate()}.</li>
464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
465 * the framework will take care of measuring, laying out, and drawing the tree
466 * as appropriate.</li>
467 * </ol>
468 * </p>
469 *
470 * <p><em>Note: The entire view tree is single threaded. You must always be on
471 * the UI thread when calling any method on any view.</em>
472 * If you are doing work on other threads and want to update the state of a view
473 * from that thread, you should use a {@link Handler}.
474 * </p>
475 *
476 * <a name="FocusHandling"></a>
477 * <h3>Focus Handling</h3>
478 * <p>
479 * The framework will handle routine focus movement in response to user input.
480 * This includes changing the focus as views are removed or hidden, or as new
481 * views become available. Views indicate their willingness to take focus
482 * through the {@link #isFocusable} method. To change whether a view can take
483 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
485 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
486 * </p>
487 * <p>
488 * Focus movement is based on an algorithm which finds the nearest neighbor in a
489 * given direction. In rare cases, the default algorithm may not match the
490 * intended behavior of the developer. In these situations, you can provide
491 * explicit overrides by using these XML attributes in the layout file:
492 * <pre>
493 * nextFocusDown
494 * nextFocusLeft
495 * nextFocusRight
496 * nextFocusUp
497 * </pre>
498 * </p>
499 *
500 *
501 * <p>
502 * To get a particular view to take focus, call {@link #requestFocus()}.
503 * </p>
504 *
505 * <a name="TouchMode"></a>
506 * <h3>Touch Mode</h3>
507 * <p>
508 * When a user is navigating a user interface via directional keys such as a D-pad, it is
509 * necessary to give focus to actionable items such as buttons so the user can see
510 * what will take input.  If the device has touch capabilities, however, and the user
511 * begins interacting with the interface by touching it, it is no longer necessary to
512 * always highlight, or give focus to, a particular view.  This motivates a mode
513 * for interaction named 'touch mode'.
514 * </p>
515 * <p>
516 * For a touch capable device, once the user touches the screen, the device
517 * will enter touch mode.  From this point onward, only views for which
518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
519 * Other views that are touchable, like buttons, will not take focus when touched; they will
520 * only fire the on click listeners.
521 * </p>
522 * <p>
523 * Any time a user hits a directional key, such as a D-pad direction, the view device will
524 * exit touch mode, and find a view to take focus, so that the user may resume interacting
525 * with the user interface without touching the screen again.
526 * </p>
527 * <p>
528 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
529 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
530 * </p>
531 *
532 * <a name="Scrolling"></a>
533 * <h3>Scrolling</h3>
534 * <p>
535 * The framework provides basic support for views that wish to internally
536 * scroll their content. This includes keeping track of the X and Y scroll
537 * offset as well as mechanisms for drawing scrollbars. See
538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
539 * {@link #awakenScrollBars()} for more details.
540 * </p>
541 *
542 * <a name="Tags"></a>
543 * <h3>Tags</h3>
544 * <p>
545 * Unlike IDs, tags are not used to identify views. Tags are essentially an
546 * extra piece of information that can be associated with a view. They are most
547 * often used as a convenience to store data related to views in the views
548 * themselves rather than by putting them in a separate structure.
549 * </p>
550 *
551 * <a name="Properties"></a>
552 * <h3>Properties</h3>
553 * <p>
554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
556 * available both in the {@link Property} form as well as in similarly-named setter/getter
557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
558 * be used to set persistent state associated with these rendering-related properties on the view.
559 * The properties and methods can also be used in conjunction with
560 * {@link android.animation.Animator Animator}-based animations, described more in the
561 * <a href="#Animation">Animation</a> section.
562 * </p>
563 *
564 * <a name="Animation"></a>
565 * <h3>Animation</h3>
566 * <p>
567 * Starting with Android 3.0, the preferred way of animating views is to use the
568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
573 * makes animating these View properties particularly easy and efficient.
574 * </p>
575 * <p>
576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
577 * You can attach an {@link Animation} object to a view using
578 * {@link #setAnimation(Animation)} or
579 * {@link #startAnimation(Animation)}. The animation can alter the scale,
580 * rotation, translation and alpha of a view over time. If the animation is
581 * attached to a view that has children, the animation will affect the entire
582 * subtree rooted by that node. When an animation is started, the framework will
583 * take care of redrawing the appropriate views until the animation completes.
584 * </p>
585 *
586 * <a name="Security"></a>
587 * <h3>Security</h3>
588 * <p>
589 * Sometimes it is essential that an application be able to verify that an action
590 * is being performed with the full knowledge and consent of the user, such as
591 * granting a permission request, making a purchase or clicking on an advertisement.
592 * Unfortunately, a malicious application could try to spoof the user into
593 * performing these actions, unaware, by concealing the intended purpose of the view.
594 * As a remedy, the framework offers a touch filtering mechanism that can be used to
595 * improve the security of views that provide access to sensitive functionality.
596 * </p><p>
597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
598 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
599 * will discard touches that are received whenever the view's window is obscured by
600 * another visible window.  As a result, the view will not receive touches whenever a
601 * toast, dialog or other window appears above the view's window.
602 * </p><p>
603 * For more fine-grained control over security, consider overriding the
604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
606 * </p>
607 *
608 * @attr ref android.R.styleable#View_alpha
609 * @attr ref android.R.styleable#View_background
610 * @attr ref android.R.styleable#View_clickable
611 * @attr ref android.R.styleable#View_contentDescription
612 * @attr ref android.R.styleable#View_drawingCacheQuality
613 * @attr ref android.R.styleable#View_duplicateParentState
614 * @attr ref android.R.styleable#View_id
615 * @attr ref android.R.styleable#View_requiresFadingEdge
616 * @attr ref android.R.styleable#View_fadeScrollbars
617 * @attr ref android.R.styleable#View_fadingEdgeLength
618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
619 * @attr ref android.R.styleable#View_fitsSystemWindows
620 * @attr ref android.R.styleable#View_isScrollContainer
621 * @attr ref android.R.styleable#View_focusable
622 * @attr ref android.R.styleable#View_focusableInTouchMode
623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
624 * @attr ref android.R.styleable#View_keepScreenOn
625 * @attr ref android.R.styleable#View_layerType
626 * @attr ref android.R.styleable#View_layoutDirection
627 * @attr ref android.R.styleable#View_longClickable
628 * @attr ref android.R.styleable#View_minHeight
629 * @attr ref android.R.styleable#View_minWidth
630 * @attr ref android.R.styleable#View_nextFocusDown
631 * @attr ref android.R.styleable#View_nextFocusLeft
632 * @attr ref android.R.styleable#View_nextFocusRight
633 * @attr ref android.R.styleable#View_nextFocusUp
634 * @attr ref android.R.styleable#View_onClick
635 * @attr ref android.R.styleable#View_padding
636 * @attr ref android.R.styleable#View_paddingBottom
637 * @attr ref android.R.styleable#View_paddingLeft
638 * @attr ref android.R.styleable#View_paddingRight
639 * @attr ref android.R.styleable#View_paddingTop
640 * @attr ref android.R.styleable#View_paddingStart
641 * @attr ref android.R.styleable#View_paddingEnd
642 * @attr ref android.R.styleable#View_saveEnabled
643 * @attr ref android.R.styleable#View_rotation
644 * @attr ref android.R.styleable#View_rotationX
645 * @attr ref android.R.styleable#View_rotationY
646 * @attr ref android.R.styleable#View_scaleX
647 * @attr ref android.R.styleable#View_scaleY
648 * @attr ref android.R.styleable#View_scrollX
649 * @attr ref android.R.styleable#View_scrollY
650 * @attr ref android.R.styleable#View_scrollbarSize
651 * @attr ref android.R.styleable#View_scrollbarStyle
652 * @attr ref android.R.styleable#View_scrollbars
653 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
654 * @attr ref android.R.styleable#View_scrollbarFadeDuration
655 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
657 * @attr ref android.R.styleable#View_scrollbarThumbVertical
658 * @attr ref android.R.styleable#View_scrollbarTrackVertical
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
661 * @attr ref android.R.styleable#View_soundEffectsEnabled
662 * @attr ref android.R.styleable#View_tag
663 * @attr ref android.R.styleable#View_textAlignment
664 * @attr ref android.R.styleable#View_textDirection
665 * @attr ref android.R.styleable#View_transformPivotX
666 * @attr ref android.R.styleable#View_transformPivotY
667 * @attr ref android.R.styleable#View_translationX
668 * @attr ref android.R.styleable#View_translationY
669 * @attr ref android.R.styleable#View_visibility
670 *
671 * @see android.view.ViewGroup
672 */
673public class View implements Drawable.Callback, KeyEvent.Callback,
674        AccessibilityEventSource {
675    private static final boolean DBG = false;
676
677    /**
678     * The logging tag used by this class with android.util.Log.
679     */
680    protected static final String VIEW_LOG_TAG = "View";
681
682    /**
683     * When set to true, apps will draw debugging information about their layouts.
684     *
685     * @hide
686     */
687    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
688
689    /**
690     * Used to mark a View that has no ID.
691     */
692    public static final int NO_ID = -1;
693
694    private static boolean sUseBrokenMakeMeasureSpec = false;
695
696    /**
697     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
698     * calling setFlags.
699     */
700    private static final int NOT_FOCUSABLE = 0x00000000;
701
702    /**
703     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
704     * setFlags.
705     */
706    private static final int FOCUSABLE = 0x00000001;
707
708    /**
709     * Mask for use with setFlags indicating bits used for focus.
710     */
711    private static final int FOCUSABLE_MASK = 0x00000001;
712
713    /**
714     * This view will adjust its padding to fit sytem windows (e.g. status bar)
715     */
716    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
717
718    /**
719     * This view is visible.
720     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
721     * android:visibility}.
722     */
723    public static final int VISIBLE = 0x00000000;
724
725    /**
726     * This view is invisible, but it still takes up space for layout purposes.
727     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
728     * android:visibility}.
729     */
730    public static final int INVISIBLE = 0x00000004;
731
732    /**
733     * This view is invisible, and it doesn't take any space for layout
734     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
735     * android:visibility}.
736     */
737    public static final int GONE = 0x00000008;
738
739    /**
740     * Mask for use with setFlags indicating bits used for visibility.
741     * {@hide}
742     */
743    static final int VISIBILITY_MASK = 0x0000000C;
744
745    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
746
747    /**
748     * This view is enabled. Interpretation varies by subclass.
749     * Use with ENABLED_MASK when calling setFlags.
750     * {@hide}
751     */
752    static final int ENABLED = 0x00000000;
753
754    /**
755     * This view is disabled. Interpretation varies by subclass.
756     * Use with ENABLED_MASK when calling setFlags.
757     * {@hide}
758     */
759    static final int DISABLED = 0x00000020;
760
761   /**
762    * Mask for use with setFlags indicating bits used for indicating whether
763    * this view is enabled
764    * {@hide}
765    */
766    static final int ENABLED_MASK = 0x00000020;
767
768    /**
769     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
770     * called and further optimizations will be performed. It is okay to have
771     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
772     * {@hide}
773     */
774    static final int WILL_NOT_DRAW = 0x00000080;
775
776    /**
777     * Mask for use with setFlags indicating bits used for indicating whether
778     * this view is will draw
779     * {@hide}
780     */
781    static final int DRAW_MASK = 0x00000080;
782
783    /**
784     * <p>This view doesn't show scrollbars.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_NONE = 0x00000000;
788
789    /**
790     * <p>This view shows horizontal scrollbars.</p>
791     * {@hide}
792     */
793    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
794
795    /**
796     * <p>This view shows vertical scrollbars.</p>
797     * {@hide}
798     */
799    static final int SCROLLBARS_VERTICAL = 0x00000200;
800
801    /**
802     * <p>Mask for use with setFlags indicating bits used for indicating which
803     * scrollbars are enabled.</p>
804     * {@hide}
805     */
806    static final int SCROLLBARS_MASK = 0x00000300;
807
808    /**
809     * Indicates that the view should filter touches when its window is obscured.
810     * Refer to the class comments for more information about this security feature.
811     * {@hide}
812     */
813    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
814
815    /**
816     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
817     * that they are optional and should be skipped if the window has
818     * requested system UI flags that ignore those insets for layout.
819     */
820    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
821
822    /**
823     * <p>This view doesn't show fading edges.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_NONE = 0x00000000;
827
828    /**
829     * <p>This view shows horizontal fading edges.</p>
830     * {@hide}
831     */
832    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
833
834    /**
835     * <p>This view shows vertical fading edges.</p>
836     * {@hide}
837     */
838    static final int FADING_EDGE_VERTICAL = 0x00002000;
839
840    /**
841     * <p>Mask for use with setFlags indicating bits used for indicating which
842     * fading edges are enabled.</p>
843     * {@hide}
844     */
845    static final int FADING_EDGE_MASK = 0x00003000;
846
847    /**
848     * <p>Indicates this view can be clicked. When clickable, a View reacts
849     * to clicks by notifying the OnClickListener.<p>
850     * {@hide}
851     */
852    static final int CLICKABLE = 0x00004000;
853
854    /**
855     * <p>Indicates this view is caching its drawing into a bitmap.</p>
856     * {@hide}
857     */
858    static final int DRAWING_CACHE_ENABLED = 0x00008000;
859
860    /**
861     * <p>Indicates that no icicle should be saved for this view.<p>
862     * {@hide}
863     */
864    static final int SAVE_DISABLED = 0x000010000;
865
866    /**
867     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
868     * property.</p>
869     * {@hide}
870     */
871    static final int SAVE_DISABLED_MASK = 0x000010000;
872
873    /**
874     * <p>Indicates that no drawing cache should ever be created for this view.<p>
875     * {@hide}
876     */
877    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
878
879    /**
880     * <p>Indicates this view can take / keep focus when int touch mode.</p>
881     * {@hide}
882     */
883    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
884
885    /**
886     * <p>Enables low quality mode for the drawing cache.</p>
887     */
888    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
889
890    /**
891     * <p>Enables high quality mode for the drawing cache.</p>
892     */
893    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
894
895    /**
896     * <p>Enables automatic quality mode for the drawing cache.</p>
897     */
898    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
899
900    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
901            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
902    };
903
904    /**
905     * <p>Mask for use with setFlags indicating bits used for the cache
906     * quality property.</p>
907     * {@hide}
908     */
909    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
910
911    /**
912     * <p>
913     * Indicates this view can be long clicked. When long clickable, a View
914     * reacts to long clicks by notifying the OnLongClickListener or showing a
915     * context menu.
916     * </p>
917     * {@hide}
918     */
919    static final int LONG_CLICKABLE = 0x00200000;
920
921    /**
922     * <p>Indicates that this view gets its drawable states from its direct parent
923     * and ignores its original internal states.</p>
924     *
925     * @hide
926     */
927    static final int DUPLICATE_PARENT_STATE = 0x00400000;
928
929    /**
930     * The scrollbar style to display the scrollbars inside the content area,
931     * without increasing the padding. The scrollbars will be overlaid with
932     * translucency on the view's content.
933     */
934    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
935
936    /**
937     * The scrollbar style to display the scrollbars inside the padded area,
938     * increasing the padding of the view. The scrollbars will not overlap the
939     * content area of the view.
940     */
941    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
942
943    /**
944     * The scrollbar style to display the scrollbars at the edge of the view,
945     * without increasing the padding. The scrollbars will be overlaid with
946     * translucency.
947     */
948    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
949
950    /**
951     * The scrollbar style to display the scrollbars at the edge of the view,
952     * increasing the padding of the view. The scrollbars will only overlap the
953     * background, if any.
954     */
955    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
956
957    /**
958     * Mask to check if the scrollbar style is overlay or inset.
959     * {@hide}
960     */
961    static final int SCROLLBARS_INSET_MASK = 0x01000000;
962
963    /**
964     * Mask to check if the scrollbar style is inside or outside.
965     * {@hide}
966     */
967    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
968
969    /**
970     * Mask for scrollbar style.
971     * {@hide}
972     */
973    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
974
975    /**
976     * View flag indicating that the screen should remain on while the
977     * window containing this view is visible to the user.  This effectively
978     * takes care of automatically setting the WindowManager's
979     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
980     */
981    public static final int KEEP_SCREEN_ON = 0x04000000;
982
983    /**
984     * View flag indicating whether this view should have sound effects enabled
985     * for events such as clicking and touching.
986     */
987    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
988
989    /**
990     * View flag indicating whether this view should have haptic feedback
991     * enabled for events such as long presses.
992     */
993    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
994
995    /**
996     * <p>Indicates that the view hierarchy should stop saving state when
997     * it reaches this view.  If state saving is initiated immediately at
998     * the view, it will be allowed.
999     * {@hide}
1000     */
1001    static final int PARENT_SAVE_DISABLED = 0x20000000;
1002
1003    /**
1004     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1005     * {@hide}
1006     */
1007    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add all focusable Views regardless if they are focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_ALL = 0x00000000;
1014
1015    /**
1016     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1017     * should add only Views focusable in touch mode.
1018     */
1019    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1023     * item.
1024     */
1025    public static final int FOCUS_BACKWARD = 0x00000001;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1029     * item.
1030     */
1031    public static final int FOCUS_FORWARD = 0x00000002;
1032
1033    /**
1034     * Use with {@link #focusSearch(int)}. Move focus to the left.
1035     */
1036    public static final int FOCUS_LEFT = 0x00000011;
1037
1038    /**
1039     * Use with {@link #focusSearch(int)}. Move focus up.
1040     */
1041    public static final int FOCUS_UP = 0x00000021;
1042
1043    /**
1044     * Use with {@link #focusSearch(int)}. Move focus to the right.
1045     */
1046    public static final int FOCUS_RIGHT = 0x00000042;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move focus down.
1050     */
1051    public static final int FOCUS_DOWN = 0x00000082;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1056     */
1057    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1058
1059    /**
1060     * Bits of {@link #getMeasuredWidthAndState()} and
1061     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1062     */
1063    public static final int MEASURED_STATE_MASK = 0xff000000;
1064
1065    /**
1066     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1067     * for functions that combine both width and height into a single int,
1068     * such as {@link #getMeasuredState()} and the childState argument of
1069     * {@link #resolveSizeAndState(int, int, int)}.
1070     */
1071    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1072
1073    /**
1074     * Bit of {@link #getMeasuredWidthAndState()} and
1075     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1076     * is smaller that the space the view would like to have.
1077     */
1078    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1079
1080    /**
1081     * Base View state sets
1082     */
1083    // Singles
1084    /**
1085     * Indicates the view has no states set. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] EMPTY_STATE_SET;
1093    /**
1094     * Indicates the view is enabled. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] ENABLED_STATE_SET;
1102    /**
1103     * Indicates the view is focused. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] FOCUSED_STATE_SET;
1111    /**
1112     * Indicates the view is selected. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     */
1119    protected static final int[] SELECTED_STATE_SET;
1120    /**
1121     * Indicates the view is pressed. States are used with
1122     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1123     * view depending on its state.
1124     *
1125     * @see android.graphics.drawable.Drawable
1126     * @see #getDrawableState()
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Accessibility event types that are dispatched for text population.
1488     */
1489    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1490            AccessibilityEvent.TYPE_VIEW_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1492            | AccessibilityEvent.TYPE_VIEW_SELECTED
1493            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1494            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1496            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1499            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1500            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1501
1502    /**
1503     * Temporary Rect currently for use in setBackground().  This will probably
1504     * be extended in the future to hold our own class with more than just
1505     * a Rect. :)
1506     */
1507    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1508
1509    /**
1510     * Map used to store views' tags.
1511     */
1512    private SparseArray<Object> mKeyedTags;
1513
1514    /**
1515     * The next available accessibility id.
1516     */
1517    private static int sNextAccessibilityViewId;
1518
1519    /**
1520     * The animation currently associated with this view.
1521     * @hide
1522     */
1523    protected Animation mCurrentAnimation = null;
1524
1525    /**
1526     * Width as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredWidth;
1531
1532    /**
1533     * Height as measured during measure pass.
1534     * {@hide}
1535     */
1536    @ViewDebug.ExportedProperty(category = "measurement")
1537    int mMeasuredHeight;
1538
1539    /**
1540     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1541     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1542     * its display list. This flag, used only when hw accelerated, allows us to clear the
1543     * flag while retaining this information until it's needed (at getDisplayList() time and
1544     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1545     *
1546     * {@hide}
1547     */
1548    boolean mRecreateDisplayList = false;
1549
1550    /**
1551     * The view's identifier.
1552     * {@hide}
1553     *
1554     * @see #setId(int)
1555     * @see #getId()
1556     */
1557    @ViewDebug.ExportedProperty(resolveId = true)
1558    int mID = NO_ID;
1559
1560    /**
1561     * The stable ID of this view for accessibility purposes.
1562     */
1563    int mAccessibilityViewId = NO_ID;
1564
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1568
1569    /**
1570     * The view's tag.
1571     * {@hide}
1572     *
1573     * @see #setTag(Object)
1574     * @see #getTag()
1575     */
1576    protected Object mTag;
1577
1578    // for mPrivateFlags:
1579    /** {@hide} */
1580    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1581    /** {@hide} */
1582    static final int PFLAG_FOCUSED                     = 0x00000002;
1583    /** {@hide} */
1584    static final int PFLAG_SELECTED                    = 0x00000004;
1585    /** {@hide} */
1586    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1587    /** {@hide} */
1588    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1589    /** {@hide} */
1590    static final int PFLAG_DRAWN                       = 0x00000020;
1591    /**
1592     * When this flag is set, this view is running an animation on behalf of its
1593     * children and should therefore not cancel invalidate requests, even if they
1594     * lie outside of this view's bounds.
1595     *
1596     * {@hide}
1597     */
1598    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1599    /** {@hide} */
1600    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1601    /** {@hide} */
1602    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1603    /** {@hide} */
1604    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1605    /** {@hide} */
1606    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1607    /** {@hide} */
1608    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1609    /** {@hide} */
1610    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1611    /** {@hide} */
1612    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1613
1614    private static final int PFLAG_PRESSED             = 0x00004000;
1615
1616    /** {@hide} */
1617    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1618    /**
1619     * Flag used to indicate that this view should be drawn once more (and only once
1620     * more) after its animation has completed.
1621     * {@hide}
1622     */
1623    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1624
1625    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1626
1627    /**
1628     * Indicates that the View returned true when onSetAlpha() was called and that
1629     * the alpha must be restored.
1630     * {@hide}
1631     */
1632    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1633
1634    /**
1635     * Set by {@link #setScrollContainer(boolean)}.
1636     */
1637    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1638
1639    /**
1640     * Set by {@link #setScrollContainer(boolean)}.
1641     */
1642    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1643
1644    /**
1645     * View flag indicating whether this view was invalidated (fully or partially.)
1646     *
1647     * @hide
1648     */
1649    static final int PFLAG_DIRTY                       = 0x00200000;
1650
1651    /**
1652     * View flag indicating whether this view was invalidated by an opaque
1653     * invalidate request.
1654     *
1655     * @hide
1656     */
1657    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1658
1659    /**
1660     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1661     *
1662     * @hide
1663     */
1664    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1665
1666    /**
1667     * Indicates whether the background is opaque.
1668     *
1669     * @hide
1670     */
1671    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1672
1673    /**
1674     * Indicates whether the scrollbars are opaque.
1675     *
1676     * @hide
1677     */
1678    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1679
1680    /**
1681     * Indicates whether the view is opaque.
1682     *
1683     * @hide
1684     */
1685    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1686
1687    /**
1688     * Indicates a prepressed state;
1689     * the short time between ACTION_DOWN and recognizing
1690     * a 'real' press. Prepressed is used to recognize quick taps
1691     * even when they are shorter than ViewConfiguration.getTapTimeout().
1692     *
1693     * @hide
1694     */
1695    private static final int PFLAG_PREPRESSED          = 0x02000000;
1696
1697    /**
1698     * Indicates whether the view is temporarily detached.
1699     *
1700     * @hide
1701     */
1702    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1703
1704    /**
1705     * Indicates that we should awaken scroll bars once attached
1706     *
1707     * @hide
1708     */
1709    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1710
1711    /**
1712     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1713     * @hide
1714     */
1715    private static final int PFLAG_HOVERED             = 0x10000000;
1716
1717    /**
1718     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1719     * for transform operations
1720     *
1721     * @hide
1722     */
1723    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1724
1725    /** {@hide} */
1726    static final int PFLAG_ACTIVATED                   = 0x40000000;
1727
1728    /**
1729     * Indicates that this view was specifically invalidated, not just dirtied because some
1730     * child view was invalidated. The flag is used to determine when we need to recreate
1731     * a view's display list (as opposed to just returning a reference to its existing
1732     * display list).
1733     *
1734     * @hide
1735     */
1736    static final int PFLAG_INVALIDATED                 = 0x80000000;
1737
1738    /**
1739     * Masks for mPrivateFlags2, as generated by dumpFlags():
1740     *
1741     * -------|-------|-------|-------|
1742     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1743     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1744     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1745     *                               1  PFLAG2_DRAG_HOVERED
1746     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1747     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1748     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1749     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1750     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1751     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1752     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1753     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1754     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1755     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1756     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1757     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1758     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1759     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1760     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1761     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1762     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1763     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1764     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1765     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1766     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1767     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1768     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1769     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1770     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1771     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1772     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1773     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1774     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1775     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1776     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1777     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1778     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1779     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1780     *   1                              PFLAG2_PADDING_RESOLVED
1781     * -------|-------|-------|-------|
1782     */
1783
1784    /**
1785     * Indicates that this view has reported that it can accept the current drag's content.
1786     * Cleared when the drag operation concludes.
1787     * @hide
1788     */
1789    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1790
1791    /**
1792     * Indicates that this view is currently directly under the drag location in a
1793     * drag-and-drop operation involving content that it can accept.  Cleared when
1794     * the drag exits the view, or when the drag operation concludes.
1795     * @hide
1796     */
1797    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1798
1799    /**
1800     * Horizontal layout direction of this view is from Left to Right.
1801     * Use with {@link #setLayoutDirection}.
1802     */
1803    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1804
1805    /**
1806     * Horizontal layout direction of this view is from Right to Left.
1807     * Use with {@link #setLayoutDirection}.
1808     */
1809    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1810
1811    /**
1812     * Horizontal layout direction of this view is inherited from its parent.
1813     * Use with {@link #setLayoutDirection}.
1814     */
1815    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1816
1817    /**
1818     * Horizontal layout direction of this view is from deduced from the default language
1819     * script for the locale. Use with {@link #setLayoutDirection}.
1820     */
1821    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1822
1823    /**
1824     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1825     * @hide
1826     */
1827    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1828
1829    /**
1830     * Mask for use with private flags indicating bits used for horizontal layout direction.
1831     * @hide
1832     */
1833    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1834
1835    /**
1836     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1837     * right-to-left direction.
1838     * @hide
1839     */
1840    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1841
1842    /**
1843     * Indicates whether the view horizontal layout direction has been resolved.
1844     * @hide
1845     */
1846    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1847
1848    /**
1849     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1850     * @hide
1851     */
1852    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1853            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1854
1855    /*
1856     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1857     * flag value.
1858     * @hide
1859     */
1860    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1861            LAYOUT_DIRECTION_LTR,
1862            LAYOUT_DIRECTION_RTL,
1863            LAYOUT_DIRECTION_INHERIT,
1864            LAYOUT_DIRECTION_LOCALE
1865    };
1866
1867    /**
1868     * Default horizontal layout direction.
1869     */
1870    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1871
1872    /**
1873     * Default horizontal layout direction.
1874     * @hide
1875     */
1876    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1877
1878    /**
1879     * Indicates that the view is tracking some sort of transient state
1880     * that the app should not need to be aware of, but that the framework
1881     * should take special care to preserve.
1882     *
1883     * @hide
1884     */
1885    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1886
1887    /**
1888     * Text direction is inherited thru {@link ViewGroup}
1889     */
1890    public static final int TEXT_DIRECTION_INHERIT = 0;
1891
1892    /**
1893     * Text direction is using "first strong algorithm". The first strong directional character
1894     * determines the paragraph direction. If there is no strong directional character, the
1895     * paragraph direction is the view's resolved layout direction.
1896     */
1897    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1898
1899    /**
1900     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1901     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1902     * If there are neither, the paragraph direction is the view's resolved layout direction.
1903     */
1904    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1905
1906    /**
1907     * Text direction is forced to LTR.
1908     */
1909    public static final int TEXT_DIRECTION_LTR = 3;
1910
1911    /**
1912     * Text direction is forced to RTL.
1913     */
1914    public static final int TEXT_DIRECTION_RTL = 4;
1915
1916    /**
1917     * Text direction is coming from the system Locale.
1918     */
1919    public static final int TEXT_DIRECTION_LOCALE = 5;
1920
1921    /**
1922     * Default text direction is inherited
1923     */
1924    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1925
1926    /**
1927     * Default resolved text direction
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1931
1932    /**
1933     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1934     * @hide
1935     */
1936    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1937
1938    /**
1939     * Mask for use with private flags indicating bits used for text direction.
1940     * @hide
1941     */
1942    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1943            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1944
1945    /**
1946     * Array of text direction flags for mapping attribute "textDirection" to correct
1947     * flag value.
1948     * @hide
1949     */
1950    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1951            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1952            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1957    };
1958
1959    /**
1960     * Indicates whether the view text direction has been resolved.
1961     * @hide
1962     */
1963    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1964            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1965
1966    /**
1967     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1968     * @hide
1969     */
1970    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1971
1972    /**
1973     * Mask for use with private flags indicating bits used for resolved text direction.
1974     * @hide
1975     */
1976    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1977            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1978
1979    /**
1980     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1981     * @hide
1982     */
1983    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1984            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1985
1986    /*
1987     * Default text alignment. The text alignment of this View is inherited from its parent.
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1991
1992    /**
1993     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1994     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1995     *
1996     * Use with {@link #setTextAlignment(int)}
1997     */
1998    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1999
2000    /**
2001     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2006
2007    /**
2008     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2009     *
2010     * Use with {@link #setTextAlignment(int)}
2011     */
2012    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2013
2014    /**
2015     * Center the paragraph, e.g. ALIGN_CENTER.
2016     *
2017     * Use with {@link #setTextAlignment(int)}
2018     */
2019    public static final int TEXT_ALIGNMENT_CENTER = 4;
2020
2021    /**
2022     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2023     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2024     *
2025     * Use with {@link #setTextAlignment(int)}
2026     */
2027    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2028
2029    /**
2030     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2031     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2032     *
2033     * Use with {@link #setTextAlignment(int)}
2034     */
2035    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2036
2037    /**
2038     * Default text alignment is inherited
2039     */
2040    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2041
2042    /**
2043     * Default resolved text alignment
2044     * @hide
2045     */
2046    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2047
2048    /**
2049      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2050      * @hide
2051      */
2052    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2053
2054    /**
2055      * Mask for use with private flags indicating bits used for text alignment.
2056      * @hide
2057      */
2058    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2059
2060    /**
2061     * Array of text direction flags for mapping attribute "textAlignment" to correct
2062     * flag value.
2063     * @hide
2064     */
2065    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2066            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2067            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2073    };
2074
2075    /**
2076     * Indicates whether the view text alignment has been resolved.
2077     * @hide
2078     */
2079    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2080
2081    /**
2082     * Bit shift to get the resolved text alignment.
2083     * @hide
2084     */
2085    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2086
2087    /**
2088     * Mask for use with private flags indicating bits used for text alignment.
2089     * @hide
2090     */
2091    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2092            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2093
2094    /**
2095     * Indicates whether if the view text alignment has been resolved to gravity
2096     */
2097    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2098            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2099
2100    // Accessiblity constants for mPrivateFlags2
2101
2102    /**
2103     * Shift for the bits in {@link #mPrivateFlags2} related to the
2104     * "importantForAccessibility" attribute.
2105     */
2106    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2107
2108    /**
2109     * Automatically determine whether a view is important for accessibility.
2110     */
2111    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2112
2113    /**
2114     * The view is important for accessibility.
2115     */
2116    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2117
2118    /**
2119     * The view is not important for accessibility.
2120     */
2121    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2122
2123    /**
2124     * The default whether the view is important for accessibility.
2125     */
2126    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2127
2128    /**
2129     * Mask for obtainig the bits which specify how to determine
2130     * whether a view is important for accessibility.
2131     */
2132    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2133        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2134        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2135
2136    /**
2137     * Shift for the bits in {@link #mPrivateFlags2} related to the
2138     * "accessibilityLiveRegion" attribute.
2139     */
2140    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 22;
2141
2142    /**
2143     * Live region mode specifying that accessibility services should not
2144     * automatically announce changes to this view. This is the default live
2145     * region mode for most views.
2146     * <p>
2147     * Use with {@link #setAccessibilityLiveRegion(int)}.
2148     */
2149    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2150
2151    /**
2152     * Live region mode specifying that accessibility services should announce
2153     * changes to this view.
2154     * <p>
2155     * Use with {@link #setAccessibilityLiveRegion(int)}.
2156     */
2157    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2158
2159    /**
2160     * Live region mode specifying that accessibility services should interrupt
2161     * ongoing speech to immediately announce changes to this view.
2162     * <p>
2163     * Use with {@link #setAccessibilityLiveRegion(int)}.
2164     */
2165    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2166
2167    /**
2168     * The default whether the view is important for accessibility.
2169     */
2170    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2171
2172    /**
2173     * Mask for obtaining the bits which specify a view's accessibility live
2174     * region mode.
2175     */
2176    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2177            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2178            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2179
2180    /**
2181     * Flag indicating whether a view has accessibility focus.
2182     */
2183    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2184
2185    /**
2186     * Flag whether the accessibility state of the subtree rooted at this view changed.
2187     */
2188    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2189
2190    /**
2191     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2192     * is used to check whether later changes to the view's transform should invalidate the
2193     * view to force the quickReject test to run again.
2194     */
2195    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2196
2197    /**
2198     * Flag indicating that start/end padding has been resolved into left/right padding
2199     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2200     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2201     * during measurement. In some special cases this is required such as when an adapter-based
2202     * view measures prospective children without attaching them to a window.
2203     */
2204    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2205
2206    /**
2207     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2208     */
2209    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2210
2211    /**
2212     * Group of bits indicating that RTL properties resolution is done.
2213     */
2214    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2215            PFLAG2_TEXT_DIRECTION_RESOLVED |
2216            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2217            PFLAG2_PADDING_RESOLVED |
2218            PFLAG2_DRAWABLE_RESOLVED;
2219
2220    // There are a couple of flags left in mPrivateFlags2
2221
2222    /* End of masks for mPrivateFlags2 */
2223
2224    /* Masks for mPrivateFlags3 */
2225
2226    /**
2227     * Flag indicating that view has a transform animation set on it. This is used to track whether
2228     * an animation is cleared between successive frames, in order to tell the associated
2229     * DisplayList to clear its animation matrix.
2230     */
2231    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2232
2233    /**
2234     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2235     * animation is cleared between successive frames, in order to tell the associated
2236     * DisplayList to restore its alpha value.
2237     */
2238    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2239
2240    /**
2241     * Flag indicating that the view has been through at least one layout since it
2242     * was last attached to a window.
2243     */
2244    static final int PFLAG3_IS_LAID_OUT = 0x4;
2245
2246    /**
2247     * Flag indicating that a call to measure() was skipped and should be done
2248     * instead when layout() is invoked.
2249     */
2250    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2251
2252    /**
2253     * Flag indicating that an overridden method correctly  called down to
2254     * the superclass implementation as required by the API spec.
2255     */
2256    static final int PFLAG3_CALLED_SUPER = 0x10;
2257
2258
2259    /* End of masks for mPrivateFlags3 */
2260
2261    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2262
2263    /**
2264     * Always allow a user to over-scroll this view, provided it is a
2265     * view that can scroll.
2266     *
2267     * @see #getOverScrollMode()
2268     * @see #setOverScrollMode(int)
2269     */
2270    public static final int OVER_SCROLL_ALWAYS = 0;
2271
2272    /**
2273     * Allow a user to over-scroll this view only if the content is large
2274     * enough to meaningfully scroll, provided it is a view that can scroll.
2275     *
2276     * @see #getOverScrollMode()
2277     * @see #setOverScrollMode(int)
2278     */
2279    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2280
2281    /**
2282     * Never allow a user to over-scroll this view.
2283     *
2284     * @see #getOverScrollMode()
2285     * @see #setOverScrollMode(int)
2286     */
2287    public static final int OVER_SCROLL_NEVER = 2;
2288
2289    /**
2290     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2291     * requested the system UI (status bar) to be visible (the default).
2292     *
2293     * @see #setSystemUiVisibility(int)
2294     */
2295    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2296
2297    /**
2298     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2299     * system UI to enter an unobtrusive "low profile" mode.
2300     *
2301     * <p>This is for use in games, book readers, video players, or any other
2302     * "immersive" application where the usual system chrome is deemed too distracting.
2303     *
2304     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2305     *
2306     * @see #setSystemUiVisibility(int)
2307     */
2308    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2309
2310    /**
2311     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2312     * system navigation be temporarily hidden.
2313     *
2314     * <p>This is an even less obtrusive state than that called for by
2315     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2316     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2317     * those to disappear. This is useful (in conjunction with the
2318     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2319     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2320     * window flags) for displaying content using every last pixel on the display.
2321     *
2322     * <p>There is a limitation: because navigation controls are so important, the least user
2323     * interaction will cause them to reappear immediately.  When this happens, both
2324     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2325     * so that both elements reappear at the same time.
2326     *
2327     * @see #setSystemUiVisibility(int)
2328     */
2329    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2330
2331    /**
2332     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2333     * into the normal fullscreen mode so that its content can take over the screen
2334     * while still allowing the user to interact with the application.
2335     *
2336     * <p>This has the same visual effect as
2337     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2338     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2339     * meaning that non-critical screen decorations (such as the status bar) will be
2340     * hidden while the user is in the View's window, focusing the experience on
2341     * that content.  Unlike the window flag, if you are using ActionBar in
2342     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2343     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2344     * hide the action bar.
2345     *
2346     * <p>This approach to going fullscreen is best used over the window flag when
2347     * it is a transient state -- that is, the application does this at certain
2348     * points in its user interaction where it wants to allow the user to focus
2349     * on content, but not as a continuous state.  For situations where the application
2350     * would like to simply stay full screen the entire time (such as a game that
2351     * wants to take over the screen), the
2352     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2353     * is usually a better approach.  The state set here will be removed by the system
2354     * in various situations (such as the user moving to another application) like
2355     * the other system UI states.
2356     *
2357     * <p>When using this flag, the application should provide some easy facility
2358     * for the user to go out of it.  A common example would be in an e-book
2359     * reader, where tapping on the screen brings back whatever screen and UI
2360     * decorations that had been hidden while the user was immersed in reading
2361     * the book.
2362     *
2363     * @see #setSystemUiVisibility(int)
2364     */
2365    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2366
2367    /**
2368     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2369     * flags, we would like a stable view of the content insets given to
2370     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2371     * will always represent the worst case that the application can expect
2372     * as a continuous state.  In the stock Android UI this is the space for
2373     * the system bar, nav bar, and status bar, but not more transient elements
2374     * such as an input method.
2375     *
2376     * The stable layout your UI sees is based on the system UI modes you can
2377     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2378     * then you will get a stable layout for changes of the
2379     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2380     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2381     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2382     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2383     * with a stable layout.  (Note that you should avoid using
2384     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2385     *
2386     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2387     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2388     * then a hidden status bar will be considered a "stable" state for purposes
2389     * here.  This allows your UI to continually hide the status bar, while still
2390     * using the system UI flags to hide the action bar while still retaining
2391     * a stable layout.  Note that changing the window fullscreen flag will never
2392     * provide a stable layout for a clean transition.
2393     *
2394     * <p>If you are using ActionBar in
2395     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2396     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2397     * insets it adds to those given to the application.
2398     */
2399    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2400
2401    /**
2402     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2403     * to be layed out as if it has requested
2404     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2405     * allows it to avoid artifacts when switching in and out of that mode, at
2406     * the expense that some of its user interface may be covered by screen
2407     * decorations when they are shown.  You can perform layout of your inner
2408     * UI elements to account for the navigation system UI through the
2409     * {@link #fitSystemWindows(Rect)} method.
2410     */
2411    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2412
2413    /**
2414     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2415     * to be layed out as if it has requested
2416     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2417     * allows it to avoid artifacts when switching in and out of that mode, at
2418     * the expense that some of its user interface may be covered by screen
2419     * decorations when they are shown.  You can perform layout of your inner
2420     * UI elements to account for non-fullscreen system UI through the
2421     * {@link #fitSystemWindows(Rect)} method.
2422     */
2423    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2424
2425    /**
2426     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2427     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2428     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2429     * experience while also hiding the system bars.  If this flag is not set,
2430     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2431     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2432     * if the user swipes from the top of the screen.
2433     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2434     * system gestures, such as swiping from the top of the screen.  These transient system bars
2435     * will overlay app’s content, may have some degree of transparency, and will automatically
2436     * hide after a short timeout.
2437     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2438     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2439     * with one or both of those flags.</p>
2440     */
2441    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2442
2443    /**
2444     * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have
2445     * transparency.
2446     *
2447     * <p>The transparency request may be denied if the bar is in another mode with a specific
2448     * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}.
2449     */
2450    public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000;
2451
2452    /**
2453     * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have
2454     * transparency.
2455     *
2456     * <p>The transparency request may be denied if the bar is in another mode with a specific
2457     * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}.
2458     */
2459    public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000;
2460
2461    /**
2462     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2463     */
2464    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2465
2466    /**
2467     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2468     */
2469    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2470
2471    /**
2472     * @hide
2473     *
2474     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2475     * out of the public fields to keep the undefined bits out of the developer's way.
2476     *
2477     * Flag to make the status bar not expandable.  Unless you also
2478     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2479     */
2480    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2481
2482    /**
2483     * @hide
2484     *
2485     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2486     * out of the public fields to keep the undefined bits out of the developer's way.
2487     *
2488     * Flag to hide notification icons and scrolling ticker text.
2489     */
2490    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2491
2492    /**
2493     * @hide
2494     *
2495     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2496     * out of the public fields to keep the undefined bits out of the developer's way.
2497     *
2498     * Flag to disable incoming notification alerts.  This will not block
2499     * icons, but it will block sound, vibrating and other visual or aural notifications.
2500     */
2501    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2502
2503    /**
2504     * @hide
2505     *
2506     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2507     * out of the public fields to keep the undefined bits out of the developer's way.
2508     *
2509     * Flag to hide only the scrolling ticker.  Note that
2510     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2511     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2512     */
2513    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2514
2515    /**
2516     * @hide
2517     *
2518     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2519     * out of the public fields to keep the undefined bits out of the developer's way.
2520     *
2521     * Flag to hide the center system info area.
2522     */
2523    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2524
2525    /**
2526     * @hide
2527     *
2528     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2529     * out of the public fields to keep the undefined bits out of the developer's way.
2530     *
2531     * Flag to hide only the home button.  Don't use this
2532     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2533     */
2534    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2535
2536    /**
2537     * @hide
2538     *
2539     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2540     * out of the public fields to keep the undefined bits out of the developer's way.
2541     *
2542     * Flag to hide only the back button. Don't use this
2543     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2544     */
2545    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2546
2547    /**
2548     * @hide
2549     *
2550     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2551     * out of the public fields to keep the undefined bits out of the developer's way.
2552     *
2553     * Flag to hide only the clock.  You might use this if your activity has
2554     * its own clock making the status bar's clock redundant.
2555     */
2556    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2557
2558    /**
2559     * @hide
2560     *
2561     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2562     * out of the public fields to keep the undefined bits out of the developer's way.
2563     *
2564     * Flag to hide only the recent apps button. Don't use this
2565     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2566     */
2567    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2568
2569    /**
2570     * @hide
2571     *
2572     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2573     * out of the public fields to keep the undefined bits out of the developer's way.
2574     *
2575     * Flag to disable the global search gesture. Don't use this
2576     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2577     */
2578    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2579
2580    /**
2581     * @hide
2582     *
2583     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2584     * out of the public fields to keep the undefined bits out of the developer's way.
2585     *
2586     * Flag to specify that the status bar is displayed in transient mode.
2587     */
2588    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2589
2590    /**
2591     * @hide
2592     *
2593     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2594     * out of the public fields to keep the undefined bits out of the developer's way.
2595     *
2596     * Flag to specify that the navigation bar is displayed in transient mode.
2597     */
2598    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2599
2600    /**
2601     * @hide
2602     *
2603     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2604     * out of the public fields to keep the undefined bits out of the developer's way.
2605     *
2606     * Flag to specify that the hidden status bar would like to be shown.
2607     */
2608    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2609
2610    /**
2611     * @hide
2612     *
2613     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2614     * out of the public fields to keep the undefined bits out of the developer's way.
2615     *
2616     * Flag to specify that the hidden navigation bar would like to be shown.
2617     */
2618    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2619
2620    /**
2621     * @hide
2622     */
2623    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2624
2625    /**
2626     * These are the system UI flags that can be cleared by events outside
2627     * of an application.  Currently this is just the ability to tap on the
2628     * screen while hiding the navigation bar to have it return.
2629     * @hide
2630     */
2631    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2632            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2633            | SYSTEM_UI_FLAG_FULLSCREEN;
2634
2635    /**
2636     * Flags that can impact the layout in relation to system UI.
2637     */
2638    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2639            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2640            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2641
2642    /**
2643     * Find views that render the specified text.
2644     *
2645     * @see #findViewsWithText(ArrayList, CharSequence, int)
2646     */
2647    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2648
2649    /**
2650     * Find find views that contain the specified content description.
2651     *
2652     * @see #findViewsWithText(ArrayList, CharSequence, int)
2653     */
2654    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2655
2656    /**
2657     * Find views that contain {@link AccessibilityNodeProvider}. Such
2658     * a View is a root of virtual view hierarchy and may contain the searched
2659     * text. If this flag is set Views with providers are automatically
2660     * added and it is a responsibility of the client to call the APIs of
2661     * the provider to determine whether the virtual tree rooted at this View
2662     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2663     * represeting the virtual views with this text.
2664     *
2665     * @see #findViewsWithText(ArrayList, CharSequence, int)
2666     *
2667     * @hide
2668     */
2669    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2670
2671    /**
2672     * The undefined cursor position.
2673     *
2674     * @hide
2675     */
2676    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2677
2678    /**
2679     * Indicates that the screen has changed state and is now off.
2680     *
2681     * @see #onScreenStateChanged(int)
2682     */
2683    public static final int SCREEN_STATE_OFF = 0x0;
2684
2685    /**
2686     * Indicates that the screen has changed state and is now on.
2687     *
2688     * @see #onScreenStateChanged(int)
2689     */
2690    public static final int SCREEN_STATE_ON = 0x1;
2691
2692    /**
2693     * Controls the over-scroll mode for this view.
2694     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2695     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2696     * and {@link #OVER_SCROLL_NEVER}.
2697     */
2698    private int mOverScrollMode;
2699
2700    /**
2701     * The parent this view is attached to.
2702     * {@hide}
2703     *
2704     * @see #getParent()
2705     */
2706    protected ViewParent mParent;
2707
2708    /**
2709     * {@hide}
2710     */
2711    AttachInfo mAttachInfo;
2712
2713    /**
2714     * {@hide}
2715     */
2716    @ViewDebug.ExportedProperty(flagMapping = {
2717        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2718                name = "FORCE_LAYOUT"),
2719        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2720                name = "LAYOUT_REQUIRED"),
2721        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2722            name = "DRAWING_CACHE_INVALID", outputIf = false),
2723        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2724        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2725        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2726        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2727    })
2728    int mPrivateFlags;
2729    int mPrivateFlags2;
2730    int mPrivateFlags3;
2731
2732    /**
2733     * This view's request for the visibility of the status bar.
2734     * @hide
2735     */
2736    @ViewDebug.ExportedProperty(flagMapping = {
2737        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2738                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2739                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2740        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2741                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2742                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2743        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2744                                equals = SYSTEM_UI_FLAG_VISIBLE,
2745                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2746    })
2747    int mSystemUiVisibility;
2748
2749    /**
2750     * Reference count for transient state.
2751     * @see #setHasTransientState(boolean)
2752     */
2753    int mTransientStateCount = 0;
2754
2755    /**
2756     * Count of how many windows this view has been attached to.
2757     */
2758    int mWindowAttachCount;
2759
2760    /**
2761     * The layout parameters associated with this view and used by the parent
2762     * {@link android.view.ViewGroup} to determine how this view should be
2763     * laid out.
2764     * {@hide}
2765     */
2766    protected ViewGroup.LayoutParams mLayoutParams;
2767
2768    /**
2769     * The view flags hold various views states.
2770     * {@hide}
2771     */
2772    @ViewDebug.ExportedProperty
2773    int mViewFlags;
2774
2775    static class TransformationInfo {
2776        /**
2777         * The transform matrix for the View. This transform is calculated internally
2778         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2779         * is used by default. Do *not* use this variable directly; instead call
2780         * getMatrix(), which will automatically recalculate the matrix if necessary
2781         * to get the correct matrix based on the latest rotation and scale properties.
2782         */
2783        private final Matrix mMatrix = new Matrix();
2784
2785        /**
2786         * The transform matrix for the View. This transform is calculated internally
2787         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2788         * is used by default. Do *not* use this variable directly; instead call
2789         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2790         * to get the correct matrix based on the latest rotation and scale properties.
2791         */
2792        private Matrix mInverseMatrix;
2793
2794        /**
2795         * An internal variable that tracks whether we need to recalculate the
2796         * transform matrix, based on whether the rotation or scaleX/Y properties
2797         * have changed since the matrix was last calculated.
2798         */
2799        boolean mMatrixDirty = false;
2800
2801        /**
2802         * An internal variable that tracks whether we need to recalculate the
2803         * transform matrix, based on whether the rotation or scaleX/Y properties
2804         * have changed since the matrix was last calculated.
2805         */
2806        private boolean mInverseMatrixDirty = true;
2807
2808        /**
2809         * A variable that tracks whether we need to recalculate the
2810         * transform matrix, based on whether the rotation or scaleX/Y properties
2811         * have changed since the matrix was last calculated. This variable
2812         * is only valid after a call to updateMatrix() or to a function that
2813         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2814         */
2815        private boolean mMatrixIsIdentity = true;
2816
2817        /**
2818         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2819         */
2820        private Camera mCamera = null;
2821
2822        /**
2823         * This matrix is used when computing the matrix for 3D rotations.
2824         */
2825        private Matrix matrix3D = null;
2826
2827        /**
2828         * These prev values are used to recalculate a centered pivot point when necessary. The
2829         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2830         * set), so thes values are only used then as well.
2831         */
2832        private int mPrevWidth = -1;
2833        private int mPrevHeight = -1;
2834
2835        /**
2836         * The degrees rotation around the vertical axis through the pivot point.
2837         */
2838        @ViewDebug.ExportedProperty
2839        float mRotationY = 0f;
2840
2841        /**
2842         * The degrees rotation around the horizontal axis through the pivot point.
2843         */
2844        @ViewDebug.ExportedProperty
2845        float mRotationX = 0f;
2846
2847        /**
2848         * The degrees rotation around the pivot point.
2849         */
2850        @ViewDebug.ExportedProperty
2851        float mRotation = 0f;
2852
2853        /**
2854         * The amount of translation of the object away from its left property (post-layout).
2855         */
2856        @ViewDebug.ExportedProperty
2857        float mTranslationX = 0f;
2858
2859        /**
2860         * The amount of translation of the object away from its top property (post-layout).
2861         */
2862        @ViewDebug.ExportedProperty
2863        float mTranslationY = 0f;
2864
2865        /**
2866         * The amount of scale in the x direction around the pivot point. A
2867         * value of 1 means no scaling is applied.
2868         */
2869        @ViewDebug.ExportedProperty
2870        float mScaleX = 1f;
2871
2872        /**
2873         * The amount of scale in the y direction around the pivot point. A
2874         * value of 1 means no scaling is applied.
2875         */
2876        @ViewDebug.ExportedProperty
2877        float mScaleY = 1f;
2878
2879        /**
2880         * The x location of the point around which the view is rotated and scaled.
2881         */
2882        @ViewDebug.ExportedProperty
2883        float mPivotX = 0f;
2884
2885        /**
2886         * The y location of the point around which the view is rotated and scaled.
2887         */
2888        @ViewDebug.ExportedProperty
2889        float mPivotY = 0f;
2890
2891        /**
2892         * The opacity of the View. This is a value from 0 to 1, where 0 means
2893         * completely transparent and 1 means completely opaque.
2894         */
2895        @ViewDebug.ExportedProperty
2896        float mAlpha = 1f;
2897
2898        /**
2899         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2900         * property only used by transitions, which is composited with the other alpha
2901         * values to calculate the final visual alpha value.
2902         */
2903        float mTransitionAlpha = 1f;
2904    }
2905
2906    TransformationInfo mTransformationInfo;
2907
2908    /**
2909     * Current clip bounds. to which all drawing of this view are constrained.
2910     */
2911    private Rect mClipBounds = null;
2912
2913    private boolean mLastIsOpaque;
2914
2915    /**
2916     * Convenience value to check for float values that are close enough to zero to be considered
2917     * zero.
2918     */
2919    private static final float NONZERO_EPSILON = .001f;
2920
2921    /**
2922     * The distance in pixels from the left edge of this view's parent
2923     * to the left edge of this view.
2924     * {@hide}
2925     */
2926    @ViewDebug.ExportedProperty(category = "layout")
2927    protected int mLeft;
2928    /**
2929     * The distance in pixels from the left edge of this view's parent
2930     * to the right edge of this view.
2931     * {@hide}
2932     */
2933    @ViewDebug.ExportedProperty(category = "layout")
2934    protected int mRight;
2935    /**
2936     * The distance in pixels from the top edge of this view's parent
2937     * to the top edge of this view.
2938     * {@hide}
2939     */
2940    @ViewDebug.ExportedProperty(category = "layout")
2941    protected int mTop;
2942    /**
2943     * The distance in pixels from the top edge of this view's parent
2944     * to the bottom edge of this view.
2945     * {@hide}
2946     */
2947    @ViewDebug.ExportedProperty(category = "layout")
2948    protected int mBottom;
2949
2950    /**
2951     * The offset, in pixels, by which the content of this view is scrolled
2952     * horizontally.
2953     * {@hide}
2954     */
2955    @ViewDebug.ExportedProperty(category = "scrolling")
2956    protected int mScrollX;
2957    /**
2958     * The offset, in pixels, by which the content of this view is scrolled
2959     * vertically.
2960     * {@hide}
2961     */
2962    @ViewDebug.ExportedProperty(category = "scrolling")
2963    protected int mScrollY;
2964
2965    /**
2966     * The left padding in pixels, that is the distance in pixels between the
2967     * left edge of this view and the left edge of its content.
2968     * {@hide}
2969     */
2970    @ViewDebug.ExportedProperty(category = "padding")
2971    protected int mPaddingLeft = 0;
2972    /**
2973     * The right padding in pixels, that is the distance in pixels between the
2974     * right edge of this view and the right edge of its content.
2975     * {@hide}
2976     */
2977    @ViewDebug.ExportedProperty(category = "padding")
2978    protected int mPaddingRight = 0;
2979    /**
2980     * The top padding in pixels, that is the distance in pixels between the
2981     * top edge of this view and the top edge of its content.
2982     * {@hide}
2983     */
2984    @ViewDebug.ExportedProperty(category = "padding")
2985    protected int mPaddingTop;
2986    /**
2987     * The bottom padding in pixels, that is the distance in pixels between the
2988     * bottom edge of this view and the bottom edge of its content.
2989     * {@hide}
2990     */
2991    @ViewDebug.ExportedProperty(category = "padding")
2992    protected int mPaddingBottom;
2993
2994    /**
2995     * The layout insets in pixels, that is the distance in pixels between the
2996     * visible edges of this view its bounds.
2997     */
2998    private Insets mLayoutInsets;
2999
3000    /**
3001     * Briefly describes the view and is primarily used for accessibility support.
3002     */
3003    private CharSequence mContentDescription;
3004
3005    /**
3006     * Specifies the id of a view for which this view serves as a label for
3007     * accessibility purposes.
3008     */
3009    private int mLabelForId = View.NO_ID;
3010
3011    /**
3012     * Predicate for matching labeled view id with its label for
3013     * accessibility purposes.
3014     */
3015    private MatchLabelForPredicate mMatchLabelForPredicate;
3016
3017    /**
3018     * Predicate for matching a view by its id.
3019     */
3020    private MatchIdPredicate mMatchIdPredicate;
3021
3022    /**
3023     * Cache the paddingRight set by the user to append to the scrollbar's size.
3024     *
3025     * @hide
3026     */
3027    @ViewDebug.ExportedProperty(category = "padding")
3028    protected int mUserPaddingRight;
3029
3030    /**
3031     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3032     *
3033     * @hide
3034     */
3035    @ViewDebug.ExportedProperty(category = "padding")
3036    protected int mUserPaddingBottom;
3037
3038    /**
3039     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3040     *
3041     * @hide
3042     */
3043    @ViewDebug.ExportedProperty(category = "padding")
3044    protected int mUserPaddingLeft;
3045
3046    /**
3047     * Cache the paddingStart set by the user to append to the scrollbar's size.
3048     *
3049     */
3050    @ViewDebug.ExportedProperty(category = "padding")
3051    int mUserPaddingStart;
3052
3053    /**
3054     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3055     *
3056     */
3057    @ViewDebug.ExportedProperty(category = "padding")
3058    int mUserPaddingEnd;
3059
3060    /**
3061     * Cache initial left padding.
3062     *
3063     * @hide
3064     */
3065    int mUserPaddingLeftInitial;
3066
3067    /**
3068     * Cache initial right padding.
3069     *
3070     * @hide
3071     */
3072    int mUserPaddingRightInitial;
3073
3074    /**
3075     * Default undefined padding
3076     */
3077    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3078
3079    /**
3080     * @hide
3081     */
3082    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3083    /**
3084     * @hide
3085     */
3086    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3087
3088    private LongSparseLongArray mMeasureCache;
3089
3090    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3091    private Drawable mBackground;
3092
3093    private int mBackgroundResource;
3094    private boolean mBackgroundSizeChanged;
3095
3096    static class ListenerInfo {
3097        /**
3098         * Listener used to dispatch focus change events.
3099         * This field should be made private, so it is hidden from the SDK.
3100         * {@hide}
3101         */
3102        protected OnFocusChangeListener mOnFocusChangeListener;
3103
3104        /**
3105         * Listeners for layout change events.
3106         */
3107        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3108
3109        /**
3110         * Listeners for attach events.
3111         */
3112        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3113
3114        /**
3115         * Listener used to dispatch click events.
3116         * This field should be made private, so it is hidden from the SDK.
3117         * {@hide}
3118         */
3119        public OnClickListener mOnClickListener;
3120
3121        /**
3122         * Listener used to dispatch long click events.
3123         * This field should be made private, so it is hidden from the SDK.
3124         * {@hide}
3125         */
3126        protected OnLongClickListener mOnLongClickListener;
3127
3128        /**
3129         * Listener used to build the context menu.
3130         * This field should be made private, so it is hidden from the SDK.
3131         * {@hide}
3132         */
3133        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3134
3135        private OnKeyListener mOnKeyListener;
3136
3137        private OnTouchListener mOnTouchListener;
3138
3139        private OnHoverListener mOnHoverListener;
3140
3141        private OnGenericMotionListener mOnGenericMotionListener;
3142
3143        private OnDragListener mOnDragListener;
3144
3145        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3146    }
3147
3148    ListenerInfo mListenerInfo;
3149
3150    /**
3151     * The application environment this view lives in.
3152     * This field should be made private, so it is hidden from the SDK.
3153     * {@hide}
3154     */
3155    protected Context mContext;
3156
3157    private final Resources mResources;
3158
3159    private ScrollabilityCache mScrollCache;
3160
3161    private int[] mDrawableState = null;
3162
3163    /**
3164     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3165     * the user may specify which view to go to next.
3166     */
3167    private int mNextFocusLeftId = View.NO_ID;
3168
3169    /**
3170     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3171     * the user may specify which view to go to next.
3172     */
3173    private int mNextFocusRightId = View.NO_ID;
3174
3175    /**
3176     * When this view has focus and the next focus is {@link #FOCUS_UP},
3177     * the user may specify which view to go to next.
3178     */
3179    private int mNextFocusUpId = View.NO_ID;
3180
3181    /**
3182     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3183     * the user may specify which view to go to next.
3184     */
3185    private int mNextFocusDownId = View.NO_ID;
3186
3187    /**
3188     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3189     * the user may specify which view to go to next.
3190     */
3191    int mNextFocusForwardId = View.NO_ID;
3192
3193    private CheckForLongPress mPendingCheckForLongPress;
3194    private CheckForTap mPendingCheckForTap = null;
3195    private PerformClick mPerformClick;
3196    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3197
3198    private UnsetPressedState mUnsetPressedState;
3199
3200    /**
3201     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3202     * up event while a long press is invoked as soon as the long press duration is reached, so
3203     * a long press could be performed before the tap is checked, in which case the tap's action
3204     * should not be invoked.
3205     */
3206    private boolean mHasPerformedLongPress;
3207
3208    /**
3209     * The minimum height of the view. We'll try our best to have the height
3210     * of this view to at least this amount.
3211     */
3212    @ViewDebug.ExportedProperty(category = "measurement")
3213    private int mMinHeight;
3214
3215    /**
3216     * The minimum width of the view. We'll try our best to have the width
3217     * of this view to at least this amount.
3218     */
3219    @ViewDebug.ExportedProperty(category = "measurement")
3220    private int mMinWidth;
3221
3222    /**
3223     * The delegate to handle touch events that are physically in this view
3224     * but should be handled by another view.
3225     */
3226    private TouchDelegate mTouchDelegate = null;
3227
3228    /**
3229     * Solid color to use as a background when creating the drawing cache. Enables
3230     * the cache to use 16 bit bitmaps instead of 32 bit.
3231     */
3232    private int mDrawingCacheBackgroundColor = 0;
3233
3234    /**
3235     * Special tree observer used when mAttachInfo is null.
3236     */
3237    private ViewTreeObserver mFloatingTreeObserver;
3238
3239    /**
3240     * Cache the touch slop from the context that created the view.
3241     */
3242    private int mTouchSlop;
3243
3244    /**
3245     * Object that handles automatic animation of view properties.
3246     */
3247    private ViewPropertyAnimator mAnimator = null;
3248
3249    /**
3250     * Flag indicating that a drag can cross window boundaries.  When
3251     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3252     * with this flag set, all visible applications will be able to participate
3253     * in the drag operation and receive the dragged content.
3254     *
3255     * @hide
3256     */
3257    public static final int DRAG_FLAG_GLOBAL = 1;
3258
3259    /**
3260     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3261     */
3262    private float mVerticalScrollFactor;
3263
3264    /**
3265     * Position of the vertical scroll bar.
3266     */
3267    private int mVerticalScrollbarPosition;
3268
3269    /**
3270     * Position the scroll bar at the default position as determined by the system.
3271     */
3272    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3273
3274    /**
3275     * Position the scroll bar along the left edge.
3276     */
3277    public static final int SCROLLBAR_POSITION_LEFT = 1;
3278
3279    /**
3280     * Position the scroll bar along the right edge.
3281     */
3282    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3283
3284    /**
3285     * Indicates that the view does not have a layer.
3286     *
3287     * @see #getLayerType()
3288     * @see #setLayerType(int, android.graphics.Paint)
3289     * @see #LAYER_TYPE_SOFTWARE
3290     * @see #LAYER_TYPE_HARDWARE
3291     */
3292    public static final int LAYER_TYPE_NONE = 0;
3293
3294    /**
3295     * <p>Indicates that the view has a software layer. A software layer is backed
3296     * by a bitmap and causes the view to be rendered using Android's software
3297     * rendering pipeline, even if hardware acceleration is enabled.</p>
3298     *
3299     * <p>Software layers have various usages:</p>
3300     * <p>When the application is not using hardware acceleration, a software layer
3301     * is useful to apply a specific color filter and/or blending mode and/or
3302     * translucency to a view and all its children.</p>
3303     * <p>When the application is using hardware acceleration, a software layer
3304     * is useful to render drawing primitives not supported by the hardware
3305     * accelerated pipeline. It can also be used to cache a complex view tree
3306     * into a texture and reduce the complexity of drawing operations. For instance,
3307     * when animating a complex view tree with a translation, a software layer can
3308     * be used to render the view tree only once.</p>
3309     * <p>Software layers should be avoided when the affected view tree updates
3310     * often. Every update will require to re-render the software layer, which can
3311     * potentially be slow (particularly when hardware acceleration is turned on
3312     * since the layer will have to be uploaded into a hardware texture after every
3313     * update.)</p>
3314     *
3315     * @see #getLayerType()
3316     * @see #setLayerType(int, android.graphics.Paint)
3317     * @see #LAYER_TYPE_NONE
3318     * @see #LAYER_TYPE_HARDWARE
3319     */
3320    public static final int LAYER_TYPE_SOFTWARE = 1;
3321
3322    /**
3323     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3324     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3325     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3326     * rendering pipeline, but only if hardware acceleration is turned on for the
3327     * view hierarchy. When hardware acceleration is turned off, hardware layers
3328     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3329     *
3330     * <p>A hardware layer is useful to apply a specific color filter and/or
3331     * blending mode and/or translucency to a view and all its children.</p>
3332     * <p>A hardware layer can be used to cache a complex view tree into a
3333     * texture and reduce the complexity of drawing operations. For instance,
3334     * when animating a complex view tree with a translation, a hardware layer can
3335     * be used to render the view tree only once.</p>
3336     * <p>A hardware layer can also be used to increase the rendering quality when
3337     * rotation transformations are applied on a view. It can also be used to
3338     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3339     *
3340     * @see #getLayerType()
3341     * @see #setLayerType(int, android.graphics.Paint)
3342     * @see #LAYER_TYPE_NONE
3343     * @see #LAYER_TYPE_SOFTWARE
3344     */
3345    public static final int LAYER_TYPE_HARDWARE = 2;
3346
3347    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3348            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3349            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3350            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3351    })
3352    int mLayerType = LAYER_TYPE_NONE;
3353    Paint mLayerPaint;
3354    Rect mLocalDirtyRect;
3355    private HardwareLayer mHardwareLayer;
3356
3357    /**
3358     * Set to true when drawing cache is enabled and cannot be created.
3359     *
3360     * @hide
3361     */
3362    public boolean mCachingFailed;
3363    private Bitmap mDrawingCache;
3364    private Bitmap mUnscaledDrawingCache;
3365
3366    DisplayList mDisplayList;
3367
3368    /**
3369     * Set to true when the view is sending hover accessibility events because it
3370     * is the innermost hovered view.
3371     */
3372    private boolean mSendingHoverAccessibilityEvents;
3373
3374    /**
3375     * Delegate for injecting accessibility functionality.
3376     */
3377    AccessibilityDelegate mAccessibilityDelegate;
3378
3379    /**
3380     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3381     * and add/remove objects to/from the overlay directly through the Overlay methods.
3382     */
3383    ViewOverlay mOverlay;
3384
3385    /**
3386     * Consistency verifier for debugging purposes.
3387     * @hide
3388     */
3389    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3390            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3391                    new InputEventConsistencyVerifier(this, 0) : null;
3392
3393    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3394
3395    /**
3396     * Simple constructor to use when creating a view from code.
3397     *
3398     * @param context The Context the view is running in, through which it can
3399     *        access the current theme, resources, etc.
3400     */
3401    public View(Context context) {
3402        mContext = context;
3403        mResources = context != null ? context.getResources() : null;
3404        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3405        // Set some flags defaults
3406        mPrivateFlags2 =
3407                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3408                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3409                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3410                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3411                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3412                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3413        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3414        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3415        mUserPaddingStart = UNDEFINED_PADDING;
3416        mUserPaddingEnd = UNDEFINED_PADDING;
3417
3418        if (!sUseBrokenMakeMeasureSpec && context != null &&
3419                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3420            // Older apps may need this compatibility hack for measurement.
3421            sUseBrokenMakeMeasureSpec = true;
3422        }
3423    }
3424
3425    /**
3426     * Constructor that is called when inflating a view from XML. This is called
3427     * when a view is being constructed from an XML file, supplying attributes
3428     * that were specified in the XML file. This version uses a default style of
3429     * 0, so the only attribute values applied are those in the Context's Theme
3430     * and the given AttributeSet.
3431     *
3432     * <p>
3433     * The method onFinishInflate() will be called after all children have been
3434     * added.
3435     *
3436     * @param context The Context the view is running in, through which it can
3437     *        access the current theme, resources, etc.
3438     * @param attrs The attributes of the XML tag that is inflating the view.
3439     * @see #View(Context, AttributeSet, int)
3440     */
3441    public View(Context context, AttributeSet attrs) {
3442        this(context, attrs, 0);
3443    }
3444
3445    /**
3446     * Perform inflation from XML and apply a class-specific base style. This
3447     * constructor of View allows subclasses to use their own base style when
3448     * they are inflating. For example, a Button class's constructor would call
3449     * this version of the super class constructor and supply
3450     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3451     * the theme's button style to modify all of the base view attributes (in
3452     * particular its background) as well as the Button class's attributes.
3453     *
3454     * @param context The Context the view is running in, through which it can
3455     *        access the current theme, resources, etc.
3456     * @param attrs The attributes of the XML tag that is inflating the view.
3457     * @param defStyleAttr An attribute in the current theme that contains a
3458     *        reference to a style resource to apply to this view. If 0, no
3459     *        default style will be applied.
3460     * @see #View(Context, AttributeSet)
3461     */
3462    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3463        this(context);
3464
3465        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3466                defStyleAttr, 0);
3467
3468        Drawable background = null;
3469
3470        int leftPadding = -1;
3471        int topPadding = -1;
3472        int rightPadding = -1;
3473        int bottomPadding = -1;
3474        int startPadding = UNDEFINED_PADDING;
3475        int endPadding = UNDEFINED_PADDING;
3476
3477        int padding = -1;
3478
3479        int viewFlagValues = 0;
3480        int viewFlagMasks = 0;
3481
3482        boolean setScrollContainer = false;
3483
3484        int x = 0;
3485        int y = 0;
3486
3487        float tx = 0;
3488        float ty = 0;
3489        float rotation = 0;
3490        float rotationX = 0;
3491        float rotationY = 0;
3492        float sx = 1f;
3493        float sy = 1f;
3494        boolean transformSet = false;
3495
3496        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3497        int overScrollMode = mOverScrollMode;
3498        boolean initializeScrollbars = false;
3499
3500        boolean leftPaddingDefined = false;
3501        boolean rightPaddingDefined = false;
3502        boolean startPaddingDefined = false;
3503        boolean endPaddingDefined = false;
3504
3505        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3506
3507        final int N = a.getIndexCount();
3508        for (int i = 0; i < N; i++) {
3509            int attr = a.getIndex(i);
3510            switch (attr) {
3511                case com.android.internal.R.styleable.View_background:
3512                    background = a.getDrawable(attr);
3513                    break;
3514                case com.android.internal.R.styleable.View_padding:
3515                    padding = a.getDimensionPixelSize(attr, -1);
3516                    mUserPaddingLeftInitial = padding;
3517                    mUserPaddingRightInitial = padding;
3518                    leftPaddingDefined = true;
3519                    rightPaddingDefined = true;
3520                    break;
3521                 case com.android.internal.R.styleable.View_paddingLeft:
3522                    leftPadding = a.getDimensionPixelSize(attr, -1);
3523                    mUserPaddingLeftInitial = leftPadding;
3524                    leftPaddingDefined = true;
3525                    break;
3526                case com.android.internal.R.styleable.View_paddingTop:
3527                    topPadding = a.getDimensionPixelSize(attr, -1);
3528                    break;
3529                case com.android.internal.R.styleable.View_paddingRight:
3530                    rightPadding = a.getDimensionPixelSize(attr, -1);
3531                    mUserPaddingRightInitial = rightPadding;
3532                    rightPaddingDefined = true;
3533                    break;
3534                case com.android.internal.R.styleable.View_paddingBottom:
3535                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3536                    break;
3537                case com.android.internal.R.styleable.View_paddingStart:
3538                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3539                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3540                    break;
3541                case com.android.internal.R.styleable.View_paddingEnd:
3542                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3543                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3544                    break;
3545                case com.android.internal.R.styleable.View_scrollX:
3546                    x = a.getDimensionPixelOffset(attr, 0);
3547                    break;
3548                case com.android.internal.R.styleable.View_scrollY:
3549                    y = a.getDimensionPixelOffset(attr, 0);
3550                    break;
3551                case com.android.internal.R.styleable.View_alpha:
3552                    setAlpha(a.getFloat(attr, 1f));
3553                    break;
3554                case com.android.internal.R.styleable.View_transformPivotX:
3555                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3556                    break;
3557                case com.android.internal.R.styleable.View_transformPivotY:
3558                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3559                    break;
3560                case com.android.internal.R.styleable.View_translationX:
3561                    tx = a.getDimensionPixelOffset(attr, 0);
3562                    transformSet = true;
3563                    break;
3564                case com.android.internal.R.styleable.View_translationY:
3565                    ty = a.getDimensionPixelOffset(attr, 0);
3566                    transformSet = true;
3567                    break;
3568                case com.android.internal.R.styleable.View_rotation:
3569                    rotation = a.getFloat(attr, 0);
3570                    transformSet = true;
3571                    break;
3572                case com.android.internal.R.styleable.View_rotationX:
3573                    rotationX = a.getFloat(attr, 0);
3574                    transformSet = true;
3575                    break;
3576                case com.android.internal.R.styleable.View_rotationY:
3577                    rotationY = a.getFloat(attr, 0);
3578                    transformSet = true;
3579                    break;
3580                case com.android.internal.R.styleable.View_scaleX:
3581                    sx = a.getFloat(attr, 1f);
3582                    transformSet = true;
3583                    break;
3584                case com.android.internal.R.styleable.View_scaleY:
3585                    sy = a.getFloat(attr, 1f);
3586                    transformSet = true;
3587                    break;
3588                case com.android.internal.R.styleable.View_id:
3589                    mID = a.getResourceId(attr, NO_ID);
3590                    break;
3591                case com.android.internal.R.styleable.View_tag:
3592                    mTag = a.getText(attr);
3593                    break;
3594                case com.android.internal.R.styleable.View_fitsSystemWindows:
3595                    if (a.getBoolean(attr, false)) {
3596                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3597                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3598                    }
3599                    break;
3600                case com.android.internal.R.styleable.View_focusable:
3601                    if (a.getBoolean(attr, false)) {
3602                        viewFlagValues |= FOCUSABLE;
3603                        viewFlagMasks |= FOCUSABLE_MASK;
3604                    }
3605                    break;
3606                case com.android.internal.R.styleable.View_focusableInTouchMode:
3607                    if (a.getBoolean(attr, false)) {
3608                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3609                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3610                    }
3611                    break;
3612                case com.android.internal.R.styleable.View_clickable:
3613                    if (a.getBoolean(attr, false)) {
3614                        viewFlagValues |= CLICKABLE;
3615                        viewFlagMasks |= CLICKABLE;
3616                    }
3617                    break;
3618                case com.android.internal.R.styleable.View_longClickable:
3619                    if (a.getBoolean(attr, false)) {
3620                        viewFlagValues |= LONG_CLICKABLE;
3621                        viewFlagMasks |= LONG_CLICKABLE;
3622                    }
3623                    break;
3624                case com.android.internal.R.styleable.View_saveEnabled:
3625                    if (!a.getBoolean(attr, true)) {
3626                        viewFlagValues |= SAVE_DISABLED;
3627                        viewFlagMasks |= SAVE_DISABLED_MASK;
3628                    }
3629                    break;
3630                case com.android.internal.R.styleable.View_duplicateParentState:
3631                    if (a.getBoolean(attr, false)) {
3632                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3633                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3634                    }
3635                    break;
3636                case com.android.internal.R.styleable.View_visibility:
3637                    final int visibility = a.getInt(attr, 0);
3638                    if (visibility != 0) {
3639                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3640                        viewFlagMasks |= VISIBILITY_MASK;
3641                    }
3642                    break;
3643                case com.android.internal.R.styleable.View_layoutDirection:
3644                    // Clear any layout direction flags (included resolved bits) already set
3645                    mPrivateFlags2 &=
3646                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3647                    // Set the layout direction flags depending on the value of the attribute
3648                    final int layoutDirection = a.getInt(attr, -1);
3649                    final int value = (layoutDirection != -1) ?
3650                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3651                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3652                    break;
3653                case com.android.internal.R.styleable.View_drawingCacheQuality:
3654                    final int cacheQuality = a.getInt(attr, 0);
3655                    if (cacheQuality != 0) {
3656                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3657                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3658                    }
3659                    break;
3660                case com.android.internal.R.styleable.View_contentDescription:
3661                    setContentDescription(a.getString(attr));
3662                    break;
3663                case com.android.internal.R.styleable.View_labelFor:
3664                    setLabelFor(a.getResourceId(attr, NO_ID));
3665                    break;
3666                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3667                    if (!a.getBoolean(attr, true)) {
3668                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3669                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3670                    }
3671                    break;
3672                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3673                    if (!a.getBoolean(attr, true)) {
3674                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3675                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3676                    }
3677                    break;
3678                case R.styleable.View_scrollbars:
3679                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3680                    if (scrollbars != SCROLLBARS_NONE) {
3681                        viewFlagValues |= scrollbars;
3682                        viewFlagMasks |= SCROLLBARS_MASK;
3683                        initializeScrollbars = true;
3684                    }
3685                    break;
3686                //noinspection deprecation
3687                case R.styleable.View_fadingEdge:
3688                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3689                        // Ignore the attribute starting with ICS
3690                        break;
3691                    }
3692                    // With builds < ICS, fall through and apply fading edges
3693                case R.styleable.View_requiresFadingEdge:
3694                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3695                    if (fadingEdge != FADING_EDGE_NONE) {
3696                        viewFlagValues |= fadingEdge;
3697                        viewFlagMasks |= FADING_EDGE_MASK;
3698                        initializeFadingEdge(a);
3699                    }
3700                    break;
3701                case R.styleable.View_scrollbarStyle:
3702                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3703                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3704                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3705                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3706                    }
3707                    break;
3708                case R.styleable.View_isScrollContainer:
3709                    setScrollContainer = true;
3710                    if (a.getBoolean(attr, false)) {
3711                        setScrollContainer(true);
3712                    }
3713                    break;
3714                case com.android.internal.R.styleable.View_keepScreenOn:
3715                    if (a.getBoolean(attr, false)) {
3716                        viewFlagValues |= KEEP_SCREEN_ON;
3717                        viewFlagMasks |= KEEP_SCREEN_ON;
3718                    }
3719                    break;
3720                case R.styleable.View_filterTouchesWhenObscured:
3721                    if (a.getBoolean(attr, false)) {
3722                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3723                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3724                    }
3725                    break;
3726                case R.styleable.View_nextFocusLeft:
3727                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3728                    break;
3729                case R.styleable.View_nextFocusRight:
3730                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3731                    break;
3732                case R.styleable.View_nextFocusUp:
3733                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3734                    break;
3735                case R.styleable.View_nextFocusDown:
3736                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3737                    break;
3738                case R.styleable.View_nextFocusForward:
3739                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3740                    break;
3741                case R.styleable.View_minWidth:
3742                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3743                    break;
3744                case R.styleable.View_minHeight:
3745                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3746                    break;
3747                case R.styleable.View_onClick:
3748                    if (context.isRestricted()) {
3749                        throw new IllegalStateException("The android:onClick attribute cannot "
3750                                + "be used within a restricted context");
3751                    }
3752
3753                    final String handlerName = a.getString(attr);
3754                    if (handlerName != null) {
3755                        setOnClickListener(new OnClickListener() {
3756                            private Method mHandler;
3757
3758                            public void onClick(View v) {
3759                                if (mHandler == null) {
3760                                    try {
3761                                        mHandler = getContext().getClass().getMethod(handlerName,
3762                                                View.class);
3763                                    } catch (NoSuchMethodException e) {
3764                                        int id = getId();
3765                                        String idText = id == NO_ID ? "" : " with id '"
3766                                                + getContext().getResources().getResourceEntryName(
3767                                                    id) + "'";
3768                                        throw new IllegalStateException("Could not find a method " +
3769                                                handlerName + "(View) in the activity "
3770                                                + getContext().getClass() + " for onClick handler"
3771                                                + " on view " + View.this.getClass() + idText, e);
3772                                    }
3773                                }
3774
3775                                try {
3776                                    mHandler.invoke(getContext(), View.this);
3777                                } catch (IllegalAccessException e) {
3778                                    throw new IllegalStateException("Could not execute non "
3779                                            + "public method of the activity", e);
3780                                } catch (InvocationTargetException e) {
3781                                    throw new IllegalStateException("Could not execute "
3782                                            + "method of the activity", e);
3783                                }
3784                            }
3785                        });
3786                    }
3787                    break;
3788                case R.styleable.View_overScrollMode:
3789                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3790                    break;
3791                case R.styleable.View_verticalScrollbarPosition:
3792                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3793                    break;
3794                case R.styleable.View_layerType:
3795                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3796                    break;
3797                case R.styleable.View_textDirection:
3798                    // Clear any text direction flag already set
3799                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3800                    // Set the text direction flags depending on the value of the attribute
3801                    final int textDirection = a.getInt(attr, -1);
3802                    if (textDirection != -1) {
3803                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3804                    }
3805                    break;
3806                case R.styleable.View_textAlignment:
3807                    // Clear any text alignment flag already set
3808                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3809                    // Set the text alignment flag depending on the value of the attribute
3810                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3811                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3812                    break;
3813                case R.styleable.View_importantForAccessibility:
3814                    setImportantForAccessibility(a.getInt(attr,
3815                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3816                    break;
3817                case R.styleable.View_accessibilityLiveRegion:
3818                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
3819                    break;
3820            }
3821        }
3822
3823        setOverScrollMode(overScrollMode);
3824
3825        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3826        // the resolved layout direction). Those cached values will be used later during padding
3827        // resolution.
3828        mUserPaddingStart = startPadding;
3829        mUserPaddingEnd = endPadding;
3830
3831        if (background != null) {
3832            setBackground(background);
3833        }
3834
3835        if (padding >= 0) {
3836            leftPadding = padding;
3837            topPadding = padding;
3838            rightPadding = padding;
3839            bottomPadding = padding;
3840            mUserPaddingLeftInitial = padding;
3841            mUserPaddingRightInitial = padding;
3842        }
3843
3844        if (isRtlCompatibilityMode()) {
3845            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3846            // left / right padding are used if defined (meaning here nothing to do). If they are not
3847            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3848            // start / end and resolve them as left / right (layout direction is not taken into account).
3849            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3850            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3851            // defined.
3852            if (!leftPaddingDefined && startPaddingDefined) {
3853                leftPadding = startPadding;
3854            }
3855            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3856            if (!rightPaddingDefined && endPaddingDefined) {
3857                rightPadding = endPadding;
3858            }
3859            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3860        } else {
3861            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3862            // values defined. Otherwise, left /right values are used.
3863            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3864            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3865            // defined.
3866            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3867
3868            if (leftPaddingDefined && !hasRelativePadding) {
3869                mUserPaddingLeftInitial = leftPadding;
3870            }
3871            if (rightPaddingDefined && !hasRelativePadding) {
3872                mUserPaddingRightInitial = rightPadding;
3873            }
3874        }
3875
3876        internalSetPadding(
3877                mUserPaddingLeftInitial,
3878                topPadding >= 0 ? topPadding : mPaddingTop,
3879                mUserPaddingRightInitial,
3880                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3881
3882        if (viewFlagMasks != 0) {
3883            setFlags(viewFlagValues, viewFlagMasks);
3884        }
3885
3886        if (initializeScrollbars) {
3887            initializeScrollbars(a);
3888        }
3889
3890        a.recycle();
3891
3892        // Needs to be called after mViewFlags is set
3893        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3894            recomputePadding();
3895        }
3896
3897        if (x != 0 || y != 0) {
3898            scrollTo(x, y);
3899        }
3900
3901        if (transformSet) {
3902            setTranslationX(tx);
3903            setTranslationY(ty);
3904            setRotation(rotation);
3905            setRotationX(rotationX);
3906            setRotationY(rotationY);
3907            setScaleX(sx);
3908            setScaleY(sy);
3909        }
3910
3911        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3912            setScrollContainer(true);
3913        }
3914
3915        computeOpaqueFlags();
3916    }
3917
3918    /**
3919     * Non-public constructor for use in testing
3920     */
3921    View() {
3922        mResources = null;
3923    }
3924
3925    public String toString() {
3926        StringBuilder out = new StringBuilder(128);
3927        out.append(getClass().getName());
3928        out.append('{');
3929        out.append(Integer.toHexString(System.identityHashCode(this)));
3930        out.append(' ');
3931        switch (mViewFlags&VISIBILITY_MASK) {
3932            case VISIBLE: out.append('V'); break;
3933            case INVISIBLE: out.append('I'); break;
3934            case GONE: out.append('G'); break;
3935            default: out.append('.'); break;
3936        }
3937        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3938        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3939        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3940        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3941        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3942        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3943        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3944        out.append(' ');
3945        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3946        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3947        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3948        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3949            out.append('p');
3950        } else {
3951            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3952        }
3953        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3954        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3955        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3956        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3957        out.append(' ');
3958        out.append(mLeft);
3959        out.append(',');
3960        out.append(mTop);
3961        out.append('-');
3962        out.append(mRight);
3963        out.append(',');
3964        out.append(mBottom);
3965        final int id = getId();
3966        if (id != NO_ID) {
3967            out.append(" #");
3968            out.append(Integer.toHexString(id));
3969            final Resources r = mResources;
3970            if (id != 0 && r != null) {
3971                try {
3972                    String pkgname;
3973                    switch (id&0xff000000) {
3974                        case 0x7f000000:
3975                            pkgname="app";
3976                            break;
3977                        case 0x01000000:
3978                            pkgname="android";
3979                            break;
3980                        default:
3981                            pkgname = r.getResourcePackageName(id);
3982                            break;
3983                    }
3984                    String typename = r.getResourceTypeName(id);
3985                    String entryname = r.getResourceEntryName(id);
3986                    out.append(" ");
3987                    out.append(pkgname);
3988                    out.append(":");
3989                    out.append(typename);
3990                    out.append("/");
3991                    out.append(entryname);
3992                } catch (Resources.NotFoundException e) {
3993                }
3994            }
3995        }
3996        out.append("}");
3997        return out.toString();
3998    }
3999
4000    /**
4001     * <p>
4002     * Initializes the fading edges from a given set of styled attributes. This
4003     * method should be called by subclasses that need fading edges and when an
4004     * instance of these subclasses is created programmatically rather than
4005     * being inflated from XML. This method is automatically called when the XML
4006     * is inflated.
4007     * </p>
4008     *
4009     * @param a the styled attributes set to initialize the fading edges from
4010     */
4011    protected void initializeFadingEdge(TypedArray a) {
4012        initScrollCache();
4013
4014        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4015                R.styleable.View_fadingEdgeLength,
4016                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4017    }
4018
4019    /**
4020     * Returns the size of the vertical faded edges used to indicate that more
4021     * content in this view is visible.
4022     *
4023     * @return The size in pixels of the vertical faded edge or 0 if vertical
4024     *         faded edges are not enabled for this view.
4025     * @attr ref android.R.styleable#View_fadingEdgeLength
4026     */
4027    public int getVerticalFadingEdgeLength() {
4028        if (isVerticalFadingEdgeEnabled()) {
4029            ScrollabilityCache cache = mScrollCache;
4030            if (cache != null) {
4031                return cache.fadingEdgeLength;
4032            }
4033        }
4034        return 0;
4035    }
4036
4037    /**
4038     * Set the size of the faded edge used to indicate that more content in this
4039     * view is available.  Will not change whether the fading edge is enabled; use
4040     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4041     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4042     * for the vertical or horizontal fading edges.
4043     *
4044     * @param length The size in pixels of the faded edge used to indicate that more
4045     *        content in this view is visible.
4046     */
4047    public void setFadingEdgeLength(int length) {
4048        initScrollCache();
4049        mScrollCache.fadingEdgeLength = length;
4050    }
4051
4052    /**
4053     * Returns the size of the horizontal faded edges used to indicate that more
4054     * content in this view is visible.
4055     *
4056     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4057     *         faded edges are not enabled for this view.
4058     * @attr ref android.R.styleable#View_fadingEdgeLength
4059     */
4060    public int getHorizontalFadingEdgeLength() {
4061        if (isHorizontalFadingEdgeEnabled()) {
4062            ScrollabilityCache cache = mScrollCache;
4063            if (cache != null) {
4064                return cache.fadingEdgeLength;
4065            }
4066        }
4067        return 0;
4068    }
4069
4070    /**
4071     * Returns the width of the vertical scrollbar.
4072     *
4073     * @return The width in pixels of the vertical scrollbar or 0 if there
4074     *         is no vertical scrollbar.
4075     */
4076    public int getVerticalScrollbarWidth() {
4077        ScrollabilityCache cache = mScrollCache;
4078        if (cache != null) {
4079            ScrollBarDrawable scrollBar = cache.scrollBar;
4080            if (scrollBar != null) {
4081                int size = scrollBar.getSize(true);
4082                if (size <= 0) {
4083                    size = cache.scrollBarSize;
4084                }
4085                return size;
4086            }
4087            return 0;
4088        }
4089        return 0;
4090    }
4091
4092    /**
4093     * Returns the height of the horizontal scrollbar.
4094     *
4095     * @return The height in pixels of the horizontal scrollbar or 0 if
4096     *         there is no horizontal scrollbar.
4097     */
4098    protected int getHorizontalScrollbarHeight() {
4099        ScrollabilityCache cache = mScrollCache;
4100        if (cache != null) {
4101            ScrollBarDrawable scrollBar = cache.scrollBar;
4102            if (scrollBar != null) {
4103                int size = scrollBar.getSize(false);
4104                if (size <= 0) {
4105                    size = cache.scrollBarSize;
4106                }
4107                return size;
4108            }
4109            return 0;
4110        }
4111        return 0;
4112    }
4113
4114    /**
4115     * <p>
4116     * Initializes the scrollbars from a given set of styled attributes. This
4117     * method should be called by subclasses that need scrollbars and when an
4118     * instance of these subclasses is created programmatically rather than
4119     * being inflated from XML. This method is automatically called when the XML
4120     * is inflated.
4121     * </p>
4122     *
4123     * @param a the styled attributes set to initialize the scrollbars from
4124     */
4125    protected void initializeScrollbars(TypedArray a) {
4126        initScrollCache();
4127
4128        final ScrollabilityCache scrollabilityCache = mScrollCache;
4129
4130        if (scrollabilityCache.scrollBar == null) {
4131            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4132        }
4133
4134        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4135
4136        if (!fadeScrollbars) {
4137            scrollabilityCache.state = ScrollabilityCache.ON;
4138        }
4139        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4140
4141
4142        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4143                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4144                        .getScrollBarFadeDuration());
4145        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4146                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4147                ViewConfiguration.getScrollDefaultDelay());
4148
4149
4150        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4151                com.android.internal.R.styleable.View_scrollbarSize,
4152                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4153
4154        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4155        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4156
4157        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4158        if (thumb != null) {
4159            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4160        }
4161
4162        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4163                false);
4164        if (alwaysDraw) {
4165            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4166        }
4167
4168        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4169        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4170
4171        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4172        if (thumb != null) {
4173            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4174        }
4175
4176        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4177                false);
4178        if (alwaysDraw) {
4179            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4180        }
4181
4182        // Apply layout direction to the new Drawables if needed
4183        final int layoutDirection = getLayoutDirection();
4184        if (track != null) {
4185            track.setLayoutDirection(layoutDirection);
4186        }
4187        if (thumb != null) {
4188            thumb.setLayoutDirection(layoutDirection);
4189        }
4190
4191        // Re-apply user/background padding so that scrollbar(s) get added
4192        resolvePadding();
4193    }
4194
4195    /**
4196     * <p>
4197     * Initalizes the scrollability cache if necessary.
4198     * </p>
4199     */
4200    private void initScrollCache() {
4201        if (mScrollCache == null) {
4202            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4203        }
4204    }
4205
4206    private ScrollabilityCache getScrollCache() {
4207        initScrollCache();
4208        return mScrollCache;
4209    }
4210
4211    /**
4212     * Set the position of the vertical scroll bar. Should be one of
4213     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4214     * {@link #SCROLLBAR_POSITION_RIGHT}.
4215     *
4216     * @param position Where the vertical scroll bar should be positioned.
4217     */
4218    public void setVerticalScrollbarPosition(int position) {
4219        if (mVerticalScrollbarPosition != position) {
4220            mVerticalScrollbarPosition = position;
4221            computeOpaqueFlags();
4222            resolvePadding();
4223        }
4224    }
4225
4226    /**
4227     * @return The position where the vertical scroll bar will show, if applicable.
4228     * @see #setVerticalScrollbarPosition(int)
4229     */
4230    public int getVerticalScrollbarPosition() {
4231        return mVerticalScrollbarPosition;
4232    }
4233
4234    ListenerInfo getListenerInfo() {
4235        if (mListenerInfo != null) {
4236            return mListenerInfo;
4237        }
4238        mListenerInfo = new ListenerInfo();
4239        return mListenerInfo;
4240    }
4241
4242    /**
4243     * Register a callback to be invoked when focus of this view changed.
4244     *
4245     * @param l The callback that will run.
4246     */
4247    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4248        getListenerInfo().mOnFocusChangeListener = l;
4249    }
4250
4251    /**
4252     * Add a listener that will be called when the bounds of the view change due to
4253     * layout processing.
4254     *
4255     * @param listener The listener that will be called when layout bounds change.
4256     */
4257    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4258        ListenerInfo li = getListenerInfo();
4259        if (li.mOnLayoutChangeListeners == null) {
4260            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4261        }
4262        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4263            li.mOnLayoutChangeListeners.add(listener);
4264        }
4265    }
4266
4267    /**
4268     * Remove a listener for layout changes.
4269     *
4270     * @param listener The listener for layout bounds change.
4271     */
4272    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4273        ListenerInfo li = mListenerInfo;
4274        if (li == null || li.mOnLayoutChangeListeners == null) {
4275            return;
4276        }
4277        li.mOnLayoutChangeListeners.remove(listener);
4278    }
4279
4280    /**
4281     * Add a listener for attach state changes.
4282     *
4283     * This listener will be called whenever this view is attached or detached
4284     * from a window. Remove the listener using
4285     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4286     *
4287     * @param listener Listener to attach
4288     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4289     */
4290    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4291        ListenerInfo li = getListenerInfo();
4292        if (li.mOnAttachStateChangeListeners == null) {
4293            li.mOnAttachStateChangeListeners
4294                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4295        }
4296        li.mOnAttachStateChangeListeners.add(listener);
4297    }
4298
4299    /**
4300     * Remove a listener for attach state changes. The listener will receive no further
4301     * notification of window attach/detach events.
4302     *
4303     * @param listener Listener to remove
4304     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4305     */
4306    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4307        ListenerInfo li = mListenerInfo;
4308        if (li == null || li.mOnAttachStateChangeListeners == null) {
4309            return;
4310        }
4311        li.mOnAttachStateChangeListeners.remove(listener);
4312    }
4313
4314    /**
4315     * Returns the focus-change callback registered for this view.
4316     *
4317     * @return The callback, or null if one is not registered.
4318     */
4319    public OnFocusChangeListener getOnFocusChangeListener() {
4320        ListenerInfo li = mListenerInfo;
4321        return li != null ? li.mOnFocusChangeListener : null;
4322    }
4323
4324    /**
4325     * Register a callback to be invoked when this view is clicked. If this view is not
4326     * clickable, it becomes clickable.
4327     *
4328     * @param l The callback that will run
4329     *
4330     * @see #setClickable(boolean)
4331     */
4332    public void setOnClickListener(OnClickListener l) {
4333        if (!isClickable()) {
4334            setClickable(true);
4335        }
4336        getListenerInfo().mOnClickListener = l;
4337    }
4338
4339    /**
4340     * Return whether this view has an attached OnClickListener.  Returns
4341     * true if there is a listener, false if there is none.
4342     */
4343    public boolean hasOnClickListeners() {
4344        ListenerInfo li = mListenerInfo;
4345        return (li != null && li.mOnClickListener != null);
4346    }
4347
4348    /**
4349     * Register a callback to be invoked when this view is clicked and held. If this view is not
4350     * long clickable, it becomes long clickable.
4351     *
4352     * @param l The callback that will run
4353     *
4354     * @see #setLongClickable(boolean)
4355     */
4356    public void setOnLongClickListener(OnLongClickListener l) {
4357        if (!isLongClickable()) {
4358            setLongClickable(true);
4359        }
4360        getListenerInfo().mOnLongClickListener = l;
4361    }
4362
4363    /**
4364     * Register a callback to be invoked when the context menu for this view is
4365     * being built. If this view is not long clickable, it becomes long clickable.
4366     *
4367     * @param l The callback that will run
4368     *
4369     */
4370    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4371        if (!isLongClickable()) {
4372            setLongClickable(true);
4373        }
4374        getListenerInfo().mOnCreateContextMenuListener = l;
4375    }
4376
4377    /**
4378     * Call this view's OnClickListener, if it is defined.  Performs all normal
4379     * actions associated with clicking: reporting accessibility event, playing
4380     * a sound, etc.
4381     *
4382     * @return True there was an assigned OnClickListener that was called, false
4383     *         otherwise is returned.
4384     */
4385    public boolean performClick() {
4386        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4387
4388        ListenerInfo li = mListenerInfo;
4389        if (li != null && li.mOnClickListener != null) {
4390            playSoundEffect(SoundEffectConstants.CLICK);
4391            li.mOnClickListener.onClick(this);
4392            return true;
4393        }
4394
4395        return false;
4396    }
4397
4398    /**
4399     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4400     * this only calls the listener, and does not do any associated clicking
4401     * actions like reporting an accessibility event.
4402     *
4403     * @return True there was an assigned OnClickListener that was called, false
4404     *         otherwise is returned.
4405     */
4406    public boolean callOnClick() {
4407        ListenerInfo li = mListenerInfo;
4408        if (li != null && li.mOnClickListener != null) {
4409            li.mOnClickListener.onClick(this);
4410            return true;
4411        }
4412        return false;
4413    }
4414
4415    /**
4416     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4417     * OnLongClickListener did not consume the event.
4418     *
4419     * @return True if one of the above receivers consumed the event, false otherwise.
4420     */
4421    public boolean performLongClick() {
4422        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4423
4424        boolean handled = false;
4425        ListenerInfo li = mListenerInfo;
4426        if (li != null && li.mOnLongClickListener != null) {
4427            handled = li.mOnLongClickListener.onLongClick(View.this);
4428        }
4429        if (!handled) {
4430            handled = showContextMenu();
4431        }
4432        if (handled) {
4433            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4434        }
4435        return handled;
4436    }
4437
4438    /**
4439     * Performs button-related actions during a touch down event.
4440     *
4441     * @param event The event.
4442     * @return True if the down was consumed.
4443     *
4444     * @hide
4445     */
4446    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4447        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4448            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4449                return true;
4450            }
4451        }
4452        return false;
4453    }
4454
4455    /**
4456     * Bring up the context menu for this view.
4457     *
4458     * @return Whether a context menu was displayed.
4459     */
4460    public boolean showContextMenu() {
4461        return getParent().showContextMenuForChild(this);
4462    }
4463
4464    /**
4465     * Bring up the context menu for this view, referring to the item under the specified point.
4466     *
4467     * @param x The referenced x coordinate.
4468     * @param y The referenced y coordinate.
4469     * @param metaState The keyboard modifiers that were pressed.
4470     * @return Whether a context menu was displayed.
4471     *
4472     * @hide
4473     */
4474    public boolean showContextMenu(float x, float y, int metaState) {
4475        return showContextMenu();
4476    }
4477
4478    /**
4479     * Start an action mode.
4480     *
4481     * @param callback Callback that will control the lifecycle of the action mode
4482     * @return The new action mode if it is started, null otherwise
4483     *
4484     * @see ActionMode
4485     */
4486    public ActionMode startActionMode(ActionMode.Callback callback) {
4487        ViewParent parent = getParent();
4488        if (parent == null) return null;
4489        return parent.startActionModeForChild(this, callback);
4490    }
4491
4492    /**
4493     * Register a callback to be invoked when a hardware key is pressed in this view.
4494     * Key presses in software input methods will generally not trigger the methods of
4495     * this listener.
4496     * @param l the key listener to attach to this view
4497     */
4498    public void setOnKeyListener(OnKeyListener l) {
4499        getListenerInfo().mOnKeyListener = l;
4500    }
4501
4502    /**
4503     * Register a callback to be invoked when a touch event is sent to this view.
4504     * @param l the touch listener to attach to this view
4505     */
4506    public void setOnTouchListener(OnTouchListener l) {
4507        getListenerInfo().mOnTouchListener = l;
4508    }
4509
4510    /**
4511     * Register a callback to be invoked when a generic motion event is sent to this view.
4512     * @param l the generic motion listener to attach to this view
4513     */
4514    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4515        getListenerInfo().mOnGenericMotionListener = l;
4516    }
4517
4518    /**
4519     * Register a callback to be invoked when a hover event is sent to this view.
4520     * @param l the hover listener to attach to this view
4521     */
4522    public void setOnHoverListener(OnHoverListener l) {
4523        getListenerInfo().mOnHoverListener = l;
4524    }
4525
4526    /**
4527     * Register a drag event listener callback object for this View. The parameter is
4528     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4529     * View, the system calls the
4530     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4531     * @param l An implementation of {@link android.view.View.OnDragListener}.
4532     */
4533    public void setOnDragListener(OnDragListener l) {
4534        getListenerInfo().mOnDragListener = l;
4535    }
4536
4537    /**
4538     * Give this view focus. This will cause
4539     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4540     *
4541     * Note: this does not check whether this {@link View} should get focus, it just
4542     * gives it focus no matter what.  It should only be called internally by framework
4543     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4544     *
4545     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4546     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4547     *        focus moved when requestFocus() is called. It may not always
4548     *        apply, in which case use the default View.FOCUS_DOWN.
4549     * @param previouslyFocusedRect The rectangle of the view that had focus
4550     *        prior in this View's coordinate system.
4551     */
4552    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4553        if (DBG) {
4554            System.out.println(this + " requestFocus()");
4555        }
4556
4557        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4558            mPrivateFlags |= PFLAG_FOCUSED;
4559
4560            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4561
4562            if (mParent != null) {
4563                mParent.requestChildFocus(this, this);
4564            }
4565
4566            if (mAttachInfo != null) {
4567                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4568            }
4569
4570            onFocusChanged(true, direction, previouslyFocusedRect);
4571            refreshDrawableState();
4572        }
4573    }
4574
4575    /**
4576     * Request that a rectangle of this view be visible on the screen,
4577     * scrolling if necessary just enough.
4578     *
4579     * <p>A View should call this if it maintains some notion of which part
4580     * of its content is interesting.  For example, a text editing view
4581     * should call this when its cursor moves.
4582     *
4583     * @param rectangle The rectangle.
4584     * @return Whether any parent scrolled.
4585     */
4586    public boolean requestRectangleOnScreen(Rect rectangle) {
4587        return requestRectangleOnScreen(rectangle, false);
4588    }
4589
4590    /**
4591     * Request that a rectangle of this view be visible on the screen,
4592     * scrolling if necessary just enough.
4593     *
4594     * <p>A View should call this if it maintains some notion of which part
4595     * of its content is interesting.  For example, a text editing view
4596     * should call this when its cursor moves.
4597     *
4598     * <p>When <code>immediate</code> is set to true, scrolling will not be
4599     * animated.
4600     *
4601     * @param rectangle The rectangle.
4602     * @param immediate True to forbid animated scrolling, false otherwise
4603     * @return Whether any parent scrolled.
4604     */
4605    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4606        if (mParent == null) {
4607            return false;
4608        }
4609
4610        View child = this;
4611
4612        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4613        position.set(rectangle);
4614
4615        ViewParent parent = mParent;
4616        boolean scrolled = false;
4617        while (parent != null) {
4618            rectangle.set((int) position.left, (int) position.top,
4619                    (int) position.right, (int) position.bottom);
4620
4621            scrolled |= parent.requestChildRectangleOnScreen(child,
4622                    rectangle, immediate);
4623
4624            if (!child.hasIdentityMatrix()) {
4625                child.getMatrix().mapRect(position);
4626            }
4627
4628            position.offset(child.mLeft, child.mTop);
4629
4630            if (!(parent instanceof View)) {
4631                break;
4632            }
4633
4634            View parentView = (View) parent;
4635
4636            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4637
4638            child = parentView;
4639            parent = child.getParent();
4640        }
4641
4642        return scrolled;
4643    }
4644
4645    /**
4646     * Called when this view wants to give up focus. If focus is cleared
4647     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4648     * <p>
4649     * <strong>Note:</strong> When a View clears focus the framework is trying
4650     * to give focus to the first focusable View from the top. Hence, if this
4651     * View is the first from the top that can take focus, then all callbacks
4652     * related to clearing focus will be invoked after wich the framework will
4653     * give focus to this view.
4654     * </p>
4655     */
4656    public void clearFocus() {
4657        if (DBG) {
4658            System.out.println(this + " clearFocus()");
4659        }
4660
4661        clearFocusInternal(true, true);
4662    }
4663
4664    /**
4665     * Clears focus from the view, optionally propagating the change up through
4666     * the parent hierarchy and requesting that the root view place new focus.
4667     *
4668     * @param propagate whether to propagate the change up through the parent
4669     *            hierarchy
4670     * @param refocus when propagate is true, specifies whether to request the
4671     *            root view place new focus
4672     */
4673    void clearFocusInternal(boolean propagate, boolean refocus) {
4674        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4675            mPrivateFlags &= ~PFLAG_FOCUSED;
4676
4677            if (propagate && mParent != null) {
4678                mParent.clearChildFocus(this);
4679            }
4680
4681            onFocusChanged(false, 0, null);
4682
4683            refreshDrawableState();
4684
4685            if (propagate && (!refocus || !rootViewRequestFocus())) {
4686                notifyGlobalFocusCleared(this);
4687            }
4688        }
4689    }
4690
4691    void notifyGlobalFocusCleared(View oldFocus) {
4692        if (oldFocus != null && mAttachInfo != null) {
4693            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4694        }
4695    }
4696
4697    boolean rootViewRequestFocus() {
4698        final View root = getRootView();
4699        return root != null && root.requestFocus();
4700    }
4701
4702    /**
4703     * Called internally by the view system when a new view is getting focus.
4704     * This is what clears the old focus.
4705     * <p>
4706     * <b>NOTE:</b> The parent view's focused child must be updated manually
4707     * after calling this method. Otherwise, the view hierarchy may be left in
4708     * an inconstent state.
4709     */
4710    void unFocus() {
4711        if (DBG) {
4712            System.out.println(this + " unFocus()");
4713        }
4714
4715        clearFocusInternal(false, false);
4716    }
4717
4718    /**
4719     * Returns true if this view has focus iteself, or is the ancestor of the
4720     * view that has focus.
4721     *
4722     * @return True if this view has or contains focus, false otherwise.
4723     */
4724    @ViewDebug.ExportedProperty(category = "focus")
4725    public boolean hasFocus() {
4726        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4727    }
4728
4729    /**
4730     * Returns true if this view is focusable or if it contains a reachable View
4731     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4732     * is a View whose parents do not block descendants focus.
4733     *
4734     * Only {@link #VISIBLE} views are considered focusable.
4735     *
4736     * @return True if the view is focusable or if the view contains a focusable
4737     *         View, false otherwise.
4738     *
4739     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4740     */
4741    public boolean hasFocusable() {
4742        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4743    }
4744
4745    /**
4746     * Called by the view system when the focus state of this view changes.
4747     * When the focus change event is caused by directional navigation, direction
4748     * and previouslyFocusedRect provide insight into where the focus is coming from.
4749     * When overriding, be sure to call up through to the super class so that
4750     * the standard focus handling will occur.
4751     *
4752     * @param gainFocus True if the View has focus; false otherwise.
4753     * @param direction The direction focus has moved when requestFocus()
4754     *                  is called to give this view focus. Values are
4755     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4756     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4757     *                  It may not always apply, in which case use the default.
4758     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4759     *        system, of the previously focused view.  If applicable, this will be
4760     *        passed in as finer grained information about where the focus is coming
4761     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4762     */
4763    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4764        if (gainFocus) {
4765            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4766        } else {
4767            notifyViewAccessibilityStateChangedIfNeeded(
4768                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
4769        }
4770
4771        InputMethodManager imm = InputMethodManager.peekInstance();
4772        if (!gainFocus) {
4773            if (isPressed()) {
4774                setPressed(false);
4775            }
4776            if (imm != null && mAttachInfo != null
4777                    && mAttachInfo.mHasWindowFocus) {
4778                imm.focusOut(this);
4779            }
4780            onFocusLost();
4781        } else if (imm != null && mAttachInfo != null
4782                && mAttachInfo.mHasWindowFocus) {
4783            imm.focusIn(this);
4784        }
4785
4786        invalidate(true);
4787        ListenerInfo li = mListenerInfo;
4788        if (li != null && li.mOnFocusChangeListener != null) {
4789            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4790        }
4791
4792        if (mAttachInfo != null) {
4793            mAttachInfo.mKeyDispatchState.reset(this);
4794        }
4795    }
4796
4797    /**
4798     * Sends an accessibility event of the given type. If accessibility is
4799     * not enabled this method has no effect. The default implementation calls
4800     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4801     * to populate information about the event source (this View), then calls
4802     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4803     * populate the text content of the event source including its descendants,
4804     * and last calls
4805     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4806     * on its parent to resuest sending of the event to interested parties.
4807     * <p>
4808     * If an {@link AccessibilityDelegate} has been specified via calling
4809     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4810     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4811     * responsible for handling this call.
4812     * </p>
4813     *
4814     * @param eventType The type of the event to send, as defined by several types from
4815     * {@link android.view.accessibility.AccessibilityEvent}, such as
4816     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4817     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4818     *
4819     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4820     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4821     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4822     * @see AccessibilityDelegate
4823     */
4824    public void sendAccessibilityEvent(int eventType) {
4825        // Excluded views do not send accessibility events.
4826        if (!includeForAccessibility()) {
4827            return;
4828        }
4829        if (mAccessibilityDelegate != null) {
4830            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4831        } else {
4832            sendAccessibilityEventInternal(eventType);
4833        }
4834    }
4835
4836    /**
4837     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4838     * {@link AccessibilityEvent} to make an announcement which is related to some
4839     * sort of a context change for which none of the events representing UI transitions
4840     * is a good fit. For example, announcing a new page in a book. If accessibility
4841     * is not enabled this method does nothing.
4842     *
4843     * @param text The announcement text.
4844     */
4845    public void announceForAccessibility(CharSequence text) {
4846        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4847            AccessibilityEvent event = AccessibilityEvent.obtain(
4848                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4849            onInitializeAccessibilityEvent(event);
4850            event.getText().add(text);
4851            event.setContentDescription(null);
4852            mParent.requestSendAccessibilityEvent(this, event);
4853        }
4854    }
4855
4856    /**
4857     * @see #sendAccessibilityEvent(int)
4858     *
4859     * Note: Called from the default {@link AccessibilityDelegate}.
4860     */
4861    void sendAccessibilityEventInternal(int eventType) {
4862        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4863            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4864        }
4865    }
4866
4867    /**
4868     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4869     * takes as an argument an empty {@link AccessibilityEvent} and does not
4870     * perform a check whether accessibility is enabled.
4871     * <p>
4872     * If an {@link AccessibilityDelegate} has been specified via calling
4873     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4874     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4875     * is responsible for handling this call.
4876     * </p>
4877     *
4878     * @param event The event to send.
4879     *
4880     * @see #sendAccessibilityEvent(int)
4881     */
4882    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4883        if (mAccessibilityDelegate != null) {
4884            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4885        } else {
4886            sendAccessibilityEventUncheckedInternal(event);
4887        }
4888    }
4889
4890    /**
4891     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4892     *
4893     * Note: Called from the default {@link AccessibilityDelegate}.
4894     */
4895    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4896        if (!isShown()) {
4897            return;
4898        }
4899        onInitializeAccessibilityEvent(event);
4900        // Only a subset of accessibility events populates text content.
4901        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4902            dispatchPopulateAccessibilityEvent(event);
4903        }
4904        // In the beginning we called #isShown(), so we know that getParent() is not null.
4905        getParent().requestSendAccessibilityEvent(this, event);
4906    }
4907
4908    /**
4909     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4910     * to its children for adding their text content to the event. Note that the
4911     * event text is populated in a separate dispatch path since we add to the
4912     * event not only the text of the source but also the text of all its descendants.
4913     * A typical implementation will call
4914     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4915     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4916     * on each child. Override this method if custom population of the event text
4917     * content is required.
4918     * <p>
4919     * If an {@link AccessibilityDelegate} has been specified via calling
4920     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4921     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4922     * is responsible for handling this call.
4923     * </p>
4924     * <p>
4925     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4926     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4927     * </p>
4928     *
4929     * @param event The event.
4930     *
4931     * @return True if the event population was completed.
4932     */
4933    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4934        if (mAccessibilityDelegate != null) {
4935            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4936        } else {
4937            return dispatchPopulateAccessibilityEventInternal(event);
4938        }
4939    }
4940
4941    /**
4942     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4943     *
4944     * Note: Called from the default {@link AccessibilityDelegate}.
4945     */
4946    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4947        onPopulateAccessibilityEvent(event);
4948        return false;
4949    }
4950
4951    /**
4952     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4953     * giving a chance to this View to populate the accessibility event with its
4954     * text content. While this method is free to modify event
4955     * attributes other than text content, doing so should normally be performed in
4956     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4957     * <p>
4958     * Example: Adding formatted date string to an accessibility event in addition
4959     *          to the text added by the super implementation:
4960     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4961     *     super.onPopulateAccessibilityEvent(event);
4962     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4963     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4964     *         mCurrentDate.getTimeInMillis(), flags);
4965     *     event.getText().add(selectedDateUtterance);
4966     * }</pre>
4967     * <p>
4968     * If an {@link AccessibilityDelegate} has been specified via calling
4969     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4970     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4971     * is responsible for handling this call.
4972     * </p>
4973     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4974     * information to the event, in case the default implementation has basic information to add.
4975     * </p>
4976     *
4977     * @param event The accessibility event which to populate.
4978     *
4979     * @see #sendAccessibilityEvent(int)
4980     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4981     */
4982    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4983        if (mAccessibilityDelegate != null) {
4984            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4985        } else {
4986            onPopulateAccessibilityEventInternal(event);
4987        }
4988    }
4989
4990    /**
4991     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4992     *
4993     * Note: Called from the default {@link AccessibilityDelegate}.
4994     */
4995    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4996    }
4997
4998    /**
4999     * Initializes an {@link AccessibilityEvent} with information about
5000     * this View which is the event source. In other words, the source of
5001     * an accessibility event is the view whose state change triggered firing
5002     * the event.
5003     * <p>
5004     * Example: Setting the password property of an event in addition
5005     *          to properties set by the super implementation:
5006     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5007     *     super.onInitializeAccessibilityEvent(event);
5008     *     event.setPassword(true);
5009     * }</pre>
5010     * <p>
5011     * If an {@link AccessibilityDelegate} has been specified via calling
5012     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5013     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5014     * is responsible for handling this call.
5015     * </p>
5016     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5017     * information to the event, in case the default implementation has basic information to add.
5018     * </p>
5019     * @param event The event to initialize.
5020     *
5021     * @see #sendAccessibilityEvent(int)
5022     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5023     */
5024    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5025        if (mAccessibilityDelegate != null) {
5026            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5027        } else {
5028            onInitializeAccessibilityEventInternal(event);
5029        }
5030    }
5031
5032    /**
5033     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5034     *
5035     * Note: Called from the default {@link AccessibilityDelegate}.
5036     */
5037    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5038        event.setSource(this);
5039        event.setClassName(View.class.getName());
5040        event.setPackageName(getContext().getPackageName());
5041        event.setEnabled(isEnabled());
5042        event.setContentDescription(mContentDescription);
5043
5044        switch (event.getEventType()) {
5045            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5046                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5047                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5048                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5049                event.setItemCount(focusablesTempList.size());
5050                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5051                if (mAttachInfo != null) {
5052                    focusablesTempList.clear();
5053                }
5054            } break;
5055            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5056                CharSequence text = getIterableTextForAccessibility();
5057                if (text != null && text.length() > 0) {
5058                    event.setFromIndex(getAccessibilitySelectionStart());
5059                    event.setToIndex(getAccessibilitySelectionEnd());
5060                    event.setItemCount(text.length());
5061                }
5062            } break;
5063        }
5064    }
5065
5066    /**
5067     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5068     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5069     * This method is responsible for obtaining an accessibility node info from a
5070     * pool of reusable instances and calling
5071     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5072     * initialize the former.
5073     * <p>
5074     * Note: The client is responsible for recycling the obtained instance by calling
5075     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5076     * </p>
5077     *
5078     * @return A populated {@link AccessibilityNodeInfo}.
5079     *
5080     * @see AccessibilityNodeInfo
5081     */
5082    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5083        if (mAccessibilityDelegate != null) {
5084            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5085        } else {
5086            return createAccessibilityNodeInfoInternal();
5087        }
5088    }
5089
5090    /**
5091     * @see #createAccessibilityNodeInfo()
5092     */
5093    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5094        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5095        if (provider != null) {
5096            return provider.createAccessibilityNodeInfo(View.NO_ID);
5097        } else {
5098            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5099            onInitializeAccessibilityNodeInfo(info);
5100            return info;
5101        }
5102    }
5103
5104    /**
5105     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5106     * The base implementation sets:
5107     * <ul>
5108     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5109     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5110     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5111     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5112     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5113     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5114     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5115     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5116     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5117     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5118     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5119     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5120     * </ul>
5121     * <p>
5122     * Subclasses should override this method, call the super implementation,
5123     * and set additional attributes.
5124     * </p>
5125     * <p>
5126     * If an {@link AccessibilityDelegate} has been specified via calling
5127     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5128     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5129     * is responsible for handling this call.
5130     * </p>
5131     *
5132     * @param info The instance to initialize.
5133     */
5134    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5135        if (mAccessibilityDelegate != null) {
5136            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5137        } else {
5138            onInitializeAccessibilityNodeInfoInternal(info);
5139        }
5140    }
5141
5142    /**
5143     * Gets the location of this view in screen coordintates.
5144     *
5145     * @param outRect The output location
5146     */
5147    void getBoundsOnScreen(Rect outRect) {
5148        if (mAttachInfo == null) {
5149            return;
5150        }
5151
5152        RectF position = mAttachInfo.mTmpTransformRect;
5153        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5154
5155        if (!hasIdentityMatrix()) {
5156            getMatrix().mapRect(position);
5157        }
5158
5159        position.offset(mLeft, mTop);
5160
5161        ViewParent parent = mParent;
5162        while (parent instanceof View) {
5163            View parentView = (View) parent;
5164
5165            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5166
5167            if (!parentView.hasIdentityMatrix()) {
5168                parentView.getMatrix().mapRect(position);
5169            }
5170
5171            position.offset(parentView.mLeft, parentView.mTop);
5172
5173            parent = parentView.mParent;
5174        }
5175
5176        if (parent instanceof ViewRootImpl) {
5177            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5178            position.offset(0, -viewRootImpl.mCurScrollY);
5179        }
5180
5181        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5182
5183        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5184                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5185    }
5186
5187    /**
5188     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5189     *
5190     * Note: Called from the default {@link AccessibilityDelegate}.
5191     */
5192    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5193        Rect bounds = mAttachInfo.mTmpInvalRect;
5194
5195        getDrawingRect(bounds);
5196        info.setBoundsInParent(bounds);
5197
5198        getBoundsOnScreen(bounds);
5199        info.setBoundsInScreen(bounds);
5200
5201        ViewParent parent = getParentForAccessibility();
5202        if (parent instanceof View) {
5203            info.setParent((View) parent);
5204        }
5205
5206        if (mID != View.NO_ID) {
5207            View rootView = getRootView();
5208            if (rootView == null) {
5209                rootView = this;
5210            }
5211            View label = rootView.findLabelForView(this, mID);
5212            if (label != null) {
5213                info.setLabeledBy(label);
5214            }
5215
5216            if ((mAttachInfo.mAccessibilityFetchFlags
5217                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5218                    && Resources.resourceHasPackage(mID)) {
5219                try {
5220                    String viewId = getResources().getResourceName(mID);
5221                    info.setViewIdResourceName(viewId);
5222                } catch (Resources.NotFoundException nfe) {
5223                    /* ignore */
5224                }
5225            }
5226        }
5227
5228        if (mLabelForId != View.NO_ID) {
5229            View rootView = getRootView();
5230            if (rootView == null) {
5231                rootView = this;
5232            }
5233            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5234            if (labeled != null) {
5235                info.setLabelFor(labeled);
5236            }
5237        }
5238
5239        info.setVisibleToUser(isVisibleToUser());
5240
5241        info.setPackageName(mContext.getPackageName());
5242        info.setClassName(View.class.getName());
5243        info.setContentDescription(getContentDescription());
5244
5245        info.setEnabled(isEnabled());
5246        info.setClickable(isClickable());
5247        info.setFocusable(isFocusable());
5248        info.setFocused(isFocused());
5249        info.setAccessibilityFocused(isAccessibilityFocused());
5250        info.setSelected(isSelected());
5251        info.setLongClickable(isLongClickable());
5252        info.setLiveRegion(getAccessibilityLiveRegion());
5253
5254        // TODO: These make sense only if we are in an AdapterView but all
5255        // views can be selected. Maybe from accessibility perspective
5256        // we should report as selectable view in an AdapterView.
5257        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5258        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5259
5260        if (isFocusable()) {
5261            if (isFocused()) {
5262                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5263            } else {
5264                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5265            }
5266        }
5267
5268        if (!isAccessibilityFocused()) {
5269            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5270        } else {
5271            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5272        }
5273
5274        if (isClickable() && isEnabled()) {
5275            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5276        }
5277
5278        if (isLongClickable() && isEnabled()) {
5279            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5280        }
5281
5282        CharSequence text = getIterableTextForAccessibility();
5283        if (text != null && text.length() > 0) {
5284            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5285
5286            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5287            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5288            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5289            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5290                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5291                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5292        }
5293    }
5294
5295    private View findLabelForView(View view, int labeledId) {
5296        if (mMatchLabelForPredicate == null) {
5297            mMatchLabelForPredicate = new MatchLabelForPredicate();
5298        }
5299        mMatchLabelForPredicate.mLabeledId = labeledId;
5300        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5301    }
5302
5303    /**
5304     * Computes whether this view is visible to the user. Such a view is
5305     * attached, visible, all its predecessors are visible, it is not clipped
5306     * entirely by its predecessors, and has an alpha greater than zero.
5307     *
5308     * @return Whether the view is visible on the screen.
5309     *
5310     * @hide
5311     */
5312    protected boolean isVisibleToUser() {
5313        return isVisibleToUser(null);
5314    }
5315
5316    /**
5317     * Computes whether the given portion of this view is visible to the user.
5318     * Such a view is attached, visible, all its predecessors are visible,
5319     * has an alpha greater than zero, and the specified portion is not
5320     * clipped entirely by its predecessors.
5321     *
5322     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5323     *                    <code>null</code>, and the entire view will be tested in this case.
5324     *                    When <code>true</code> is returned by the function, the actual visible
5325     *                    region will be stored in this parameter; that is, if boundInView is fully
5326     *                    contained within the view, no modification will be made, otherwise regions
5327     *                    outside of the visible area of the view will be clipped.
5328     *
5329     * @return Whether the specified portion of the view is visible on the screen.
5330     *
5331     * @hide
5332     */
5333    protected boolean isVisibleToUser(Rect boundInView) {
5334        if (mAttachInfo != null) {
5335            // Attached to invisible window means this view is not visible.
5336            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5337                return false;
5338            }
5339            // An invisible predecessor or one with alpha zero means
5340            // that this view is not visible to the user.
5341            Object current = this;
5342            while (current instanceof View) {
5343                View view = (View) current;
5344                // We have attach info so this view is attached and there is no
5345                // need to check whether we reach to ViewRootImpl on the way up.
5346                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5347                        view.getVisibility() != VISIBLE) {
5348                    return false;
5349                }
5350                current = view.mParent;
5351            }
5352            // Check if the view is entirely covered by its predecessors.
5353            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5354            Point offset = mAttachInfo.mPoint;
5355            if (!getGlobalVisibleRect(visibleRect, offset)) {
5356                return false;
5357            }
5358            // Check if the visible portion intersects the rectangle of interest.
5359            if (boundInView != null) {
5360                visibleRect.offset(-offset.x, -offset.y);
5361                return boundInView.intersect(visibleRect);
5362            }
5363            return true;
5364        }
5365        return false;
5366    }
5367
5368    /**
5369     * Returns the delegate for implementing accessibility support via
5370     * composition. For more details see {@link AccessibilityDelegate}.
5371     *
5372     * @return The delegate, or null if none set.
5373     *
5374     * @hide
5375     */
5376    public AccessibilityDelegate getAccessibilityDelegate() {
5377        return mAccessibilityDelegate;
5378    }
5379
5380    /**
5381     * Sets a delegate for implementing accessibility support via composition as
5382     * opposed to inheritance. The delegate's primary use is for implementing
5383     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5384     *
5385     * @param delegate The delegate instance.
5386     *
5387     * @see AccessibilityDelegate
5388     */
5389    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5390        mAccessibilityDelegate = delegate;
5391    }
5392
5393    /**
5394     * Gets the provider for managing a virtual view hierarchy rooted at this View
5395     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5396     * that explore the window content.
5397     * <p>
5398     * If this method returns an instance, this instance is responsible for managing
5399     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5400     * View including the one representing the View itself. Similarly the returned
5401     * instance is responsible for performing accessibility actions on any virtual
5402     * view or the root view itself.
5403     * </p>
5404     * <p>
5405     * If an {@link AccessibilityDelegate} has been specified via calling
5406     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5407     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5408     * is responsible for handling this call.
5409     * </p>
5410     *
5411     * @return The provider.
5412     *
5413     * @see AccessibilityNodeProvider
5414     */
5415    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5416        if (mAccessibilityDelegate != null) {
5417            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5418        } else {
5419            return null;
5420        }
5421    }
5422
5423    /**
5424     * Gets the unique identifier of this view on the screen for accessibility purposes.
5425     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5426     *
5427     * @return The view accessibility id.
5428     *
5429     * @hide
5430     */
5431    public int getAccessibilityViewId() {
5432        if (mAccessibilityViewId == NO_ID) {
5433            mAccessibilityViewId = sNextAccessibilityViewId++;
5434        }
5435        return mAccessibilityViewId;
5436    }
5437
5438    /**
5439     * Gets the unique identifier of the window in which this View reseides.
5440     *
5441     * @return The window accessibility id.
5442     *
5443     * @hide
5444     */
5445    public int getAccessibilityWindowId() {
5446        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5447    }
5448
5449    /**
5450     * Gets the {@link View} description. It briefly describes the view and is
5451     * primarily used for accessibility support. Set this property to enable
5452     * better accessibility support for your application. This is especially
5453     * true for views that do not have textual representation (For example,
5454     * ImageButton).
5455     *
5456     * @return The content description.
5457     *
5458     * @attr ref android.R.styleable#View_contentDescription
5459     */
5460    @ViewDebug.ExportedProperty(category = "accessibility")
5461    public CharSequence getContentDescription() {
5462        return mContentDescription;
5463    }
5464
5465    /**
5466     * Sets the {@link View} description. It briefly describes the view and is
5467     * primarily used for accessibility support. Set this property to enable
5468     * better accessibility support for your application. This is especially
5469     * true for views that do not have textual representation (For example,
5470     * ImageButton).
5471     *
5472     * @param contentDescription The content description.
5473     *
5474     * @attr ref android.R.styleable#View_contentDescription
5475     */
5476    @RemotableViewMethod
5477    public void setContentDescription(CharSequence contentDescription) {
5478        if (mContentDescription == null) {
5479            if (contentDescription == null) {
5480                return;
5481            }
5482        } else if (mContentDescription.equals(contentDescription)) {
5483            return;
5484        }
5485        mContentDescription = contentDescription;
5486        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5487        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5488            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5489            notifySubtreeAccessibilityStateChangedIfNeeded();
5490        } else {
5491            notifyViewAccessibilityStateChangedIfNeeded(
5492                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5493        }
5494    }
5495
5496    /**
5497     * Gets the id of a view for which this view serves as a label for
5498     * accessibility purposes.
5499     *
5500     * @return The labeled view id.
5501     */
5502    @ViewDebug.ExportedProperty(category = "accessibility")
5503    public int getLabelFor() {
5504        return mLabelForId;
5505    }
5506
5507    /**
5508     * Sets the id of a view for which this view serves as a label for
5509     * accessibility purposes.
5510     *
5511     * @param id The labeled view id.
5512     */
5513    @RemotableViewMethod
5514    public void setLabelFor(int id) {
5515        mLabelForId = id;
5516        if (mLabelForId != View.NO_ID
5517                && mID == View.NO_ID) {
5518            mID = generateViewId();
5519        }
5520    }
5521
5522    /**
5523     * Invoked whenever this view loses focus, either by losing window focus or by losing
5524     * focus within its window. This method can be used to clear any state tied to the
5525     * focus. For instance, if a button is held pressed with the trackball and the window
5526     * loses focus, this method can be used to cancel the press.
5527     *
5528     * Subclasses of View overriding this method should always call super.onFocusLost().
5529     *
5530     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5531     * @see #onWindowFocusChanged(boolean)
5532     *
5533     * @hide pending API council approval
5534     */
5535    protected void onFocusLost() {
5536        resetPressedState();
5537    }
5538
5539    private void resetPressedState() {
5540        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5541            return;
5542        }
5543
5544        if (isPressed()) {
5545            setPressed(false);
5546
5547            if (!mHasPerformedLongPress) {
5548                removeLongPressCallback();
5549            }
5550        }
5551    }
5552
5553    /**
5554     * Returns true if this view has focus
5555     *
5556     * @return True if this view has focus, false otherwise.
5557     */
5558    @ViewDebug.ExportedProperty(category = "focus")
5559    public boolean isFocused() {
5560        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5561    }
5562
5563    /**
5564     * Find the view in the hierarchy rooted at this view that currently has
5565     * focus.
5566     *
5567     * @return The view that currently has focus, or null if no focused view can
5568     *         be found.
5569     */
5570    public View findFocus() {
5571        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5572    }
5573
5574    /**
5575     * Indicates whether this view is one of the set of scrollable containers in
5576     * its window.
5577     *
5578     * @return whether this view is one of the set of scrollable containers in
5579     * its window
5580     *
5581     * @attr ref android.R.styleable#View_isScrollContainer
5582     */
5583    public boolean isScrollContainer() {
5584        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5585    }
5586
5587    /**
5588     * Change whether this view is one of the set of scrollable containers in
5589     * its window.  This will be used to determine whether the window can
5590     * resize or must pan when a soft input area is open -- scrollable
5591     * containers allow the window to use resize mode since the container
5592     * will appropriately shrink.
5593     *
5594     * @attr ref android.R.styleable#View_isScrollContainer
5595     */
5596    public void setScrollContainer(boolean isScrollContainer) {
5597        if (isScrollContainer) {
5598            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5599                mAttachInfo.mScrollContainers.add(this);
5600                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5601            }
5602            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5603        } else {
5604            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5605                mAttachInfo.mScrollContainers.remove(this);
5606            }
5607            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5608        }
5609    }
5610
5611    /**
5612     * Returns the quality of the drawing cache.
5613     *
5614     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5615     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5616     *
5617     * @see #setDrawingCacheQuality(int)
5618     * @see #setDrawingCacheEnabled(boolean)
5619     * @see #isDrawingCacheEnabled()
5620     *
5621     * @attr ref android.R.styleable#View_drawingCacheQuality
5622     */
5623    public int getDrawingCacheQuality() {
5624        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5625    }
5626
5627    /**
5628     * Set the drawing cache quality of this view. This value is used only when the
5629     * drawing cache is enabled
5630     *
5631     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5632     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5633     *
5634     * @see #getDrawingCacheQuality()
5635     * @see #setDrawingCacheEnabled(boolean)
5636     * @see #isDrawingCacheEnabled()
5637     *
5638     * @attr ref android.R.styleable#View_drawingCacheQuality
5639     */
5640    public void setDrawingCacheQuality(int quality) {
5641        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5642    }
5643
5644    /**
5645     * Returns whether the screen should remain on, corresponding to the current
5646     * value of {@link #KEEP_SCREEN_ON}.
5647     *
5648     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5649     *
5650     * @see #setKeepScreenOn(boolean)
5651     *
5652     * @attr ref android.R.styleable#View_keepScreenOn
5653     */
5654    public boolean getKeepScreenOn() {
5655        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5656    }
5657
5658    /**
5659     * Controls whether the screen should remain on, modifying the
5660     * value of {@link #KEEP_SCREEN_ON}.
5661     *
5662     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5663     *
5664     * @see #getKeepScreenOn()
5665     *
5666     * @attr ref android.R.styleable#View_keepScreenOn
5667     */
5668    public void setKeepScreenOn(boolean keepScreenOn) {
5669        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5670    }
5671
5672    /**
5673     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5674     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5675     *
5676     * @attr ref android.R.styleable#View_nextFocusLeft
5677     */
5678    public int getNextFocusLeftId() {
5679        return mNextFocusLeftId;
5680    }
5681
5682    /**
5683     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5684     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5685     * decide automatically.
5686     *
5687     * @attr ref android.R.styleable#View_nextFocusLeft
5688     */
5689    public void setNextFocusLeftId(int nextFocusLeftId) {
5690        mNextFocusLeftId = nextFocusLeftId;
5691    }
5692
5693    /**
5694     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5695     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5696     *
5697     * @attr ref android.R.styleable#View_nextFocusRight
5698     */
5699    public int getNextFocusRightId() {
5700        return mNextFocusRightId;
5701    }
5702
5703    /**
5704     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5705     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5706     * decide automatically.
5707     *
5708     * @attr ref android.R.styleable#View_nextFocusRight
5709     */
5710    public void setNextFocusRightId(int nextFocusRightId) {
5711        mNextFocusRightId = nextFocusRightId;
5712    }
5713
5714    /**
5715     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5716     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5717     *
5718     * @attr ref android.R.styleable#View_nextFocusUp
5719     */
5720    public int getNextFocusUpId() {
5721        return mNextFocusUpId;
5722    }
5723
5724    /**
5725     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5726     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5727     * decide automatically.
5728     *
5729     * @attr ref android.R.styleable#View_nextFocusUp
5730     */
5731    public void setNextFocusUpId(int nextFocusUpId) {
5732        mNextFocusUpId = nextFocusUpId;
5733    }
5734
5735    /**
5736     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5737     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5738     *
5739     * @attr ref android.R.styleable#View_nextFocusDown
5740     */
5741    public int getNextFocusDownId() {
5742        return mNextFocusDownId;
5743    }
5744
5745    /**
5746     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5747     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5748     * decide automatically.
5749     *
5750     * @attr ref android.R.styleable#View_nextFocusDown
5751     */
5752    public void setNextFocusDownId(int nextFocusDownId) {
5753        mNextFocusDownId = nextFocusDownId;
5754    }
5755
5756    /**
5757     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5758     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5759     *
5760     * @attr ref android.R.styleable#View_nextFocusForward
5761     */
5762    public int getNextFocusForwardId() {
5763        return mNextFocusForwardId;
5764    }
5765
5766    /**
5767     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5768     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5769     * decide automatically.
5770     *
5771     * @attr ref android.R.styleable#View_nextFocusForward
5772     */
5773    public void setNextFocusForwardId(int nextFocusForwardId) {
5774        mNextFocusForwardId = nextFocusForwardId;
5775    }
5776
5777    /**
5778     * Returns the visibility of this view and all of its ancestors
5779     *
5780     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5781     */
5782    public boolean isShown() {
5783        View current = this;
5784        //noinspection ConstantConditions
5785        do {
5786            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5787                return false;
5788            }
5789            ViewParent parent = current.mParent;
5790            if (parent == null) {
5791                return false; // We are not attached to the view root
5792            }
5793            if (!(parent instanceof View)) {
5794                return true;
5795            }
5796            current = (View) parent;
5797        } while (current != null);
5798
5799        return false;
5800    }
5801
5802    /**
5803     * Called by the view hierarchy when the content insets for a window have
5804     * changed, to allow it to adjust its content to fit within those windows.
5805     * The content insets tell you the space that the status bar, input method,
5806     * and other system windows infringe on the application's window.
5807     *
5808     * <p>You do not normally need to deal with this function, since the default
5809     * window decoration given to applications takes care of applying it to the
5810     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5811     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5812     * and your content can be placed under those system elements.  You can then
5813     * use this method within your view hierarchy if you have parts of your UI
5814     * which you would like to ensure are not being covered.
5815     *
5816     * <p>The default implementation of this method simply applies the content
5817     * insets to the view's padding, consuming that content (modifying the
5818     * insets to be 0), and returning true.  This behavior is off by default, but can
5819     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5820     *
5821     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5822     * insets object is propagated down the hierarchy, so any changes made to it will
5823     * be seen by all following views (including potentially ones above in
5824     * the hierarchy since this is a depth-first traversal).  The first view
5825     * that returns true will abort the entire traversal.
5826     *
5827     * <p>The default implementation works well for a situation where it is
5828     * used with a container that covers the entire window, allowing it to
5829     * apply the appropriate insets to its content on all edges.  If you need
5830     * a more complicated layout (such as two different views fitting system
5831     * windows, one on the top of the window, and one on the bottom),
5832     * you can override the method and handle the insets however you would like.
5833     * Note that the insets provided by the framework are always relative to the
5834     * far edges of the window, not accounting for the location of the called view
5835     * within that window.  (In fact when this method is called you do not yet know
5836     * where the layout will place the view, as it is done before layout happens.)
5837     *
5838     * <p>Note: unlike many View methods, there is no dispatch phase to this
5839     * call.  If you are overriding it in a ViewGroup and want to allow the
5840     * call to continue to your children, you must be sure to call the super
5841     * implementation.
5842     *
5843     * <p>Here is a sample layout that makes use of fitting system windows
5844     * to have controls for a video view placed inside of the window decorations
5845     * that it hides and shows.  This can be used with code like the second
5846     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5847     *
5848     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5849     *
5850     * @param insets Current content insets of the window.  Prior to
5851     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5852     * the insets or else you and Android will be unhappy.
5853     *
5854     * @return {@code true} if this view applied the insets and it should not
5855     * continue propagating further down the hierarchy, {@code false} otherwise.
5856     * @see #getFitsSystemWindows()
5857     * @see #setFitsSystemWindows(boolean)
5858     * @see #setSystemUiVisibility(int)
5859     */
5860    protected boolean fitSystemWindows(Rect insets) {
5861        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5862            mUserPaddingStart = UNDEFINED_PADDING;
5863            mUserPaddingEnd = UNDEFINED_PADDING;
5864            Rect localInsets = sThreadLocal.get();
5865            if (localInsets == null) {
5866                localInsets = new Rect();
5867                sThreadLocal.set(localInsets);
5868            }
5869            boolean res = computeFitSystemWindows(insets, localInsets);
5870            internalSetPadding(localInsets.left, localInsets.top,
5871                    localInsets.right, localInsets.bottom);
5872            return res;
5873        }
5874        return false;
5875    }
5876
5877    /**
5878     * @hide Compute the insets that should be consumed by this view and the ones
5879     * that should propagate to those under it.
5880     */
5881    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5882        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5883                || mAttachInfo == null
5884                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5885                        && !mAttachInfo.mOverscanRequested)) {
5886            outLocalInsets.set(inoutInsets);
5887            inoutInsets.set(0, 0, 0, 0);
5888            return true;
5889        } else {
5890            // The application wants to take care of fitting system window for
5891            // the content...  however we still need to take care of any overscan here.
5892            final Rect overscan = mAttachInfo.mOverscanInsets;
5893            outLocalInsets.set(overscan);
5894            inoutInsets.left -= overscan.left;
5895            inoutInsets.top -= overscan.top;
5896            inoutInsets.right -= overscan.right;
5897            inoutInsets.bottom -= overscan.bottom;
5898            return false;
5899        }
5900    }
5901
5902    /**
5903     * Sets whether or not this view should account for system screen decorations
5904     * such as the status bar and inset its content; that is, controlling whether
5905     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5906     * executed.  See that method for more details.
5907     *
5908     * <p>Note that if you are providing your own implementation of
5909     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5910     * flag to true -- your implementation will be overriding the default
5911     * implementation that checks this flag.
5912     *
5913     * @param fitSystemWindows If true, then the default implementation of
5914     * {@link #fitSystemWindows(Rect)} will be executed.
5915     *
5916     * @attr ref android.R.styleable#View_fitsSystemWindows
5917     * @see #getFitsSystemWindows()
5918     * @see #fitSystemWindows(Rect)
5919     * @see #setSystemUiVisibility(int)
5920     */
5921    public void setFitsSystemWindows(boolean fitSystemWindows) {
5922        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5923    }
5924
5925    /**
5926     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5927     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5928     * will be executed.
5929     *
5930     * @return {@code true} if the default implementation of
5931     * {@link #fitSystemWindows(Rect)} will be executed.
5932     *
5933     * @attr ref android.R.styleable#View_fitsSystemWindows
5934     * @see #setFitsSystemWindows(boolean)
5935     * @see #fitSystemWindows(Rect)
5936     * @see #setSystemUiVisibility(int)
5937     */
5938    public boolean getFitsSystemWindows() {
5939        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5940    }
5941
5942    /** @hide */
5943    public boolean fitsSystemWindows() {
5944        return getFitsSystemWindows();
5945    }
5946
5947    /**
5948     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5949     */
5950    public void requestFitSystemWindows() {
5951        if (mParent != null) {
5952            mParent.requestFitSystemWindows();
5953        }
5954    }
5955
5956    /**
5957     * For use by PhoneWindow to make its own system window fitting optional.
5958     * @hide
5959     */
5960    public void makeOptionalFitsSystemWindows() {
5961        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5962    }
5963
5964    /**
5965     * Returns the visibility status for this view.
5966     *
5967     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5968     * @attr ref android.R.styleable#View_visibility
5969     */
5970    @ViewDebug.ExportedProperty(mapping = {
5971        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5972        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5973        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5974    })
5975    public int getVisibility() {
5976        return mViewFlags & VISIBILITY_MASK;
5977    }
5978
5979    /**
5980     * Set the enabled state of this view.
5981     *
5982     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5983     * @attr ref android.R.styleable#View_visibility
5984     */
5985    @RemotableViewMethod
5986    public void setVisibility(int visibility) {
5987        setFlags(visibility, VISIBILITY_MASK);
5988        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5989    }
5990
5991    /**
5992     * Returns the enabled status for this view. The interpretation of the
5993     * enabled state varies by subclass.
5994     *
5995     * @return True if this view is enabled, false otherwise.
5996     */
5997    @ViewDebug.ExportedProperty
5998    public boolean isEnabled() {
5999        return (mViewFlags & ENABLED_MASK) == ENABLED;
6000    }
6001
6002    /**
6003     * Set the enabled state of this view. The interpretation of the enabled
6004     * state varies by subclass.
6005     *
6006     * @param enabled True if this view is enabled, false otherwise.
6007     */
6008    @RemotableViewMethod
6009    public void setEnabled(boolean enabled) {
6010        if (enabled == isEnabled()) return;
6011
6012        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6013
6014        /*
6015         * The View most likely has to change its appearance, so refresh
6016         * the drawable state.
6017         */
6018        refreshDrawableState();
6019
6020        // Invalidate too, since the default behavior for views is to be
6021        // be drawn at 50% alpha rather than to change the drawable.
6022        invalidate(true);
6023
6024        if (!enabled) {
6025            cancelPendingInputEvents();
6026        }
6027    }
6028
6029    /**
6030     * Set whether this view can receive the focus.
6031     *
6032     * Setting this to false will also ensure that this view is not focusable
6033     * in touch mode.
6034     *
6035     * @param focusable If true, this view can receive the focus.
6036     *
6037     * @see #setFocusableInTouchMode(boolean)
6038     * @attr ref android.R.styleable#View_focusable
6039     */
6040    public void setFocusable(boolean focusable) {
6041        if (!focusable) {
6042            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6043        }
6044        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6045    }
6046
6047    /**
6048     * Set whether this view can receive focus while in touch mode.
6049     *
6050     * Setting this to true will also ensure that this view is focusable.
6051     *
6052     * @param focusableInTouchMode If true, this view can receive the focus while
6053     *   in touch mode.
6054     *
6055     * @see #setFocusable(boolean)
6056     * @attr ref android.R.styleable#View_focusableInTouchMode
6057     */
6058    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6059        // Focusable in touch mode should always be set before the focusable flag
6060        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6061        // which, in touch mode, will not successfully request focus on this view
6062        // because the focusable in touch mode flag is not set
6063        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6064        if (focusableInTouchMode) {
6065            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6066        }
6067    }
6068
6069    /**
6070     * Set whether this view should have sound effects enabled for events such as
6071     * clicking and touching.
6072     *
6073     * <p>You may wish to disable sound effects for a view if you already play sounds,
6074     * for instance, a dial key that plays dtmf tones.
6075     *
6076     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6077     * @see #isSoundEffectsEnabled()
6078     * @see #playSoundEffect(int)
6079     * @attr ref android.R.styleable#View_soundEffectsEnabled
6080     */
6081    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6082        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6083    }
6084
6085    /**
6086     * @return whether this view should have sound effects enabled for events such as
6087     *     clicking and touching.
6088     *
6089     * @see #setSoundEffectsEnabled(boolean)
6090     * @see #playSoundEffect(int)
6091     * @attr ref android.R.styleable#View_soundEffectsEnabled
6092     */
6093    @ViewDebug.ExportedProperty
6094    public boolean isSoundEffectsEnabled() {
6095        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6096    }
6097
6098    /**
6099     * Set whether this view should have haptic feedback for events such as
6100     * long presses.
6101     *
6102     * <p>You may wish to disable haptic feedback if your view already controls
6103     * its own haptic feedback.
6104     *
6105     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6106     * @see #isHapticFeedbackEnabled()
6107     * @see #performHapticFeedback(int)
6108     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6109     */
6110    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6111        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6112    }
6113
6114    /**
6115     * @return whether this view should have haptic feedback enabled for events
6116     * long presses.
6117     *
6118     * @see #setHapticFeedbackEnabled(boolean)
6119     * @see #performHapticFeedback(int)
6120     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6121     */
6122    @ViewDebug.ExportedProperty
6123    public boolean isHapticFeedbackEnabled() {
6124        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6125    }
6126
6127    /**
6128     * Returns the layout direction for this view.
6129     *
6130     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6131     *   {@link #LAYOUT_DIRECTION_RTL},
6132     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6133     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6134     *
6135     * @attr ref android.R.styleable#View_layoutDirection
6136     *
6137     * @hide
6138     */
6139    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6140        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6141        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6142        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6143        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6144    })
6145    public int getRawLayoutDirection() {
6146        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6147    }
6148
6149    /**
6150     * Set the layout direction for this view. This will propagate a reset of layout direction
6151     * resolution to the view's children and resolve layout direction for this view.
6152     *
6153     * @param layoutDirection the layout direction to set. Should be one of:
6154     *
6155     * {@link #LAYOUT_DIRECTION_LTR},
6156     * {@link #LAYOUT_DIRECTION_RTL},
6157     * {@link #LAYOUT_DIRECTION_INHERIT},
6158     * {@link #LAYOUT_DIRECTION_LOCALE}.
6159     *
6160     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6161     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6162     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6163     *
6164     * @attr ref android.R.styleable#View_layoutDirection
6165     */
6166    @RemotableViewMethod
6167    public void setLayoutDirection(int layoutDirection) {
6168        if (getRawLayoutDirection() != layoutDirection) {
6169            // Reset the current layout direction and the resolved one
6170            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6171            resetRtlProperties();
6172            // Set the new layout direction (filtered)
6173            mPrivateFlags2 |=
6174                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6175            // We need to resolve all RTL properties as they all depend on layout direction
6176            resolveRtlPropertiesIfNeeded();
6177            requestLayout();
6178            invalidate(true);
6179        }
6180    }
6181
6182    /**
6183     * Returns the resolved layout direction for this view.
6184     *
6185     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6186     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6187     *
6188     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6189     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6190     *
6191     * @attr ref android.R.styleable#View_layoutDirection
6192     */
6193    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6194        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6195        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6196    })
6197    public int getLayoutDirection() {
6198        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6199        if (targetSdkVersion < JELLY_BEAN_MR1) {
6200            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6201            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6202        }
6203        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6204                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6205    }
6206
6207    /**
6208     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6209     * layout attribute and/or the inherited value from the parent
6210     *
6211     * @return true if the layout is right-to-left.
6212     *
6213     * @hide
6214     */
6215    @ViewDebug.ExportedProperty(category = "layout")
6216    public boolean isLayoutRtl() {
6217        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6218    }
6219
6220    /**
6221     * Indicates whether the view is currently tracking transient state that the
6222     * app should not need to concern itself with saving and restoring, but that
6223     * the framework should take special note to preserve when possible.
6224     *
6225     * <p>A view with transient state cannot be trivially rebound from an external
6226     * data source, such as an adapter binding item views in a list. This may be
6227     * because the view is performing an animation, tracking user selection
6228     * of content, or similar.</p>
6229     *
6230     * @return true if the view has transient state
6231     */
6232    @ViewDebug.ExportedProperty(category = "layout")
6233    public boolean hasTransientState() {
6234        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6235    }
6236
6237    /**
6238     * Set whether this view is currently tracking transient state that the
6239     * framework should attempt to preserve when possible. This flag is reference counted,
6240     * so every call to setHasTransientState(true) should be paired with a later call
6241     * to setHasTransientState(false).
6242     *
6243     * <p>A view with transient state cannot be trivially rebound from an external
6244     * data source, such as an adapter binding item views in a list. This may be
6245     * because the view is performing an animation, tracking user selection
6246     * of content, or similar.</p>
6247     *
6248     * @param hasTransientState true if this view has transient state
6249     */
6250    public void setHasTransientState(boolean hasTransientState) {
6251        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6252                mTransientStateCount - 1;
6253        if (mTransientStateCount < 0) {
6254            mTransientStateCount = 0;
6255            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6256                    "unmatched pair of setHasTransientState calls");
6257        } else if ((hasTransientState && mTransientStateCount == 1) ||
6258                (!hasTransientState && mTransientStateCount == 0)) {
6259            // update flag if we've just incremented up from 0 or decremented down to 0
6260            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6261                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6262            if (mParent != null) {
6263                try {
6264                    mParent.childHasTransientStateChanged(this, hasTransientState);
6265                } catch (AbstractMethodError e) {
6266                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6267                            " does not fully implement ViewParent", e);
6268                }
6269            }
6270        }
6271    }
6272
6273    /**
6274     * Returns true if this view is currently attached to a window.
6275     */
6276    public boolean isAttachedToWindow() {
6277        return mAttachInfo != null;
6278    }
6279
6280    /**
6281     * Returns true if this view has been through at least one layout since it
6282     * was last attached to or detached from a window.
6283     */
6284    public boolean isLaidOut() {
6285        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6286    }
6287
6288    /**
6289     * If this view doesn't do any drawing on its own, set this flag to
6290     * allow further optimizations. By default, this flag is not set on
6291     * View, but could be set on some View subclasses such as ViewGroup.
6292     *
6293     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6294     * you should clear this flag.
6295     *
6296     * @param willNotDraw whether or not this View draw on its own
6297     */
6298    public void setWillNotDraw(boolean willNotDraw) {
6299        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6300    }
6301
6302    /**
6303     * Returns whether or not this View draws on its own.
6304     *
6305     * @return true if this view has nothing to draw, false otherwise
6306     */
6307    @ViewDebug.ExportedProperty(category = "drawing")
6308    public boolean willNotDraw() {
6309        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6310    }
6311
6312    /**
6313     * When a View's drawing cache is enabled, drawing is redirected to an
6314     * offscreen bitmap. Some views, like an ImageView, must be able to
6315     * bypass this mechanism if they already draw a single bitmap, to avoid
6316     * unnecessary usage of the memory.
6317     *
6318     * @param willNotCacheDrawing true if this view does not cache its
6319     *        drawing, false otherwise
6320     */
6321    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6322        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6323    }
6324
6325    /**
6326     * Returns whether or not this View can cache its drawing or not.
6327     *
6328     * @return true if this view does not cache its drawing, false otherwise
6329     */
6330    @ViewDebug.ExportedProperty(category = "drawing")
6331    public boolean willNotCacheDrawing() {
6332        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6333    }
6334
6335    /**
6336     * Indicates whether this view reacts to click events or not.
6337     *
6338     * @return true if the view is clickable, false otherwise
6339     *
6340     * @see #setClickable(boolean)
6341     * @attr ref android.R.styleable#View_clickable
6342     */
6343    @ViewDebug.ExportedProperty
6344    public boolean isClickable() {
6345        return (mViewFlags & CLICKABLE) == CLICKABLE;
6346    }
6347
6348    /**
6349     * Enables or disables click events for this view. When a view
6350     * is clickable it will change its state to "pressed" on every click.
6351     * Subclasses should set the view clickable to visually react to
6352     * user's clicks.
6353     *
6354     * @param clickable true to make the view clickable, false otherwise
6355     *
6356     * @see #isClickable()
6357     * @attr ref android.R.styleable#View_clickable
6358     */
6359    public void setClickable(boolean clickable) {
6360        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6361    }
6362
6363    /**
6364     * Indicates whether this view reacts to long click events or not.
6365     *
6366     * @return true if the view is long clickable, false otherwise
6367     *
6368     * @see #setLongClickable(boolean)
6369     * @attr ref android.R.styleable#View_longClickable
6370     */
6371    public boolean isLongClickable() {
6372        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6373    }
6374
6375    /**
6376     * Enables or disables long click events for this view. When a view is long
6377     * clickable it reacts to the user holding down the button for a longer
6378     * duration than a tap. This event can either launch the listener or a
6379     * context menu.
6380     *
6381     * @param longClickable true to make the view long clickable, false otherwise
6382     * @see #isLongClickable()
6383     * @attr ref android.R.styleable#View_longClickable
6384     */
6385    public void setLongClickable(boolean longClickable) {
6386        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6387    }
6388
6389    /**
6390     * Sets the pressed state for this view.
6391     *
6392     * @see #isClickable()
6393     * @see #setClickable(boolean)
6394     *
6395     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6396     *        the View's internal state from a previously set "pressed" state.
6397     */
6398    public void setPressed(boolean pressed) {
6399        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6400
6401        if (pressed) {
6402            mPrivateFlags |= PFLAG_PRESSED;
6403        } else {
6404            mPrivateFlags &= ~PFLAG_PRESSED;
6405        }
6406
6407        if (needsRefresh) {
6408            refreshDrawableState();
6409        }
6410        dispatchSetPressed(pressed);
6411    }
6412
6413    /**
6414     * Dispatch setPressed to all of this View's children.
6415     *
6416     * @see #setPressed(boolean)
6417     *
6418     * @param pressed The new pressed state
6419     */
6420    protected void dispatchSetPressed(boolean pressed) {
6421    }
6422
6423    /**
6424     * Indicates whether the view is currently in pressed state. Unless
6425     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6426     * the pressed state.
6427     *
6428     * @see #setPressed(boolean)
6429     * @see #isClickable()
6430     * @see #setClickable(boolean)
6431     *
6432     * @return true if the view is currently pressed, false otherwise
6433     */
6434    public boolean isPressed() {
6435        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6436    }
6437
6438    /**
6439     * Indicates whether this view will save its state (that is,
6440     * whether its {@link #onSaveInstanceState} method will be called).
6441     *
6442     * @return Returns true if the view state saving is enabled, else false.
6443     *
6444     * @see #setSaveEnabled(boolean)
6445     * @attr ref android.R.styleable#View_saveEnabled
6446     */
6447    public boolean isSaveEnabled() {
6448        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6449    }
6450
6451    /**
6452     * Controls whether the saving of this view's state is
6453     * enabled (that is, whether its {@link #onSaveInstanceState} method
6454     * will be called).  Note that even if freezing is enabled, the
6455     * view still must have an id assigned to it (via {@link #setId(int)})
6456     * for its state to be saved.  This flag can only disable the
6457     * saving of this view; any child views may still have their state saved.
6458     *
6459     * @param enabled Set to false to <em>disable</em> state saving, or true
6460     * (the default) to allow it.
6461     *
6462     * @see #isSaveEnabled()
6463     * @see #setId(int)
6464     * @see #onSaveInstanceState()
6465     * @attr ref android.R.styleable#View_saveEnabled
6466     */
6467    public void setSaveEnabled(boolean enabled) {
6468        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6469    }
6470
6471    /**
6472     * Gets whether the framework should discard touches when the view's
6473     * window is obscured by another visible window.
6474     * Refer to the {@link View} security documentation for more details.
6475     *
6476     * @return True if touch filtering is enabled.
6477     *
6478     * @see #setFilterTouchesWhenObscured(boolean)
6479     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6480     */
6481    @ViewDebug.ExportedProperty
6482    public boolean getFilterTouchesWhenObscured() {
6483        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6484    }
6485
6486    /**
6487     * Sets whether the framework should discard touches when the view's
6488     * window is obscured by another visible window.
6489     * Refer to the {@link View} security documentation for more details.
6490     *
6491     * @param enabled True if touch filtering should be enabled.
6492     *
6493     * @see #getFilterTouchesWhenObscured
6494     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6495     */
6496    public void setFilterTouchesWhenObscured(boolean enabled) {
6497        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6498                FILTER_TOUCHES_WHEN_OBSCURED);
6499    }
6500
6501    /**
6502     * Indicates whether the entire hierarchy under this view will save its
6503     * state when a state saving traversal occurs from its parent.  The default
6504     * is true; if false, these views will not be saved unless
6505     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6506     *
6507     * @return Returns true if the view state saving from parent is enabled, else false.
6508     *
6509     * @see #setSaveFromParentEnabled(boolean)
6510     */
6511    public boolean isSaveFromParentEnabled() {
6512        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6513    }
6514
6515    /**
6516     * Controls whether the entire hierarchy under this view will save its
6517     * state when a state saving traversal occurs from its parent.  The default
6518     * is true; if false, these views will not be saved unless
6519     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6520     *
6521     * @param enabled Set to false to <em>disable</em> state saving, or true
6522     * (the default) to allow it.
6523     *
6524     * @see #isSaveFromParentEnabled()
6525     * @see #setId(int)
6526     * @see #onSaveInstanceState()
6527     */
6528    public void setSaveFromParentEnabled(boolean enabled) {
6529        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6530    }
6531
6532
6533    /**
6534     * Returns whether this View is able to take focus.
6535     *
6536     * @return True if this view can take focus, or false otherwise.
6537     * @attr ref android.R.styleable#View_focusable
6538     */
6539    @ViewDebug.ExportedProperty(category = "focus")
6540    public final boolean isFocusable() {
6541        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6542    }
6543
6544    /**
6545     * When a view is focusable, it may not want to take focus when in touch mode.
6546     * For example, a button would like focus when the user is navigating via a D-pad
6547     * so that the user can click on it, but once the user starts touching the screen,
6548     * the button shouldn't take focus
6549     * @return Whether the view is focusable in touch mode.
6550     * @attr ref android.R.styleable#View_focusableInTouchMode
6551     */
6552    @ViewDebug.ExportedProperty
6553    public final boolean isFocusableInTouchMode() {
6554        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6555    }
6556
6557    /**
6558     * Find the nearest view in the specified direction that can take focus.
6559     * This does not actually give focus to that view.
6560     *
6561     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6562     *
6563     * @return The nearest focusable in the specified direction, or null if none
6564     *         can be found.
6565     */
6566    public View focusSearch(int direction) {
6567        if (mParent != null) {
6568            return mParent.focusSearch(this, direction);
6569        } else {
6570            return null;
6571        }
6572    }
6573
6574    /**
6575     * This method is the last chance for the focused view and its ancestors to
6576     * respond to an arrow key. This is called when the focused view did not
6577     * consume the key internally, nor could the view system find a new view in
6578     * the requested direction to give focus to.
6579     *
6580     * @param focused The currently focused view.
6581     * @param direction The direction focus wants to move. One of FOCUS_UP,
6582     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6583     * @return True if the this view consumed this unhandled move.
6584     */
6585    public boolean dispatchUnhandledMove(View focused, int direction) {
6586        return false;
6587    }
6588
6589    /**
6590     * If a user manually specified the next view id for a particular direction,
6591     * use the root to look up the view.
6592     * @param root The root view of the hierarchy containing this view.
6593     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6594     * or FOCUS_BACKWARD.
6595     * @return The user specified next view, or null if there is none.
6596     */
6597    View findUserSetNextFocus(View root, int direction) {
6598        switch (direction) {
6599            case FOCUS_LEFT:
6600                if (mNextFocusLeftId == View.NO_ID) return null;
6601                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6602            case FOCUS_RIGHT:
6603                if (mNextFocusRightId == View.NO_ID) return null;
6604                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6605            case FOCUS_UP:
6606                if (mNextFocusUpId == View.NO_ID) return null;
6607                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6608            case FOCUS_DOWN:
6609                if (mNextFocusDownId == View.NO_ID) return null;
6610                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6611            case FOCUS_FORWARD:
6612                if (mNextFocusForwardId == View.NO_ID) return null;
6613                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6614            case FOCUS_BACKWARD: {
6615                if (mID == View.NO_ID) return null;
6616                final int id = mID;
6617                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6618                    @Override
6619                    public boolean apply(View t) {
6620                        return t.mNextFocusForwardId == id;
6621                    }
6622                });
6623            }
6624        }
6625        return null;
6626    }
6627
6628    private View findViewInsideOutShouldExist(View root, int id) {
6629        if (mMatchIdPredicate == null) {
6630            mMatchIdPredicate = new MatchIdPredicate();
6631        }
6632        mMatchIdPredicate.mId = id;
6633        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6634        if (result == null) {
6635            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6636        }
6637        return result;
6638    }
6639
6640    /**
6641     * Find and return all focusable views that are descendants of this view,
6642     * possibly including this view if it is focusable itself.
6643     *
6644     * @param direction The direction of the focus
6645     * @return A list of focusable views
6646     */
6647    public ArrayList<View> getFocusables(int direction) {
6648        ArrayList<View> result = new ArrayList<View>(24);
6649        addFocusables(result, direction);
6650        return result;
6651    }
6652
6653    /**
6654     * Add any focusable views that are descendants of this view (possibly
6655     * including this view if it is focusable itself) to views.  If we are in touch mode,
6656     * only add views that are also focusable in touch mode.
6657     *
6658     * @param views Focusable views found so far
6659     * @param direction The direction of the focus
6660     */
6661    public void addFocusables(ArrayList<View> views, int direction) {
6662        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6663    }
6664
6665    /**
6666     * Adds any focusable views that are descendants of this view (possibly
6667     * including this view if it is focusable itself) to views. This method
6668     * adds all focusable views regardless if we are in touch mode or
6669     * only views focusable in touch mode if we are in touch mode or
6670     * only views that can take accessibility focus if accessibility is enabeld
6671     * depending on the focusable mode paramater.
6672     *
6673     * @param views Focusable views found so far or null if all we are interested is
6674     *        the number of focusables.
6675     * @param direction The direction of the focus.
6676     * @param focusableMode The type of focusables to be added.
6677     *
6678     * @see #FOCUSABLES_ALL
6679     * @see #FOCUSABLES_TOUCH_MODE
6680     */
6681    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6682        if (views == null) {
6683            return;
6684        }
6685        if (!isFocusable()) {
6686            return;
6687        }
6688        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6689                && isInTouchMode() && !isFocusableInTouchMode()) {
6690            return;
6691        }
6692        views.add(this);
6693    }
6694
6695    /**
6696     * Finds the Views that contain given text. The containment is case insensitive.
6697     * The search is performed by either the text that the View renders or the content
6698     * description that describes the view for accessibility purposes and the view does
6699     * not render or both. Clients can specify how the search is to be performed via
6700     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6701     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6702     *
6703     * @param outViews The output list of matching Views.
6704     * @param searched The text to match against.
6705     *
6706     * @see #FIND_VIEWS_WITH_TEXT
6707     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6708     * @see #setContentDescription(CharSequence)
6709     */
6710    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6711        if (getAccessibilityNodeProvider() != null) {
6712            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6713                outViews.add(this);
6714            }
6715        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6716                && (searched != null && searched.length() > 0)
6717                && (mContentDescription != null && mContentDescription.length() > 0)) {
6718            String searchedLowerCase = searched.toString().toLowerCase();
6719            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6720            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6721                outViews.add(this);
6722            }
6723        }
6724    }
6725
6726    /**
6727     * Find and return all touchable views that are descendants of this view,
6728     * possibly including this view if it is touchable itself.
6729     *
6730     * @return A list of touchable views
6731     */
6732    public ArrayList<View> getTouchables() {
6733        ArrayList<View> result = new ArrayList<View>();
6734        addTouchables(result);
6735        return result;
6736    }
6737
6738    /**
6739     * Add any touchable views that are descendants of this view (possibly
6740     * including this view if it is touchable itself) to views.
6741     *
6742     * @param views Touchable views found so far
6743     */
6744    public void addTouchables(ArrayList<View> views) {
6745        final int viewFlags = mViewFlags;
6746
6747        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6748                && (viewFlags & ENABLED_MASK) == ENABLED) {
6749            views.add(this);
6750        }
6751    }
6752
6753    /**
6754     * Returns whether this View is accessibility focused.
6755     *
6756     * @return True if this View is accessibility focused.
6757     * @hide
6758     */
6759    public boolean isAccessibilityFocused() {
6760        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6761    }
6762
6763    /**
6764     * Call this to try to give accessibility focus to this view.
6765     *
6766     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6767     * returns false or the view is no visible or the view already has accessibility
6768     * focus.
6769     *
6770     * See also {@link #focusSearch(int)}, which is what you call to say that you
6771     * have focus, and you want your parent to look for the next one.
6772     *
6773     * @return Whether this view actually took accessibility focus.
6774     *
6775     * @hide
6776     */
6777    public boolean requestAccessibilityFocus() {
6778        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6779        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6780            return false;
6781        }
6782        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6783            return false;
6784        }
6785        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6786            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6787            ViewRootImpl viewRootImpl = getViewRootImpl();
6788            if (viewRootImpl != null) {
6789                viewRootImpl.setAccessibilityFocus(this, null);
6790            }
6791            invalidate();
6792            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6793            return true;
6794        }
6795        return false;
6796    }
6797
6798    /**
6799     * Call this to try to clear accessibility focus of this view.
6800     *
6801     * See also {@link #focusSearch(int)}, which is what you call to say that you
6802     * have focus, and you want your parent to look for the next one.
6803     *
6804     * @hide
6805     */
6806    public void clearAccessibilityFocus() {
6807        clearAccessibilityFocusNoCallbacks();
6808        // Clear the global reference of accessibility focus if this
6809        // view or any of its descendants had accessibility focus.
6810        ViewRootImpl viewRootImpl = getViewRootImpl();
6811        if (viewRootImpl != null) {
6812            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6813            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6814                viewRootImpl.setAccessibilityFocus(null, null);
6815            }
6816        }
6817    }
6818
6819    private void sendAccessibilityHoverEvent(int eventType) {
6820        // Since we are not delivering to a client accessibility events from not
6821        // important views (unless the clinet request that) we need to fire the
6822        // event from the deepest view exposed to the client. As a consequence if
6823        // the user crosses a not exposed view the client will see enter and exit
6824        // of the exposed predecessor followed by and enter and exit of that same
6825        // predecessor when entering and exiting the not exposed descendant. This
6826        // is fine since the client has a clear idea which view is hovered at the
6827        // price of a couple more events being sent. This is a simple and
6828        // working solution.
6829        View source = this;
6830        while (true) {
6831            if (source.includeForAccessibility()) {
6832                source.sendAccessibilityEvent(eventType);
6833                return;
6834            }
6835            ViewParent parent = source.getParent();
6836            if (parent instanceof View) {
6837                source = (View) parent;
6838            } else {
6839                return;
6840            }
6841        }
6842    }
6843
6844    /**
6845     * Clears accessibility focus without calling any callback methods
6846     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6847     * is used for clearing accessibility focus when giving this focus to
6848     * another view.
6849     */
6850    void clearAccessibilityFocusNoCallbacks() {
6851        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6852            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6853            invalidate();
6854            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6855        }
6856    }
6857
6858    /**
6859     * Call this to try to give focus to a specific view or to one of its
6860     * descendants.
6861     *
6862     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6863     * false), or if it is focusable and it is not focusable in touch mode
6864     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6865     *
6866     * See also {@link #focusSearch(int)}, which is what you call to say that you
6867     * have focus, and you want your parent to look for the next one.
6868     *
6869     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6870     * {@link #FOCUS_DOWN} and <code>null</code>.
6871     *
6872     * @return Whether this view or one of its descendants actually took focus.
6873     */
6874    public final boolean requestFocus() {
6875        return requestFocus(View.FOCUS_DOWN);
6876    }
6877
6878    /**
6879     * Call this to try to give focus to a specific view or to one of its
6880     * descendants and give it a hint about what direction focus is heading.
6881     *
6882     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6883     * false), or if it is focusable and it is not focusable in touch mode
6884     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6885     *
6886     * See also {@link #focusSearch(int)}, which is what you call to say that you
6887     * have focus, and you want your parent to look for the next one.
6888     *
6889     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6890     * <code>null</code> set for the previously focused rectangle.
6891     *
6892     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6893     * @return Whether this view or one of its descendants actually took focus.
6894     */
6895    public final boolean requestFocus(int direction) {
6896        return requestFocus(direction, null);
6897    }
6898
6899    /**
6900     * Call this to try to give focus to a specific view or to one of its descendants
6901     * and give it hints about the direction and a specific rectangle that the focus
6902     * is coming from.  The rectangle can help give larger views a finer grained hint
6903     * about where focus is coming from, and therefore, where to show selection, or
6904     * forward focus change internally.
6905     *
6906     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6907     * false), or if it is focusable and it is not focusable in touch mode
6908     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6909     *
6910     * A View will not take focus if it is not visible.
6911     *
6912     * A View will not take focus if one of its parents has
6913     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6914     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6915     *
6916     * See also {@link #focusSearch(int)}, which is what you call to say that you
6917     * have focus, and you want your parent to look for the next one.
6918     *
6919     * You may wish to override this method if your custom {@link View} has an internal
6920     * {@link View} that it wishes to forward the request to.
6921     *
6922     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6923     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6924     *        to give a finer grained hint about where focus is coming from.  May be null
6925     *        if there is no hint.
6926     * @return Whether this view or one of its descendants actually took focus.
6927     */
6928    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6929        return requestFocusNoSearch(direction, previouslyFocusedRect);
6930    }
6931
6932    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6933        // need to be focusable
6934        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6935                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6936            return false;
6937        }
6938
6939        // need to be focusable in touch mode if in touch mode
6940        if (isInTouchMode() &&
6941            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6942               return false;
6943        }
6944
6945        // need to not have any parents blocking us
6946        if (hasAncestorThatBlocksDescendantFocus()) {
6947            return false;
6948        }
6949
6950        handleFocusGainInternal(direction, previouslyFocusedRect);
6951        return true;
6952    }
6953
6954    /**
6955     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6956     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6957     * touch mode to request focus when they are touched.
6958     *
6959     * @return Whether this view or one of its descendants actually took focus.
6960     *
6961     * @see #isInTouchMode()
6962     *
6963     */
6964    public final boolean requestFocusFromTouch() {
6965        // Leave touch mode if we need to
6966        if (isInTouchMode()) {
6967            ViewRootImpl viewRoot = getViewRootImpl();
6968            if (viewRoot != null) {
6969                viewRoot.ensureTouchMode(false);
6970            }
6971        }
6972        return requestFocus(View.FOCUS_DOWN);
6973    }
6974
6975    /**
6976     * @return Whether any ancestor of this view blocks descendant focus.
6977     */
6978    private boolean hasAncestorThatBlocksDescendantFocus() {
6979        ViewParent ancestor = mParent;
6980        while (ancestor instanceof ViewGroup) {
6981            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6982            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6983                return true;
6984            } else {
6985                ancestor = vgAncestor.getParent();
6986            }
6987        }
6988        return false;
6989    }
6990
6991    /**
6992     * Gets the mode for determining whether this View is important for accessibility
6993     * which is if it fires accessibility events and if it is reported to
6994     * accessibility services that query the screen.
6995     *
6996     * @return The mode for determining whether a View is important for accessibility.
6997     *
6998     * @attr ref android.R.styleable#View_importantForAccessibility
6999     *
7000     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7001     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7002     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7003     */
7004    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7005            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7006            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7007            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
7008        })
7009    public int getImportantForAccessibility() {
7010        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7011                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7012    }
7013
7014    /**
7015     * Sets the live region mode for this view. This indicates to accessibility
7016     * services whether they should automatically notify the user about changes
7017     * to the view's content description or text, or to the content descriptions
7018     * or text of the view's children (where applicable).
7019     * <p>
7020     * For example, in a login screen with a TextView that displays an "incorrect
7021     * password" notification, that view should be marked as a live region with
7022     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7023     * <p>
7024     * To disable change notifications for this view, use
7025     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7026     * mode for most views.
7027     * <p>
7028     * To indicate that the user should be notified of changes, use
7029     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7030     * <p>
7031     * If the view's changes should interrupt ongoing speech and notify the user
7032     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7033     *
7034     * @param mode The live region mode for this view, one of:
7035     *        <ul>
7036     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7037     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7038     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7039     *        </ul>
7040     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7041     */
7042    public void setAccessibilityLiveRegion(int mode) {
7043        if (mode != getAccessibilityLiveRegion()) {
7044            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7045            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7046                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7047            notifyViewAccessibilityStateChangedIfNeeded(
7048                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7049        }
7050    }
7051
7052    /**
7053     * Gets the live region mode for this View.
7054     *
7055     * @return The live region mode for the view.
7056     *
7057     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7058     *
7059     * @see #setAccessibilityLiveRegion(int)
7060     */
7061    public int getAccessibilityLiveRegion() {
7062        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7063                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7064    }
7065
7066    /**
7067     * Sets how to determine whether this view is important for accessibility
7068     * which is if it fires accessibility events and if it is reported to
7069     * accessibility services that query the screen.
7070     *
7071     * @param mode How to determine whether this view is important for accessibility.
7072     *
7073     * @attr ref android.R.styleable#View_importantForAccessibility
7074     *
7075     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7076     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7077     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7078     */
7079    public void setImportantForAccessibility(int mode) {
7080        final boolean oldIncludeForAccessibility = includeForAccessibility();
7081        if (mode != getImportantForAccessibility()) {
7082            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7083            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7084                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7085            if (oldIncludeForAccessibility != includeForAccessibility()) {
7086                notifySubtreeAccessibilityStateChangedIfNeeded();
7087            } else {
7088                notifyViewAccessibilityStateChangedIfNeeded(
7089                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7090            }
7091        }
7092    }
7093
7094    /**
7095     * Gets whether this view should be exposed for accessibility.
7096     *
7097     * @return Whether the view is exposed for accessibility.
7098     *
7099     * @hide
7100     */
7101    public boolean isImportantForAccessibility() {
7102        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7103                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7104        switch (mode) {
7105            case IMPORTANT_FOR_ACCESSIBILITY_YES:
7106                return true;
7107            case IMPORTANT_FOR_ACCESSIBILITY_NO:
7108                return false;
7109            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
7110                return isActionableForAccessibility() || hasListenersForAccessibility()
7111                        || getAccessibilityNodeProvider() != null
7112                        || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7113            default:
7114                throw new IllegalArgumentException("Unknow important for accessibility mode: "
7115                        + mode);
7116        }
7117    }
7118
7119    /**
7120     * Gets the parent for accessibility purposes. Note that the parent for
7121     * accessibility is not necessary the immediate parent. It is the first
7122     * predecessor that is important for accessibility.
7123     *
7124     * @return The parent for accessibility purposes.
7125     */
7126    public ViewParent getParentForAccessibility() {
7127        if (mParent instanceof View) {
7128            View parentView = (View) mParent;
7129            if (parentView.includeForAccessibility()) {
7130                return mParent;
7131            } else {
7132                return mParent.getParentForAccessibility();
7133            }
7134        }
7135        return null;
7136    }
7137
7138    /**
7139     * Adds the children of a given View for accessibility. Since some Views are
7140     * not important for accessibility the children for accessibility are not
7141     * necessarily direct children of the view, rather they are the first level of
7142     * descendants important for accessibility.
7143     *
7144     * @param children The list of children for accessibility.
7145     */
7146    public void addChildrenForAccessibility(ArrayList<View> children) {
7147        if (includeForAccessibility()) {
7148            children.add(this);
7149        }
7150    }
7151
7152    /**
7153     * Whether to regard this view for accessibility. A view is regarded for
7154     * accessibility if it is important for accessibility or the querying
7155     * accessibility service has explicitly requested that view not
7156     * important for accessibility are regarded.
7157     *
7158     * @return Whether to regard the view for accessibility.
7159     *
7160     * @hide
7161     */
7162    public boolean includeForAccessibility() {
7163        //noinspection SimplifiableIfStatement
7164        if (mAttachInfo != null) {
7165            return (mAttachInfo.mAccessibilityFetchFlags
7166                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7167                    || isImportantForAccessibility();
7168        }
7169        return false;
7170    }
7171
7172    /**
7173     * Returns whether the View is considered actionable from
7174     * accessibility perspective. Such view are important for
7175     * accessibility.
7176     *
7177     * @return True if the view is actionable for accessibility.
7178     *
7179     * @hide
7180     */
7181    public boolean isActionableForAccessibility() {
7182        return (isClickable() || isLongClickable() || isFocusable());
7183    }
7184
7185    /**
7186     * Returns whether the View has registered callbacks wich makes it
7187     * important for accessibility.
7188     *
7189     * @return True if the view is actionable for accessibility.
7190     */
7191    private boolean hasListenersForAccessibility() {
7192        ListenerInfo info = getListenerInfo();
7193        return mTouchDelegate != null || info.mOnKeyListener != null
7194                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7195                || info.mOnHoverListener != null || info.mOnDragListener != null;
7196    }
7197
7198    /**
7199     * Notifies that the accessibility state of this view changed. The change
7200     * is local to this view and does not represent structural changes such
7201     * as children and parent. For example, the view became focusable. The
7202     * notification is at at most once every
7203     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7204     * to avoid unnecessary load to the system. Also once a view has a pending
7205     * notifucation this method is a NOP until the notification has been sent.
7206     *
7207     * @hide
7208     */
7209    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7210        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7211            return;
7212        }
7213        if (mSendViewStateChangedAccessibilityEvent == null) {
7214            mSendViewStateChangedAccessibilityEvent =
7215                    new SendViewStateChangedAccessibilityEvent();
7216        }
7217        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7218    }
7219
7220    /**
7221     * Notifies that the accessibility state of this view changed. The change
7222     * is *not* local to this view and does represent structural changes such
7223     * as children and parent. For example, the view size changed. The
7224     * notification is at at most once every
7225     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7226     * to avoid unnecessary load to the system. Also once a view has a pending
7227     * notifucation this method is a NOP until the notification has been sent.
7228     *
7229     * @hide
7230     */
7231    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7232        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7233            return;
7234        }
7235        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7236            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7237            if (mParent != null) {
7238                try {
7239                    mParent.notifySubtreeAccessibilityStateChanged(
7240                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7241                } catch (AbstractMethodError e) {
7242                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7243                            " does not fully implement ViewParent", e);
7244                }
7245            }
7246        }
7247    }
7248
7249    /**
7250     * Reset the flag indicating the accessibility state of the subtree rooted
7251     * at this view changed.
7252     */
7253    void resetSubtreeAccessibilityStateChanged() {
7254        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7255    }
7256
7257    /**
7258     * Performs the specified accessibility action on the view. For
7259     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7260     * <p>
7261     * If an {@link AccessibilityDelegate} has been specified via calling
7262     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7263     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7264     * is responsible for handling this call.
7265     * </p>
7266     *
7267     * @param action The action to perform.
7268     * @param arguments Optional action arguments.
7269     * @return Whether the action was performed.
7270     */
7271    public boolean performAccessibilityAction(int action, Bundle arguments) {
7272      if (mAccessibilityDelegate != null) {
7273          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7274      } else {
7275          return performAccessibilityActionInternal(action, arguments);
7276      }
7277    }
7278
7279   /**
7280    * @see #performAccessibilityAction(int, Bundle)
7281    *
7282    * Note: Called from the default {@link AccessibilityDelegate}.
7283    */
7284    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7285        switch (action) {
7286            case AccessibilityNodeInfo.ACTION_CLICK: {
7287                if (isClickable()) {
7288                    performClick();
7289                    return true;
7290                }
7291            } break;
7292            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7293                if (isLongClickable()) {
7294                    performLongClick();
7295                    return true;
7296                }
7297            } break;
7298            case AccessibilityNodeInfo.ACTION_FOCUS: {
7299                if (!hasFocus()) {
7300                    // Get out of touch mode since accessibility
7301                    // wants to move focus around.
7302                    getViewRootImpl().ensureTouchMode(false);
7303                    return requestFocus();
7304                }
7305            } break;
7306            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7307                if (hasFocus()) {
7308                    clearFocus();
7309                    return !isFocused();
7310                }
7311            } break;
7312            case AccessibilityNodeInfo.ACTION_SELECT: {
7313                if (!isSelected()) {
7314                    setSelected(true);
7315                    return isSelected();
7316                }
7317            } break;
7318            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7319                if (isSelected()) {
7320                    setSelected(false);
7321                    return !isSelected();
7322                }
7323            } break;
7324            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7325                if (!isAccessibilityFocused()) {
7326                    return requestAccessibilityFocus();
7327                }
7328            } break;
7329            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7330                if (isAccessibilityFocused()) {
7331                    clearAccessibilityFocus();
7332                    return true;
7333                }
7334            } break;
7335            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7336                if (arguments != null) {
7337                    final int granularity = arguments.getInt(
7338                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7339                    final boolean extendSelection = arguments.getBoolean(
7340                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7341                    return traverseAtGranularity(granularity, true, extendSelection);
7342                }
7343            } break;
7344            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7345                if (arguments != null) {
7346                    final int granularity = arguments.getInt(
7347                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7348                    final boolean extendSelection = arguments.getBoolean(
7349                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7350                    return traverseAtGranularity(granularity, false, extendSelection);
7351                }
7352            } break;
7353            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7354                CharSequence text = getIterableTextForAccessibility();
7355                if (text == null) {
7356                    return false;
7357                }
7358                final int start = (arguments != null) ? arguments.getInt(
7359                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7360                final int end = (arguments != null) ? arguments.getInt(
7361                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7362                // Only cursor position can be specified (selection length == 0)
7363                if ((getAccessibilitySelectionStart() != start
7364                        || getAccessibilitySelectionEnd() != end)
7365                        && (start == end)) {
7366                    setAccessibilitySelection(start, end);
7367                    notifyViewAccessibilityStateChangedIfNeeded(
7368                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7369                    return true;
7370                }
7371            } break;
7372        }
7373        return false;
7374    }
7375
7376    private boolean traverseAtGranularity(int granularity, boolean forward,
7377            boolean extendSelection) {
7378        CharSequence text = getIterableTextForAccessibility();
7379        if (text == null || text.length() == 0) {
7380            return false;
7381        }
7382        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7383        if (iterator == null) {
7384            return false;
7385        }
7386        int current = getAccessibilitySelectionEnd();
7387        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7388            current = forward ? 0 : text.length();
7389        }
7390        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7391        if (range == null) {
7392            return false;
7393        }
7394        final int segmentStart = range[0];
7395        final int segmentEnd = range[1];
7396        int selectionStart;
7397        int selectionEnd;
7398        if (extendSelection && isAccessibilitySelectionExtendable()) {
7399            selectionStart = getAccessibilitySelectionStart();
7400            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7401                selectionStart = forward ? segmentStart : segmentEnd;
7402            }
7403            selectionEnd = forward ? segmentEnd : segmentStart;
7404        } else {
7405            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7406        }
7407        setAccessibilitySelection(selectionStart, selectionEnd);
7408        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7409                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7410        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7411        return true;
7412    }
7413
7414    /**
7415     * Gets the text reported for accessibility purposes.
7416     *
7417     * @return The accessibility text.
7418     *
7419     * @hide
7420     */
7421    public CharSequence getIterableTextForAccessibility() {
7422        return getContentDescription();
7423    }
7424
7425    /**
7426     * Gets whether accessibility selection can be extended.
7427     *
7428     * @return If selection is extensible.
7429     *
7430     * @hide
7431     */
7432    public boolean isAccessibilitySelectionExtendable() {
7433        return false;
7434    }
7435
7436    /**
7437     * @hide
7438     */
7439    public int getAccessibilitySelectionStart() {
7440        return mAccessibilityCursorPosition;
7441    }
7442
7443    /**
7444     * @hide
7445     */
7446    public int getAccessibilitySelectionEnd() {
7447        return getAccessibilitySelectionStart();
7448    }
7449
7450    /**
7451     * @hide
7452     */
7453    public void setAccessibilitySelection(int start, int end) {
7454        if (start ==  end && end == mAccessibilityCursorPosition) {
7455            return;
7456        }
7457        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7458            mAccessibilityCursorPosition = start;
7459        } else {
7460            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7461        }
7462        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7463    }
7464
7465    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7466            int fromIndex, int toIndex) {
7467        if (mParent == null) {
7468            return;
7469        }
7470        AccessibilityEvent event = AccessibilityEvent.obtain(
7471                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7472        onInitializeAccessibilityEvent(event);
7473        onPopulateAccessibilityEvent(event);
7474        event.setFromIndex(fromIndex);
7475        event.setToIndex(toIndex);
7476        event.setAction(action);
7477        event.setMovementGranularity(granularity);
7478        mParent.requestSendAccessibilityEvent(this, event);
7479    }
7480
7481    /**
7482     * @hide
7483     */
7484    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7485        switch (granularity) {
7486            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7487                CharSequence text = getIterableTextForAccessibility();
7488                if (text != null && text.length() > 0) {
7489                    CharacterTextSegmentIterator iterator =
7490                        CharacterTextSegmentIterator.getInstance(
7491                                mContext.getResources().getConfiguration().locale);
7492                    iterator.initialize(text.toString());
7493                    return iterator;
7494                }
7495            } break;
7496            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7497                CharSequence text = getIterableTextForAccessibility();
7498                if (text != null && text.length() > 0) {
7499                    WordTextSegmentIterator iterator =
7500                        WordTextSegmentIterator.getInstance(
7501                                mContext.getResources().getConfiguration().locale);
7502                    iterator.initialize(text.toString());
7503                    return iterator;
7504                }
7505            } break;
7506            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7507                CharSequence text = getIterableTextForAccessibility();
7508                if (text != null && text.length() > 0) {
7509                    ParagraphTextSegmentIterator iterator =
7510                        ParagraphTextSegmentIterator.getInstance();
7511                    iterator.initialize(text.toString());
7512                    return iterator;
7513                }
7514            } break;
7515        }
7516        return null;
7517    }
7518
7519    /**
7520     * @hide
7521     */
7522    public void dispatchStartTemporaryDetach() {
7523        clearDisplayList();
7524
7525        onStartTemporaryDetach();
7526    }
7527
7528    /**
7529     * This is called when a container is going to temporarily detach a child, with
7530     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7531     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7532     * {@link #onDetachedFromWindow()} when the container is done.
7533     */
7534    public void onStartTemporaryDetach() {
7535        removeUnsetPressCallback();
7536        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7537    }
7538
7539    /**
7540     * @hide
7541     */
7542    public void dispatchFinishTemporaryDetach() {
7543        onFinishTemporaryDetach();
7544    }
7545
7546    /**
7547     * Called after {@link #onStartTemporaryDetach} when the container is done
7548     * changing the view.
7549     */
7550    public void onFinishTemporaryDetach() {
7551    }
7552
7553    /**
7554     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7555     * for this view's window.  Returns null if the view is not currently attached
7556     * to the window.  Normally you will not need to use this directly, but
7557     * just use the standard high-level event callbacks like
7558     * {@link #onKeyDown(int, KeyEvent)}.
7559     */
7560    public KeyEvent.DispatcherState getKeyDispatcherState() {
7561        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7562    }
7563
7564    /**
7565     * Dispatch a key event before it is processed by any input method
7566     * associated with the view hierarchy.  This can be used to intercept
7567     * key events in special situations before the IME consumes them; a
7568     * typical example would be handling the BACK key to update the application's
7569     * UI instead of allowing the IME to see it and close itself.
7570     *
7571     * @param event The key event to be dispatched.
7572     * @return True if the event was handled, false otherwise.
7573     */
7574    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7575        return onKeyPreIme(event.getKeyCode(), event);
7576    }
7577
7578    /**
7579     * Dispatch a key event to the next view on the focus path. This path runs
7580     * from the top of the view tree down to the currently focused view. If this
7581     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7582     * the next node down the focus path. This method also fires any key
7583     * listeners.
7584     *
7585     * @param event The key event to be dispatched.
7586     * @return True if the event was handled, false otherwise.
7587     */
7588    public boolean dispatchKeyEvent(KeyEvent event) {
7589        if (mInputEventConsistencyVerifier != null) {
7590            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7591        }
7592
7593        // Give any attached key listener a first crack at the event.
7594        //noinspection SimplifiableIfStatement
7595        ListenerInfo li = mListenerInfo;
7596        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7597                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7598            return true;
7599        }
7600
7601        if (event.dispatch(this, mAttachInfo != null
7602                ? mAttachInfo.mKeyDispatchState : null, this)) {
7603            return true;
7604        }
7605
7606        if (mInputEventConsistencyVerifier != null) {
7607            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7608        }
7609        return false;
7610    }
7611
7612    /**
7613     * Dispatches a key shortcut event.
7614     *
7615     * @param event The key event to be dispatched.
7616     * @return True if the event was handled by the view, false otherwise.
7617     */
7618    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7619        return onKeyShortcut(event.getKeyCode(), event);
7620    }
7621
7622    /**
7623     * Pass the touch screen motion event down to the target view, or this
7624     * view if it is the target.
7625     *
7626     * @param event The motion event to be dispatched.
7627     * @return True if the event was handled by the view, false otherwise.
7628     */
7629    public boolean dispatchTouchEvent(MotionEvent event) {
7630        if (mInputEventConsistencyVerifier != null) {
7631            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7632        }
7633
7634        if (onFilterTouchEventForSecurity(event)) {
7635            //noinspection SimplifiableIfStatement
7636            ListenerInfo li = mListenerInfo;
7637            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7638                    && li.mOnTouchListener.onTouch(this, event)) {
7639                return true;
7640            }
7641
7642            if (onTouchEvent(event)) {
7643                return true;
7644            }
7645        }
7646
7647        if (mInputEventConsistencyVerifier != null) {
7648            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7649        }
7650        return false;
7651    }
7652
7653    /**
7654     * Filter the touch event to apply security policies.
7655     *
7656     * @param event The motion event to be filtered.
7657     * @return True if the event should be dispatched, false if the event should be dropped.
7658     *
7659     * @see #getFilterTouchesWhenObscured
7660     */
7661    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7662        //noinspection RedundantIfStatement
7663        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7664                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7665            // Window is obscured, drop this touch.
7666            return false;
7667        }
7668        return true;
7669    }
7670
7671    /**
7672     * Pass a trackball motion event down to the focused view.
7673     *
7674     * @param event The motion event to be dispatched.
7675     * @return True if the event was handled by the view, false otherwise.
7676     */
7677    public boolean dispatchTrackballEvent(MotionEvent event) {
7678        if (mInputEventConsistencyVerifier != null) {
7679            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7680        }
7681
7682        return onTrackballEvent(event);
7683    }
7684
7685    /**
7686     * Dispatch a generic motion event.
7687     * <p>
7688     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7689     * are delivered to the view under the pointer.  All other generic motion events are
7690     * delivered to the focused view.  Hover events are handled specially and are delivered
7691     * to {@link #onHoverEvent(MotionEvent)}.
7692     * </p>
7693     *
7694     * @param event The motion event to be dispatched.
7695     * @return True if the event was handled by the view, false otherwise.
7696     */
7697    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7698        if (mInputEventConsistencyVerifier != null) {
7699            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7700        }
7701
7702        final int source = event.getSource();
7703        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7704            final int action = event.getAction();
7705            if (action == MotionEvent.ACTION_HOVER_ENTER
7706                    || action == MotionEvent.ACTION_HOVER_MOVE
7707                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7708                if (dispatchHoverEvent(event)) {
7709                    return true;
7710                }
7711            } else if (dispatchGenericPointerEvent(event)) {
7712                return true;
7713            }
7714        } else if (dispatchGenericFocusedEvent(event)) {
7715            return true;
7716        }
7717
7718        if (dispatchGenericMotionEventInternal(event)) {
7719            return true;
7720        }
7721
7722        if (mInputEventConsistencyVerifier != null) {
7723            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7724        }
7725        return false;
7726    }
7727
7728    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7729        //noinspection SimplifiableIfStatement
7730        ListenerInfo li = mListenerInfo;
7731        if (li != null && li.mOnGenericMotionListener != null
7732                && (mViewFlags & ENABLED_MASK) == ENABLED
7733                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7734            return true;
7735        }
7736
7737        if (onGenericMotionEvent(event)) {
7738            return true;
7739        }
7740
7741        if (mInputEventConsistencyVerifier != null) {
7742            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7743        }
7744        return false;
7745    }
7746
7747    /**
7748     * Dispatch a hover event.
7749     * <p>
7750     * Do not call this method directly.
7751     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7752     * </p>
7753     *
7754     * @param event The motion event to be dispatched.
7755     * @return True if the event was handled by the view, false otherwise.
7756     */
7757    protected boolean dispatchHoverEvent(MotionEvent event) {
7758        ListenerInfo li = mListenerInfo;
7759        //noinspection SimplifiableIfStatement
7760        if (li != null && li.mOnHoverListener != null
7761                && (mViewFlags & ENABLED_MASK) == ENABLED
7762                && li.mOnHoverListener.onHover(this, event)) {
7763            return true;
7764        }
7765
7766        return onHoverEvent(event);
7767    }
7768
7769    /**
7770     * Returns true if the view has a child to which it has recently sent
7771     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7772     * it does not have a hovered child, then it must be the innermost hovered view.
7773     * @hide
7774     */
7775    protected boolean hasHoveredChild() {
7776        return false;
7777    }
7778
7779    /**
7780     * Dispatch a generic motion event to the view under the first pointer.
7781     * <p>
7782     * Do not call this method directly.
7783     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7784     * </p>
7785     *
7786     * @param event The motion event to be dispatched.
7787     * @return True if the event was handled by the view, false otherwise.
7788     */
7789    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7790        return false;
7791    }
7792
7793    /**
7794     * Dispatch a generic motion event to the currently focused view.
7795     * <p>
7796     * Do not call this method directly.
7797     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7798     * </p>
7799     *
7800     * @param event The motion event to be dispatched.
7801     * @return True if the event was handled by the view, false otherwise.
7802     */
7803    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7804        return false;
7805    }
7806
7807    /**
7808     * Dispatch a pointer event.
7809     * <p>
7810     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7811     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7812     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7813     * and should not be expected to handle other pointing device features.
7814     * </p>
7815     *
7816     * @param event The motion event to be dispatched.
7817     * @return True if the event was handled by the view, false otherwise.
7818     * @hide
7819     */
7820    public final boolean dispatchPointerEvent(MotionEvent event) {
7821        if (event.isTouchEvent()) {
7822            return dispatchTouchEvent(event);
7823        } else {
7824            return dispatchGenericMotionEvent(event);
7825        }
7826    }
7827
7828    /**
7829     * Called when the window containing this view gains or loses window focus.
7830     * ViewGroups should override to route to their children.
7831     *
7832     * @param hasFocus True if the window containing this view now has focus,
7833     *        false otherwise.
7834     */
7835    public void dispatchWindowFocusChanged(boolean hasFocus) {
7836        onWindowFocusChanged(hasFocus);
7837    }
7838
7839    /**
7840     * Called when the window containing this view gains or loses focus.  Note
7841     * that this is separate from view focus: to receive key events, both
7842     * your view and its window must have focus.  If a window is displayed
7843     * on top of yours that takes input focus, then your own window will lose
7844     * focus but the view focus will remain unchanged.
7845     *
7846     * @param hasWindowFocus True if the window containing this view now has
7847     *        focus, false otherwise.
7848     */
7849    public void onWindowFocusChanged(boolean hasWindowFocus) {
7850        InputMethodManager imm = InputMethodManager.peekInstance();
7851        if (!hasWindowFocus) {
7852            if (isPressed()) {
7853                setPressed(false);
7854            }
7855            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7856                imm.focusOut(this);
7857            }
7858            removeLongPressCallback();
7859            removeTapCallback();
7860            onFocusLost();
7861        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7862            imm.focusIn(this);
7863        }
7864        refreshDrawableState();
7865    }
7866
7867    /**
7868     * Returns true if this view is in a window that currently has window focus.
7869     * Note that this is not the same as the view itself having focus.
7870     *
7871     * @return True if this view is in a window that currently has window focus.
7872     */
7873    public boolean hasWindowFocus() {
7874        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7875    }
7876
7877    /**
7878     * Dispatch a view visibility change down the view hierarchy.
7879     * ViewGroups should override to route to their children.
7880     * @param changedView The view whose visibility changed. Could be 'this' or
7881     * an ancestor view.
7882     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7883     * {@link #INVISIBLE} or {@link #GONE}.
7884     */
7885    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7886        onVisibilityChanged(changedView, visibility);
7887    }
7888
7889    /**
7890     * Called when the visibility of the view or an ancestor of the view is changed.
7891     * @param changedView The view whose visibility changed. Could be 'this' or
7892     * an ancestor view.
7893     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7894     * {@link #INVISIBLE} or {@link #GONE}.
7895     */
7896    protected void onVisibilityChanged(View changedView, int visibility) {
7897        if (visibility == VISIBLE) {
7898            if (mAttachInfo != null) {
7899                initialAwakenScrollBars();
7900            } else {
7901                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7902            }
7903        }
7904    }
7905
7906    /**
7907     * Dispatch a hint about whether this view is displayed. For instance, when
7908     * a View moves out of the screen, it might receives a display hint indicating
7909     * the view is not displayed. Applications should not <em>rely</em> on this hint
7910     * as there is no guarantee that they will receive one.
7911     *
7912     * @param hint A hint about whether or not this view is displayed:
7913     * {@link #VISIBLE} or {@link #INVISIBLE}.
7914     */
7915    public void dispatchDisplayHint(int hint) {
7916        onDisplayHint(hint);
7917    }
7918
7919    /**
7920     * Gives this view a hint about whether is displayed or not. For instance, when
7921     * a View moves out of the screen, it might receives a display hint indicating
7922     * the view is not displayed. Applications should not <em>rely</em> on this hint
7923     * as there is no guarantee that they will receive one.
7924     *
7925     * @param hint A hint about whether or not this view is displayed:
7926     * {@link #VISIBLE} or {@link #INVISIBLE}.
7927     */
7928    protected void onDisplayHint(int hint) {
7929    }
7930
7931    /**
7932     * Dispatch a window visibility change down the view hierarchy.
7933     * ViewGroups should override to route to their children.
7934     *
7935     * @param visibility The new visibility of the window.
7936     *
7937     * @see #onWindowVisibilityChanged(int)
7938     */
7939    public void dispatchWindowVisibilityChanged(int visibility) {
7940        onWindowVisibilityChanged(visibility);
7941    }
7942
7943    /**
7944     * Called when the window containing has change its visibility
7945     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7946     * that this tells you whether or not your window is being made visible
7947     * to the window manager; this does <em>not</em> tell you whether or not
7948     * your window is obscured by other windows on the screen, even if it
7949     * is itself visible.
7950     *
7951     * @param visibility The new visibility of the window.
7952     */
7953    protected void onWindowVisibilityChanged(int visibility) {
7954        if (visibility == VISIBLE) {
7955            initialAwakenScrollBars();
7956        }
7957    }
7958
7959    /**
7960     * Returns the current visibility of the window this view is attached to
7961     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7962     *
7963     * @return Returns the current visibility of the view's window.
7964     */
7965    public int getWindowVisibility() {
7966        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7967    }
7968
7969    /**
7970     * Retrieve the overall visible display size in which the window this view is
7971     * attached to has been positioned in.  This takes into account screen
7972     * decorations above the window, for both cases where the window itself
7973     * is being position inside of them or the window is being placed under
7974     * then and covered insets are used for the window to position its content
7975     * inside.  In effect, this tells you the available area where content can
7976     * be placed and remain visible to users.
7977     *
7978     * <p>This function requires an IPC back to the window manager to retrieve
7979     * the requested information, so should not be used in performance critical
7980     * code like drawing.
7981     *
7982     * @param outRect Filled in with the visible display frame.  If the view
7983     * is not attached to a window, this is simply the raw display size.
7984     */
7985    public void getWindowVisibleDisplayFrame(Rect outRect) {
7986        if (mAttachInfo != null) {
7987            try {
7988                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7989            } catch (RemoteException e) {
7990                return;
7991            }
7992            // XXX This is really broken, and probably all needs to be done
7993            // in the window manager, and we need to know more about whether
7994            // we want the area behind or in front of the IME.
7995            final Rect insets = mAttachInfo.mVisibleInsets;
7996            outRect.left += insets.left;
7997            outRect.top += insets.top;
7998            outRect.right -= insets.right;
7999            outRect.bottom -= insets.bottom;
8000            return;
8001        }
8002        // The view is not attached to a display so we don't have a context.
8003        // Make a best guess about the display size.
8004        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8005        d.getRectSize(outRect);
8006    }
8007
8008    /**
8009     * Dispatch a notification about a resource configuration change down
8010     * the view hierarchy.
8011     * ViewGroups should override to route to their children.
8012     *
8013     * @param newConfig The new resource configuration.
8014     *
8015     * @see #onConfigurationChanged(android.content.res.Configuration)
8016     */
8017    public void dispatchConfigurationChanged(Configuration newConfig) {
8018        onConfigurationChanged(newConfig);
8019    }
8020
8021    /**
8022     * Called when the current configuration of the resources being used
8023     * by the application have changed.  You can use this to decide when
8024     * to reload resources that can changed based on orientation and other
8025     * configuration characterstics.  You only need to use this if you are
8026     * not relying on the normal {@link android.app.Activity} mechanism of
8027     * recreating the activity instance upon a configuration change.
8028     *
8029     * @param newConfig The new resource configuration.
8030     */
8031    protected void onConfigurationChanged(Configuration newConfig) {
8032    }
8033
8034    /**
8035     * Private function to aggregate all per-view attributes in to the view
8036     * root.
8037     */
8038    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8039        performCollectViewAttributes(attachInfo, visibility);
8040    }
8041
8042    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8043        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8044            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8045                attachInfo.mKeepScreenOn = true;
8046            }
8047            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8048            ListenerInfo li = mListenerInfo;
8049            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8050                attachInfo.mHasSystemUiListeners = true;
8051            }
8052        }
8053    }
8054
8055    void needGlobalAttributesUpdate(boolean force) {
8056        final AttachInfo ai = mAttachInfo;
8057        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8058            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8059                    || ai.mHasSystemUiListeners) {
8060                ai.mRecomputeGlobalAttributes = true;
8061            }
8062        }
8063    }
8064
8065    /**
8066     * Returns whether the device is currently in touch mode.  Touch mode is entered
8067     * once the user begins interacting with the device by touch, and affects various
8068     * things like whether focus is always visible to the user.
8069     *
8070     * @return Whether the device is in touch mode.
8071     */
8072    @ViewDebug.ExportedProperty
8073    public boolean isInTouchMode() {
8074        if (mAttachInfo != null) {
8075            return mAttachInfo.mInTouchMode;
8076        } else {
8077            return ViewRootImpl.isInTouchMode();
8078        }
8079    }
8080
8081    /**
8082     * Returns the context the view is running in, through which it can
8083     * access the current theme, resources, etc.
8084     *
8085     * @return The view's Context.
8086     */
8087    @ViewDebug.CapturedViewProperty
8088    public final Context getContext() {
8089        return mContext;
8090    }
8091
8092    /**
8093     * Handle a key event before it is processed by any input method
8094     * associated with the view hierarchy.  This can be used to intercept
8095     * key events in special situations before the IME consumes them; a
8096     * typical example would be handling the BACK key to update the application's
8097     * UI instead of allowing the IME to see it and close itself.
8098     *
8099     * @param keyCode The value in event.getKeyCode().
8100     * @param event Description of the key event.
8101     * @return If you handled the event, return true. If you want to allow the
8102     *         event to be handled by the next receiver, return false.
8103     */
8104    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8105        return false;
8106    }
8107
8108    /**
8109     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8110     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8111     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8112     * is released, if the view is enabled and clickable.
8113     *
8114     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8115     * although some may elect to do so in some situations. Do not rely on this to
8116     * catch software key presses.
8117     *
8118     * @param keyCode A key code that represents the button pressed, from
8119     *                {@link android.view.KeyEvent}.
8120     * @param event   The KeyEvent object that defines the button action.
8121     */
8122    public boolean onKeyDown(int keyCode, KeyEvent event) {
8123        boolean result = false;
8124
8125        if (KeyEvent.isConfirmKey(keyCode)) {
8126            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8127                return true;
8128            }
8129            // Long clickable items don't necessarily have to be clickable
8130            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8131                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8132                    (event.getRepeatCount() == 0)) {
8133                setPressed(true);
8134                checkForLongClick(0);
8135                return true;
8136            }
8137        }
8138        return result;
8139    }
8140
8141    /**
8142     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8143     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8144     * the event).
8145     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8146     * although some may elect to do so in some situations. Do not rely on this to
8147     * catch software key presses.
8148     */
8149    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8150        return false;
8151    }
8152
8153    /**
8154     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8155     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8156     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8157     * {@link KeyEvent#KEYCODE_ENTER} is released.
8158     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8159     * although some may elect to do so in some situations. Do not rely on this to
8160     * catch software key presses.
8161     *
8162     * @param keyCode A key code that represents the button pressed, from
8163     *                {@link android.view.KeyEvent}.
8164     * @param event   The KeyEvent object that defines the button action.
8165     */
8166    public boolean onKeyUp(int keyCode, KeyEvent event) {
8167        if (KeyEvent.isConfirmKey(keyCode)) {
8168            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8169                return true;
8170            }
8171            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8172                setPressed(false);
8173
8174                if (!mHasPerformedLongPress) {
8175                    // This is a tap, so remove the longpress check
8176                    removeLongPressCallback();
8177                    return performClick();
8178                }
8179            }
8180        }
8181        return false;
8182    }
8183
8184    /**
8185     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8186     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8187     * the event).
8188     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8189     * although some may elect to do so in some situations. Do not rely on this to
8190     * catch software key presses.
8191     *
8192     * @param keyCode     A key code that represents the button pressed, from
8193     *                    {@link android.view.KeyEvent}.
8194     * @param repeatCount The number of times the action was made.
8195     * @param event       The KeyEvent object that defines the button action.
8196     */
8197    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8198        return false;
8199    }
8200
8201    /**
8202     * Called on the focused view when a key shortcut event is not handled.
8203     * Override this method to implement local key shortcuts for the View.
8204     * Key shortcuts can also be implemented by setting the
8205     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8206     *
8207     * @param keyCode The value in event.getKeyCode().
8208     * @param event Description of the key event.
8209     * @return If you handled the event, return true. If you want to allow the
8210     *         event to be handled by the next receiver, return false.
8211     */
8212    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8213        return false;
8214    }
8215
8216    /**
8217     * Check whether the called view is a text editor, in which case it
8218     * would make sense to automatically display a soft input window for
8219     * it.  Subclasses should override this if they implement
8220     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8221     * a call on that method would return a non-null InputConnection, and
8222     * they are really a first-class editor that the user would normally
8223     * start typing on when the go into a window containing your view.
8224     *
8225     * <p>The default implementation always returns false.  This does
8226     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8227     * will not be called or the user can not otherwise perform edits on your
8228     * view; it is just a hint to the system that this is not the primary
8229     * purpose of this view.
8230     *
8231     * @return Returns true if this view is a text editor, else false.
8232     */
8233    public boolean onCheckIsTextEditor() {
8234        return false;
8235    }
8236
8237    /**
8238     * Create a new InputConnection for an InputMethod to interact
8239     * with the view.  The default implementation returns null, since it doesn't
8240     * support input methods.  You can override this to implement such support.
8241     * This is only needed for views that take focus and text input.
8242     *
8243     * <p>When implementing this, you probably also want to implement
8244     * {@link #onCheckIsTextEditor()} to indicate you will return a
8245     * non-null InputConnection.
8246     *
8247     * @param outAttrs Fill in with attribute information about the connection.
8248     */
8249    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8250        return null;
8251    }
8252
8253    /**
8254     * Called by the {@link android.view.inputmethod.InputMethodManager}
8255     * when a view who is not the current
8256     * input connection target is trying to make a call on the manager.  The
8257     * default implementation returns false; you can override this to return
8258     * true for certain views if you are performing InputConnection proxying
8259     * to them.
8260     * @param view The View that is making the InputMethodManager call.
8261     * @return Return true to allow the call, false to reject.
8262     */
8263    public boolean checkInputConnectionProxy(View view) {
8264        return false;
8265    }
8266
8267    /**
8268     * Show the context menu for this view. It is not safe to hold on to the
8269     * menu after returning from this method.
8270     *
8271     * You should normally not overload this method. Overload
8272     * {@link #onCreateContextMenu(ContextMenu)} or define an
8273     * {@link OnCreateContextMenuListener} to add items to the context menu.
8274     *
8275     * @param menu The context menu to populate
8276     */
8277    public void createContextMenu(ContextMenu menu) {
8278        ContextMenuInfo menuInfo = getContextMenuInfo();
8279
8280        // Sets the current menu info so all items added to menu will have
8281        // my extra info set.
8282        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8283
8284        onCreateContextMenu(menu);
8285        ListenerInfo li = mListenerInfo;
8286        if (li != null && li.mOnCreateContextMenuListener != null) {
8287            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8288        }
8289
8290        // Clear the extra information so subsequent items that aren't mine don't
8291        // have my extra info.
8292        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8293
8294        if (mParent != null) {
8295            mParent.createContextMenu(menu);
8296        }
8297    }
8298
8299    /**
8300     * Views should implement this if they have extra information to associate
8301     * with the context menu. The return result is supplied as a parameter to
8302     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8303     * callback.
8304     *
8305     * @return Extra information about the item for which the context menu
8306     *         should be shown. This information will vary across different
8307     *         subclasses of View.
8308     */
8309    protected ContextMenuInfo getContextMenuInfo() {
8310        return null;
8311    }
8312
8313    /**
8314     * Views should implement this if the view itself is going to add items to
8315     * the context menu.
8316     *
8317     * @param menu the context menu to populate
8318     */
8319    protected void onCreateContextMenu(ContextMenu menu) {
8320    }
8321
8322    /**
8323     * Implement this method to handle trackball motion events.  The
8324     * <em>relative</em> movement of the trackball since the last event
8325     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8326     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8327     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8328     * they will often be fractional values, representing the more fine-grained
8329     * movement information available from a trackball).
8330     *
8331     * @param event The motion event.
8332     * @return True if the event was handled, false otherwise.
8333     */
8334    public boolean onTrackballEvent(MotionEvent event) {
8335        return false;
8336    }
8337
8338    /**
8339     * Implement this method to handle generic motion events.
8340     * <p>
8341     * Generic motion events describe joystick movements, mouse hovers, track pad
8342     * touches, scroll wheel movements and other input events.  The
8343     * {@link MotionEvent#getSource() source} of the motion event specifies
8344     * the class of input that was received.  Implementations of this method
8345     * must examine the bits in the source before processing the event.
8346     * The following code example shows how this is done.
8347     * </p><p>
8348     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8349     * are delivered to the view under the pointer.  All other generic motion events are
8350     * delivered to the focused view.
8351     * </p>
8352     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8353     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8354     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8355     *             // process the joystick movement...
8356     *             return true;
8357     *         }
8358     *     }
8359     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8360     *         switch (event.getAction()) {
8361     *             case MotionEvent.ACTION_HOVER_MOVE:
8362     *                 // process the mouse hover movement...
8363     *                 return true;
8364     *             case MotionEvent.ACTION_SCROLL:
8365     *                 // process the scroll wheel movement...
8366     *                 return true;
8367     *         }
8368     *     }
8369     *     return super.onGenericMotionEvent(event);
8370     * }</pre>
8371     *
8372     * @param event The generic motion event being processed.
8373     * @return True if the event was handled, false otherwise.
8374     */
8375    public boolean onGenericMotionEvent(MotionEvent event) {
8376        return false;
8377    }
8378
8379    /**
8380     * Implement this method to handle hover events.
8381     * <p>
8382     * This method is called whenever a pointer is hovering into, over, or out of the
8383     * bounds of a view and the view is not currently being touched.
8384     * Hover events are represented as pointer events with action
8385     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8386     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8387     * </p>
8388     * <ul>
8389     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8390     * when the pointer enters the bounds of the view.</li>
8391     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8392     * when the pointer has already entered the bounds of the view and has moved.</li>
8393     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8394     * when the pointer has exited the bounds of the view or when the pointer is
8395     * about to go down due to a button click, tap, or similar user action that
8396     * causes the view to be touched.</li>
8397     * </ul>
8398     * <p>
8399     * The view should implement this method to return true to indicate that it is
8400     * handling the hover event, such as by changing its drawable state.
8401     * </p><p>
8402     * The default implementation calls {@link #setHovered} to update the hovered state
8403     * of the view when a hover enter or hover exit event is received, if the view
8404     * is enabled and is clickable.  The default implementation also sends hover
8405     * accessibility events.
8406     * </p>
8407     *
8408     * @param event The motion event that describes the hover.
8409     * @return True if the view handled the hover event.
8410     *
8411     * @see #isHovered
8412     * @see #setHovered
8413     * @see #onHoverChanged
8414     */
8415    public boolean onHoverEvent(MotionEvent event) {
8416        // The root view may receive hover (or touch) events that are outside the bounds of
8417        // the window.  This code ensures that we only send accessibility events for
8418        // hovers that are actually within the bounds of the root view.
8419        final int action = event.getActionMasked();
8420        if (!mSendingHoverAccessibilityEvents) {
8421            if ((action == MotionEvent.ACTION_HOVER_ENTER
8422                    || action == MotionEvent.ACTION_HOVER_MOVE)
8423                    && !hasHoveredChild()
8424                    && pointInView(event.getX(), event.getY())) {
8425                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8426                mSendingHoverAccessibilityEvents = true;
8427            }
8428        } else {
8429            if (action == MotionEvent.ACTION_HOVER_EXIT
8430                    || (action == MotionEvent.ACTION_MOVE
8431                            && !pointInView(event.getX(), event.getY()))) {
8432                mSendingHoverAccessibilityEvents = false;
8433                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8434                // If the window does not have input focus we take away accessibility
8435                // focus as soon as the user stop hovering over the view.
8436                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8437                    getViewRootImpl().setAccessibilityFocus(null, null);
8438                }
8439            }
8440        }
8441
8442        if (isHoverable()) {
8443            switch (action) {
8444                case MotionEvent.ACTION_HOVER_ENTER:
8445                    setHovered(true);
8446                    break;
8447                case MotionEvent.ACTION_HOVER_EXIT:
8448                    setHovered(false);
8449                    break;
8450            }
8451
8452            // Dispatch the event to onGenericMotionEvent before returning true.
8453            // This is to provide compatibility with existing applications that
8454            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8455            // break because of the new default handling for hoverable views
8456            // in onHoverEvent.
8457            // Note that onGenericMotionEvent will be called by default when
8458            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8459            dispatchGenericMotionEventInternal(event);
8460            // The event was already handled by calling setHovered(), so always
8461            // return true.
8462            return true;
8463        }
8464
8465        return false;
8466    }
8467
8468    /**
8469     * Returns true if the view should handle {@link #onHoverEvent}
8470     * by calling {@link #setHovered} to change its hovered state.
8471     *
8472     * @return True if the view is hoverable.
8473     */
8474    private boolean isHoverable() {
8475        final int viewFlags = mViewFlags;
8476        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8477            return false;
8478        }
8479
8480        return (viewFlags & CLICKABLE) == CLICKABLE
8481                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8482    }
8483
8484    /**
8485     * Returns true if the view is currently hovered.
8486     *
8487     * @return True if the view is currently hovered.
8488     *
8489     * @see #setHovered
8490     * @see #onHoverChanged
8491     */
8492    @ViewDebug.ExportedProperty
8493    public boolean isHovered() {
8494        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8495    }
8496
8497    /**
8498     * Sets whether the view is currently hovered.
8499     * <p>
8500     * Calling this method also changes the drawable state of the view.  This
8501     * enables the view to react to hover by using different drawable resources
8502     * to change its appearance.
8503     * </p><p>
8504     * The {@link #onHoverChanged} method is called when the hovered state changes.
8505     * </p>
8506     *
8507     * @param hovered True if the view is hovered.
8508     *
8509     * @see #isHovered
8510     * @see #onHoverChanged
8511     */
8512    public void setHovered(boolean hovered) {
8513        if (hovered) {
8514            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8515                mPrivateFlags |= PFLAG_HOVERED;
8516                refreshDrawableState();
8517                onHoverChanged(true);
8518            }
8519        } else {
8520            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8521                mPrivateFlags &= ~PFLAG_HOVERED;
8522                refreshDrawableState();
8523                onHoverChanged(false);
8524            }
8525        }
8526    }
8527
8528    /**
8529     * Implement this method to handle hover state changes.
8530     * <p>
8531     * This method is called whenever the hover state changes as a result of a
8532     * call to {@link #setHovered}.
8533     * </p>
8534     *
8535     * @param hovered The current hover state, as returned by {@link #isHovered}.
8536     *
8537     * @see #isHovered
8538     * @see #setHovered
8539     */
8540    public void onHoverChanged(boolean hovered) {
8541    }
8542
8543    /**
8544     * Implement this method to handle touch screen motion events.
8545     * <p>
8546     * If this method is used to detect click actions, it is recommended that
8547     * the actions be performed by implementing and calling
8548     * {@link #performClick()}. This will ensure consistent system behavior,
8549     * including:
8550     * <ul>
8551     * <li>obeying click sound preferences
8552     * <li>dispatching OnClickListener calls
8553     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
8554     * accessibility features are enabled
8555     * </ul>
8556     *
8557     * @param event The motion event.
8558     * @return True if the event was handled, false otherwise.
8559     */
8560    public boolean onTouchEvent(MotionEvent event) {
8561        final int viewFlags = mViewFlags;
8562
8563        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8564            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8565                setPressed(false);
8566            }
8567            // A disabled view that is clickable still consumes the touch
8568            // events, it just doesn't respond to them.
8569            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8570                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8571        }
8572
8573        if (mTouchDelegate != null) {
8574            if (mTouchDelegate.onTouchEvent(event)) {
8575                return true;
8576            }
8577        }
8578
8579        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8580                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8581            switch (event.getAction()) {
8582                case MotionEvent.ACTION_UP:
8583                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8584                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8585                        // take focus if we don't have it already and we should in
8586                        // touch mode.
8587                        boolean focusTaken = false;
8588                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8589                            focusTaken = requestFocus();
8590                        }
8591
8592                        if (prepressed) {
8593                            // The button is being released before we actually
8594                            // showed it as pressed.  Make it show the pressed
8595                            // state now (before scheduling the click) to ensure
8596                            // the user sees it.
8597                            setPressed(true);
8598                       }
8599
8600                        if (!mHasPerformedLongPress) {
8601                            // This is a tap, so remove the longpress check
8602                            removeLongPressCallback();
8603
8604                            // Only perform take click actions if we were in the pressed state
8605                            if (!focusTaken) {
8606                                // Use a Runnable and post this rather than calling
8607                                // performClick directly. This lets other visual state
8608                                // of the view update before click actions start.
8609                                if (mPerformClick == null) {
8610                                    mPerformClick = new PerformClick();
8611                                }
8612                                if (!post(mPerformClick)) {
8613                                    performClick();
8614                                }
8615                            }
8616                        }
8617
8618                        if (mUnsetPressedState == null) {
8619                            mUnsetPressedState = new UnsetPressedState();
8620                        }
8621
8622                        if (prepressed) {
8623                            postDelayed(mUnsetPressedState,
8624                                    ViewConfiguration.getPressedStateDuration());
8625                        } else if (!post(mUnsetPressedState)) {
8626                            // If the post failed, unpress right now
8627                            mUnsetPressedState.run();
8628                        }
8629                        removeTapCallback();
8630                    }
8631                    break;
8632
8633                case MotionEvent.ACTION_DOWN:
8634                    mHasPerformedLongPress = false;
8635
8636                    if (performButtonActionOnTouchDown(event)) {
8637                        break;
8638                    }
8639
8640                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8641                    boolean isInScrollingContainer = isInScrollingContainer();
8642
8643                    // For views inside a scrolling container, delay the pressed feedback for
8644                    // a short period in case this is a scroll.
8645                    if (isInScrollingContainer) {
8646                        mPrivateFlags |= PFLAG_PREPRESSED;
8647                        if (mPendingCheckForTap == null) {
8648                            mPendingCheckForTap = new CheckForTap();
8649                        }
8650                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8651                    } else {
8652                        // Not inside a scrolling container, so show the feedback right away
8653                        setPressed(true);
8654                        checkForLongClick(0);
8655                    }
8656                    break;
8657
8658                case MotionEvent.ACTION_CANCEL:
8659                    setPressed(false);
8660                    removeTapCallback();
8661                    removeLongPressCallback();
8662                    break;
8663
8664                case MotionEvent.ACTION_MOVE:
8665                    final int x = (int) event.getX();
8666                    final int y = (int) event.getY();
8667
8668                    // Be lenient about moving outside of buttons
8669                    if (!pointInView(x, y, mTouchSlop)) {
8670                        // Outside button
8671                        removeTapCallback();
8672                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8673                            // Remove any future long press/tap checks
8674                            removeLongPressCallback();
8675
8676                            setPressed(false);
8677                        }
8678                    }
8679                    break;
8680            }
8681            return true;
8682        }
8683
8684        return false;
8685    }
8686
8687    /**
8688     * @hide
8689     */
8690    public boolean isInScrollingContainer() {
8691        ViewParent p = getParent();
8692        while (p != null && p instanceof ViewGroup) {
8693            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8694                return true;
8695            }
8696            p = p.getParent();
8697        }
8698        return false;
8699    }
8700
8701    /**
8702     * Remove the longpress detection timer.
8703     */
8704    private void removeLongPressCallback() {
8705        if (mPendingCheckForLongPress != null) {
8706          removeCallbacks(mPendingCheckForLongPress);
8707        }
8708    }
8709
8710    /**
8711     * Remove the pending click action
8712     */
8713    private void removePerformClickCallback() {
8714        if (mPerformClick != null) {
8715            removeCallbacks(mPerformClick);
8716        }
8717    }
8718
8719    /**
8720     * Remove the prepress detection timer.
8721     */
8722    private void removeUnsetPressCallback() {
8723        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8724            setPressed(false);
8725            removeCallbacks(mUnsetPressedState);
8726        }
8727    }
8728
8729    /**
8730     * Remove the tap detection timer.
8731     */
8732    private void removeTapCallback() {
8733        if (mPendingCheckForTap != null) {
8734            mPrivateFlags &= ~PFLAG_PREPRESSED;
8735            removeCallbacks(mPendingCheckForTap);
8736        }
8737    }
8738
8739    /**
8740     * Cancels a pending long press.  Your subclass can use this if you
8741     * want the context menu to come up if the user presses and holds
8742     * at the same place, but you don't want it to come up if they press
8743     * and then move around enough to cause scrolling.
8744     */
8745    public void cancelLongPress() {
8746        removeLongPressCallback();
8747
8748        /*
8749         * The prepressed state handled by the tap callback is a display
8750         * construct, but the tap callback will post a long press callback
8751         * less its own timeout. Remove it here.
8752         */
8753        removeTapCallback();
8754    }
8755
8756    /**
8757     * Remove the pending callback for sending a
8758     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8759     */
8760    private void removeSendViewScrolledAccessibilityEventCallback() {
8761        if (mSendViewScrolledAccessibilityEvent != null) {
8762            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8763            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8764        }
8765    }
8766
8767    /**
8768     * Sets the TouchDelegate for this View.
8769     */
8770    public void setTouchDelegate(TouchDelegate delegate) {
8771        mTouchDelegate = delegate;
8772    }
8773
8774    /**
8775     * Gets the TouchDelegate for this View.
8776     */
8777    public TouchDelegate getTouchDelegate() {
8778        return mTouchDelegate;
8779    }
8780
8781    /**
8782     * Set flags controlling behavior of this view.
8783     *
8784     * @param flags Constant indicating the value which should be set
8785     * @param mask Constant indicating the bit range that should be changed
8786     */
8787    void setFlags(int flags, int mask) {
8788        final boolean accessibilityEnabled =
8789                AccessibilityManager.getInstance(mContext).isEnabled();
8790        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8791
8792        int old = mViewFlags;
8793        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8794
8795        int changed = mViewFlags ^ old;
8796        if (changed == 0) {
8797            return;
8798        }
8799        int privateFlags = mPrivateFlags;
8800
8801        /* Check if the FOCUSABLE bit has changed */
8802        if (((changed & FOCUSABLE_MASK) != 0) &&
8803                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8804            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8805                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8806                /* Give up focus if we are no longer focusable */
8807                clearFocus();
8808            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8809                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8810                /*
8811                 * Tell the view system that we are now available to take focus
8812                 * if no one else already has it.
8813                 */
8814                if (mParent != null) mParent.focusableViewAvailable(this);
8815            }
8816        }
8817
8818        final int newVisibility = flags & VISIBILITY_MASK;
8819        if (newVisibility == VISIBLE) {
8820            if ((changed & VISIBILITY_MASK) != 0) {
8821                /*
8822                 * If this view is becoming visible, invalidate it in case it changed while
8823                 * it was not visible. Marking it drawn ensures that the invalidation will
8824                 * go through.
8825                 */
8826                mPrivateFlags |= PFLAG_DRAWN;
8827                invalidate(true);
8828
8829                needGlobalAttributesUpdate(true);
8830
8831                // a view becoming visible is worth notifying the parent
8832                // about in case nothing has focus.  even if this specific view
8833                // isn't focusable, it may contain something that is, so let
8834                // the root view try to give this focus if nothing else does.
8835                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8836                    mParent.focusableViewAvailable(this);
8837                }
8838            }
8839        }
8840
8841        /* Check if the GONE bit has changed */
8842        if ((changed & GONE) != 0) {
8843            needGlobalAttributesUpdate(false);
8844            requestLayout();
8845
8846            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8847                if (hasFocus()) clearFocus();
8848                clearAccessibilityFocus();
8849                destroyDrawingCache();
8850                if (mParent instanceof View) {
8851                    // GONE views noop invalidation, so invalidate the parent
8852                    ((View) mParent).invalidate(true);
8853                }
8854                // Mark the view drawn to ensure that it gets invalidated properly the next
8855                // time it is visible and gets invalidated
8856                mPrivateFlags |= PFLAG_DRAWN;
8857            }
8858            if (mAttachInfo != null) {
8859                mAttachInfo.mViewVisibilityChanged = true;
8860            }
8861        }
8862
8863        /* Check if the VISIBLE bit has changed */
8864        if ((changed & INVISIBLE) != 0) {
8865            needGlobalAttributesUpdate(false);
8866            /*
8867             * If this view is becoming invisible, set the DRAWN flag so that
8868             * the next invalidate() will not be skipped.
8869             */
8870            mPrivateFlags |= PFLAG_DRAWN;
8871
8872            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8873                // root view becoming invisible shouldn't clear focus and accessibility focus
8874                if (getRootView() != this) {
8875                    clearFocus();
8876                    clearAccessibilityFocus();
8877                }
8878            }
8879            if (mAttachInfo != null) {
8880                mAttachInfo.mViewVisibilityChanged = true;
8881            }
8882        }
8883
8884        if ((changed & VISIBILITY_MASK) != 0) {
8885            // If the view is invisible, cleanup its display list to free up resources
8886            if (newVisibility != VISIBLE) {
8887                cleanupDraw();
8888            }
8889
8890            if (mParent instanceof ViewGroup) {
8891                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8892                        (changed & VISIBILITY_MASK), newVisibility);
8893                ((View) mParent).invalidate(true);
8894            } else if (mParent != null) {
8895                mParent.invalidateChild(this, null);
8896            }
8897            dispatchVisibilityChanged(this, newVisibility);
8898        }
8899
8900        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8901            destroyDrawingCache();
8902        }
8903
8904        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8905            destroyDrawingCache();
8906            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8907            invalidateParentCaches();
8908        }
8909
8910        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8911            destroyDrawingCache();
8912            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8913        }
8914
8915        if ((changed & DRAW_MASK) != 0) {
8916            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8917                if (mBackground != null) {
8918                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8919                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8920                } else {
8921                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8922                }
8923            } else {
8924                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8925            }
8926            requestLayout();
8927            invalidate(true);
8928        }
8929
8930        if ((changed & KEEP_SCREEN_ON) != 0) {
8931            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8932                mParent.recomputeViewAttributes(this);
8933            }
8934        }
8935
8936        if (accessibilityEnabled) {
8937            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8938                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8939                if (oldIncludeForAccessibility != includeForAccessibility()) {
8940                    notifySubtreeAccessibilityStateChangedIfNeeded();
8941                } else {
8942                    notifyViewAccessibilityStateChangedIfNeeded(
8943                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8944                }
8945            } else if ((changed & ENABLED_MASK) != 0) {
8946                notifyViewAccessibilityStateChangedIfNeeded(
8947                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8948            }
8949        }
8950    }
8951
8952    /**
8953     * Change the view's z order in the tree, so it's on top of other sibling
8954     * views. This ordering change may affect layout, if the parent container
8955     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
8956     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
8957     * method should be followed by calls to {@link #requestLayout()} and
8958     * {@link View#invalidate()} on the view's parent to force the parent to redraw
8959     * with the new child ordering.
8960     *
8961     * @see ViewGroup#bringChildToFront(View)
8962     */
8963    public void bringToFront() {
8964        if (mParent != null) {
8965            mParent.bringChildToFront(this);
8966        }
8967    }
8968
8969    /**
8970     * This is called in response to an internal scroll in this view (i.e., the
8971     * view scrolled its own contents). This is typically as a result of
8972     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8973     * called.
8974     *
8975     * @param l Current horizontal scroll origin.
8976     * @param t Current vertical scroll origin.
8977     * @param oldl Previous horizontal scroll origin.
8978     * @param oldt Previous vertical scroll origin.
8979     */
8980    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8981        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8982            postSendViewScrolledAccessibilityEventCallback();
8983        }
8984
8985        mBackgroundSizeChanged = true;
8986
8987        final AttachInfo ai = mAttachInfo;
8988        if (ai != null) {
8989            ai.mViewScrollChanged = true;
8990        }
8991    }
8992
8993    /**
8994     * Interface definition for a callback to be invoked when the layout bounds of a view
8995     * changes due to layout processing.
8996     */
8997    public interface OnLayoutChangeListener {
8998        /**
8999         * Called when the focus state of a view has changed.
9000         *
9001         * @param v The view whose state has changed.
9002         * @param left The new value of the view's left property.
9003         * @param top The new value of the view's top property.
9004         * @param right The new value of the view's right property.
9005         * @param bottom The new value of the view's bottom property.
9006         * @param oldLeft The previous value of the view's left property.
9007         * @param oldTop The previous value of the view's top property.
9008         * @param oldRight The previous value of the view's right property.
9009         * @param oldBottom The previous value of the view's bottom property.
9010         */
9011        void onLayoutChange(View v, int left, int top, int right, int bottom,
9012            int oldLeft, int oldTop, int oldRight, int oldBottom);
9013    }
9014
9015    /**
9016     * This is called during layout when the size of this view has changed. If
9017     * you were just added to the view hierarchy, you're called with the old
9018     * values of 0.
9019     *
9020     * @param w Current width of this view.
9021     * @param h Current height of this view.
9022     * @param oldw Old width of this view.
9023     * @param oldh Old height of this view.
9024     */
9025    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9026    }
9027
9028    /**
9029     * Called by draw to draw the child views. This may be overridden
9030     * by derived classes to gain control just before its children are drawn
9031     * (but after its own view has been drawn).
9032     * @param canvas the canvas on which to draw the view
9033     */
9034    protected void dispatchDraw(Canvas canvas) {
9035
9036    }
9037
9038    /**
9039     * Gets the parent of this view. Note that the parent is a
9040     * ViewParent and not necessarily a View.
9041     *
9042     * @return Parent of this view.
9043     */
9044    public final ViewParent getParent() {
9045        return mParent;
9046    }
9047
9048    /**
9049     * Set the horizontal scrolled position of your view. This will cause a call to
9050     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9051     * invalidated.
9052     * @param value the x position to scroll to
9053     */
9054    public void setScrollX(int value) {
9055        scrollTo(value, mScrollY);
9056    }
9057
9058    /**
9059     * Set the vertical scrolled position of your view. This will cause a call to
9060     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9061     * invalidated.
9062     * @param value the y position to scroll to
9063     */
9064    public void setScrollY(int value) {
9065        scrollTo(mScrollX, value);
9066    }
9067
9068    /**
9069     * Return the scrolled left position of this view. This is the left edge of
9070     * the displayed part of your view. You do not need to draw any pixels
9071     * farther left, since those are outside of the frame of your view on
9072     * screen.
9073     *
9074     * @return The left edge of the displayed part of your view, in pixels.
9075     */
9076    public final int getScrollX() {
9077        return mScrollX;
9078    }
9079
9080    /**
9081     * Return the scrolled top position of this view. This is the top edge of
9082     * the displayed part of your view. You do not need to draw any pixels above
9083     * it, since those are outside of the frame of your view on screen.
9084     *
9085     * @return The top edge of the displayed part of your view, in pixels.
9086     */
9087    public final int getScrollY() {
9088        return mScrollY;
9089    }
9090
9091    /**
9092     * Return the width of the your view.
9093     *
9094     * @return The width of your view, in pixels.
9095     */
9096    @ViewDebug.ExportedProperty(category = "layout")
9097    public final int getWidth() {
9098        return mRight - mLeft;
9099    }
9100
9101    /**
9102     * Return the height of your view.
9103     *
9104     * @return The height of your view, in pixels.
9105     */
9106    @ViewDebug.ExportedProperty(category = "layout")
9107    public final int getHeight() {
9108        return mBottom - mTop;
9109    }
9110
9111    /**
9112     * Return the visible drawing bounds of your view. Fills in the output
9113     * rectangle with the values from getScrollX(), getScrollY(),
9114     * getWidth(), and getHeight(). These bounds do not account for any
9115     * transformation properties currently set on the view, such as
9116     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9117     *
9118     * @param outRect The (scrolled) drawing bounds of the view.
9119     */
9120    public void getDrawingRect(Rect outRect) {
9121        outRect.left = mScrollX;
9122        outRect.top = mScrollY;
9123        outRect.right = mScrollX + (mRight - mLeft);
9124        outRect.bottom = mScrollY + (mBottom - mTop);
9125    }
9126
9127    /**
9128     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9129     * raw width component (that is the result is masked by
9130     * {@link #MEASURED_SIZE_MASK}).
9131     *
9132     * @return The raw measured width of this view.
9133     */
9134    public final int getMeasuredWidth() {
9135        return mMeasuredWidth & MEASURED_SIZE_MASK;
9136    }
9137
9138    /**
9139     * Return the full width measurement information for this view as computed
9140     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9141     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9142     * This should be used during measurement and layout calculations only. Use
9143     * {@link #getWidth()} to see how wide a view is after layout.
9144     *
9145     * @return The measured width of this view as a bit mask.
9146     */
9147    public final int getMeasuredWidthAndState() {
9148        return mMeasuredWidth;
9149    }
9150
9151    /**
9152     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9153     * raw width component (that is the result is masked by
9154     * {@link #MEASURED_SIZE_MASK}).
9155     *
9156     * @return The raw measured height of this view.
9157     */
9158    public final int getMeasuredHeight() {
9159        return mMeasuredHeight & MEASURED_SIZE_MASK;
9160    }
9161
9162    /**
9163     * Return the full height measurement information for this view as computed
9164     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9165     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9166     * This should be used during measurement and layout calculations only. Use
9167     * {@link #getHeight()} to see how wide a view is after layout.
9168     *
9169     * @return The measured width of this view as a bit mask.
9170     */
9171    public final int getMeasuredHeightAndState() {
9172        return mMeasuredHeight;
9173    }
9174
9175    /**
9176     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9177     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9178     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9179     * and the height component is at the shifted bits
9180     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9181     */
9182    public final int getMeasuredState() {
9183        return (mMeasuredWidth&MEASURED_STATE_MASK)
9184                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9185                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9186    }
9187
9188    /**
9189     * The transform matrix of this view, which is calculated based on the current
9190     * roation, scale, and pivot properties.
9191     *
9192     * @see #getRotation()
9193     * @see #getScaleX()
9194     * @see #getScaleY()
9195     * @see #getPivotX()
9196     * @see #getPivotY()
9197     * @return The current transform matrix for the view
9198     */
9199    public Matrix getMatrix() {
9200        if (mTransformationInfo != null) {
9201            updateMatrix();
9202            return mTransformationInfo.mMatrix;
9203        }
9204        return Matrix.IDENTITY_MATRIX;
9205    }
9206
9207    /**
9208     * Utility function to determine if the value is far enough away from zero to be
9209     * considered non-zero.
9210     * @param value A floating point value to check for zero-ness
9211     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9212     */
9213    private static boolean nonzero(float value) {
9214        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9215    }
9216
9217    /**
9218     * Returns true if the transform matrix is the identity matrix.
9219     * Recomputes the matrix if necessary.
9220     *
9221     * @return True if the transform matrix is the identity matrix, false otherwise.
9222     */
9223    final boolean hasIdentityMatrix() {
9224        if (mTransformationInfo != null) {
9225            updateMatrix();
9226            return mTransformationInfo.mMatrixIsIdentity;
9227        }
9228        return true;
9229    }
9230
9231    void ensureTransformationInfo() {
9232        if (mTransformationInfo == null) {
9233            mTransformationInfo = new TransformationInfo();
9234        }
9235    }
9236
9237    /**
9238     * Recomputes the transform matrix if necessary.
9239     */
9240    private void updateMatrix() {
9241        final TransformationInfo info = mTransformationInfo;
9242        if (info == null) {
9243            return;
9244        }
9245        if (info.mMatrixDirty) {
9246            // transform-related properties have changed since the last time someone
9247            // asked for the matrix; recalculate it with the current values
9248
9249            // Figure out if we need to update the pivot point
9250            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9251                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9252                    info.mPrevWidth = mRight - mLeft;
9253                    info.mPrevHeight = mBottom - mTop;
9254                    info.mPivotX = info.mPrevWidth / 2f;
9255                    info.mPivotY = info.mPrevHeight / 2f;
9256                }
9257            }
9258            info.mMatrix.reset();
9259            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9260                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9261                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9262                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9263            } else {
9264                if (info.mCamera == null) {
9265                    info.mCamera = new Camera();
9266                    info.matrix3D = new Matrix();
9267                }
9268                info.mCamera.save();
9269                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9270                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9271                info.mCamera.getMatrix(info.matrix3D);
9272                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9273                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9274                        info.mPivotY + info.mTranslationY);
9275                info.mMatrix.postConcat(info.matrix3D);
9276                info.mCamera.restore();
9277            }
9278            info.mMatrixDirty = false;
9279            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9280            info.mInverseMatrixDirty = true;
9281        }
9282    }
9283
9284   /**
9285     * Utility method to retrieve the inverse of the current mMatrix property.
9286     * We cache the matrix to avoid recalculating it when transform properties
9287     * have not changed.
9288     *
9289     * @return The inverse of the current matrix of this view.
9290     */
9291    final Matrix getInverseMatrix() {
9292        final TransformationInfo info = mTransformationInfo;
9293        if (info != null) {
9294            updateMatrix();
9295            if (info.mInverseMatrixDirty) {
9296                if (info.mInverseMatrix == null) {
9297                    info.mInverseMatrix = new Matrix();
9298                }
9299                info.mMatrix.invert(info.mInverseMatrix);
9300                info.mInverseMatrixDirty = false;
9301            }
9302            return info.mInverseMatrix;
9303        }
9304        return Matrix.IDENTITY_MATRIX;
9305    }
9306
9307    /**
9308     * Gets the distance along the Z axis from the camera to this view.
9309     *
9310     * @see #setCameraDistance(float)
9311     *
9312     * @return The distance along the Z axis.
9313     */
9314    public float getCameraDistance() {
9315        ensureTransformationInfo();
9316        final float dpi = mResources.getDisplayMetrics().densityDpi;
9317        final TransformationInfo info = mTransformationInfo;
9318        if (info.mCamera == null) {
9319            info.mCamera = new Camera();
9320            info.matrix3D = new Matrix();
9321        }
9322        return -(info.mCamera.getLocationZ() * dpi);
9323    }
9324
9325    /**
9326     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9327     * views are drawn) from the camera to this view. The camera's distance
9328     * affects 3D transformations, for instance rotations around the X and Y
9329     * axis. If the rotationX or rotationY properties are changed and this view is
9330     * large (more than half the size of the screen), it is recommended to always
9331     * use a camera distance that's greater than the height (X axis rotation) or
9332     * the width (Y axis rotation) of this view.</p>
9333     *
9334     * <p>The distance of the camera from the view plane can have an affect on the
9335     * perspective distortion of the view when it is rotated around the x or y axis.
9336     * For example, a large distance will result in a large viewing angle, and there
9337     * will not be much perspective distortion of the view as it rotates. A short
9338     * distance may cause much more perspective distortion upon rotation, and can
9339     * also result in some drawing artifacts if the rotated view ends up partially
9340     * behind the camera (which is why the recommendation is to use a distance at
9341     * least as far as the size of the view, if the view is to be rotated.)</p>
9342     *
9343     * <p>The distance is expressed in "depth pixels." The default distance depends
9344     * on the screen density. For instance, on a medium density display, the
9345     * default distance is 1280. On a high density display, the default distance
9346     * is 1920.</p>
9347     *
9348     * <p>If you want to specify a distance that leads to visually consistent
9349     * results across various densities, use the following formula:</p>
9350     * <pre>
9351     * float scale = context.getResources().getDisplayMetrics().density;
9352     * view.setCameraDistance(distance * scale);
9353     * </pre>
9354     *
9355     * <p>The density scale factor of a high density display is 1.5,
9356     * and 1920 = 1280 * 1.5.</p>
9357     *
9358     * @param distance The distance in "depth pixels", if negative the opposite
9359     *        value is used
9360     *
9361     * @see #setRotationX(float)
9362     * @see #setRotationY(float)
9363     */
9364    public void setCameraDistance(float distance) {
9365        invalidateViewProperty(true, false);
9366
9367        ensureTransformationInfo();
9368        final float dpi = mResources.getDisplayMetrics().densityDpi;
9369        final TransformationInfo info = mTransformationInfo;
9370        if (info.mCamera == null) {
9371            info.mCamera = new Camera();
9372            info.matrix3D = new Matrix();
9373        }
9374
9375        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9376        info.mMatrixDirty = true;
9377
9378        invalidateViewProperty(false, false);
9379        if (mDisplayList != null) {
9380            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9381        }
9382        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9383            // View was rejected last time it was drawn by its parent; this may have changed
9384            invalidateParentIfNeeded();
9385        }
9386    }
9387
9388    /**
9389     * The degrees that the view is rotated around the pivot point.
9390     *
9391     * @see #setRotation(float)
9392     * @see #getPivotX()
9393     * @see #getPivotY()
9394     *
9395     * @return The degrees of rotation.
9396     */
9397    @ViewDebug.ExportedProperty(category = "drawing")
9398    public float getRotation() {
9399        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9400    }
9401
9402    /**
9403     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9404     * result in clockwise rotation.
9405     *
9406     * @param rotation The degrees of rotation.
9407     *
9408     * @see #getRotation()
9409     * @see #getPivotX()
9410     * @see #getPivotY()
9411     * @see #setRotationX(float)
9412     * @see #setRotationY(float)
9413     *
9414     * @attr ref android.R.styleable#View_rotation
9415     */
9416    public void setRotation(float rotation) {
9417        ensureTransformationInfo();
9418        final TransformationInfo info = mTransformationInfo;
9419        if (info.mRotation != rotation) {
9420            // Double-invalidation is necessary to capture view's old and new areas
9421            invalidateViewProperty(true, false);
9422            info.mRotation = rotation;
9423            info.mMatrixDirty = true;
9424            invalidateViewProperty(false, true);
9425            if (mDisplayList != null) {
9426                mDisplayList.setRotation(rotation);
9427            }
9428            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9429                // View was rejected last time it was drawn by its parent; this may have changed
9430                invalidateParentIfNeeded();
9431            }
9432        }
9433    }
9434
9435    /**
9436     * The degrees that the view is rotated around the vertical axis through the pivot point.
9437     *
9438     * @see #getPivotX()
9439     * @see #getPivotY()
9440     * @see #setRotationY(float)
9441     *
9442     * @return The degrees of Y rotation.
9443     */
9444    @ViewDebug.ExportedProperty(category = "drawing")
9445    public float getRotationY() {
9446        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9447    }
9448
9449    /**
9450     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9451     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9452     * down the y axis.
9453     *
9454     * When rotating large views, it is recommended to adjust the camera distance
9455     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9456     *
9457     * @param rotationY The degrees of Y rotation.
9458     *
9459     * @see #getRotationY()
9460     * @see #getPivotX()
9461     * @see #getPivotY()
9462     * @see #setRotation(float)
9463     * @see #setRotationX(float)
9464     * @see #setCameraDistance(float)
9465     *
9466     * @attr ref android.R.styleable#View_rotationY
9467     */
9468    public void setRotationY(float rotationY) {
9469        ensureTransformationInfo();
9470        final TransformationInfo info = mTransformationInfo;
9471        if (info.mRotationY != rotationY) {
9472            invalidateViewProperty(true, false);
9473            info.mRotationY = rotationY;
9474            info.mMatrixDirty = true;
9475            invalidateViewProperty(false, true);
9476            if (mDisplayList != null) {
9477                mDisplayList.setRotationY(rotationY);
9478            }
9479            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9480                // View was rejected last time it was drawn by its parent; this may have changed
9481                invalidateParentIfNeeded();
9482            }
9483        }
9484    }
9485
9486    /**
9487     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9488     *
9489     * @see #getPivotX()
9490     * @see #getPivotY()
9491     * @see #setRotationX(float)
9492     *
9493     * @return The degrees of X rotation.
9494     */
9495    @ViewDebug.ExportedProperty(category = "drawing")
9496    public float getRotationX() {
9497        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9498    }
9499
9500    /**
9501     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9502     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9503     * x axis.
9504     *
9505     * When rotating large views, it is recommended to adjust the camera distance
9506     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9507     *
9508     * @param rotationX The degrees of X rotation.
9509     *
9510     * @see #getRotationX()
9511     * @see #getPivotX()
9512     * @see #getPivotY()
9513     * @see #setRotation(float)
9514     * @see #setRotationY(float)
9515     * @see #setCameraDistance(float)
9516     *
9517     * @attr ref android.R.styleable#View_rotationX
9518     */
9519    public void setRotationX(float rotationX) {
9520        ensureTransformationInfo();
9521        final TransformationInfo info = mTransformationInfo;
9522        if (info.mRotationX != rotationX) {
9523            invalidateViewProperty(true, false);
9524            info.mRotationX = rotationX;
9525            info.mMatrixDirty = true;
9526            invalidateViewProperty(false, true);
9527            if (mDisplayList != null) {
9528                mDisplayList.setRotationX(rotationX);
9529            }
9530            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9531                // View was rejected last time it was drawn by its parent; this may have changed
9532                invalidateParentIfNeeded();
9533            }
9534        }
9535    }
9536
9537    /**
9538     * The amount that the view is scaled in x around the pivot point, as a proportion of
9539     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9540     *
9541     * <p>By default, this is 1.0f.
9542     *
9543     * @see #getPivotX()
9544     * @see #getPivotY()
9545     * @return The scaling factor.
9546     */
9547    @ViewDebug.ExportedProperty(category = "drawing")
9548    public float getScaleX() {
9549        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9550    }
9551
9552    /**
9553     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9554     * the view's unscaled width. A value of 1 means that no scaling is applied.
9555     *
9556     * @param scaleX The scaling factor.
9557     * @see #getPivotX()
9558     * @see #getPivotY()
9559     *
9560     * @attr ref android.R.styleable#View_scaleX
9561     */
9562    public void setScaleX(float scaleX) {
9563        ensureTransformationInfo();
9564        final TransformationInfo info = mTransformationInfo;
9565        if (info.mScaleX != scaleX) {
9566            invalidateViewProperty(true, false);
9567            info.mScaleX = scaleX;
9568            info.mMatrixDirty = true;
9569            invalidateViewProperty(false, true);
9570            if (mDisplayList != null) {
9571                mDisplayList.setScaleX(scaleX);
9572            }
9573            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9574                // View was rejected last time it was drawn by its parent; this may have changed
9575                invalidateParentIfNeeded();
9576            }
9577        }
9578    }
9579
9580    /**
9581     * The amount that the view is scaled in y around the pivot point, as a proportion of
9582     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9583     *
9584     * <p>By default, this is 1.0f.
9585     *
9586     * @see #getPivotX()
9587     * @see #getPivotY()
9588     * @return The scaling factor.
9589     */
9590    @ViewDebug.ExportedProperty(category = "drawing")
9591    public float getScaleY() {
9592        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9593    }
9594
9595    /**
9596     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9597     * the view's unscaled width. A value of 1 means that no scaling is applied.
9598     *
9599     * @param scaleY The scaling factor.
9600     * @see #getPivotX()
9601     * @see #getPivotY()
9602     *
9603     * @attr ref android.R.styleable#View_scaleY
9604     */
9605    public void setScaleY(float scaleY) {
9606        ensureTransformationInfo();
9607        final TransformationInfo info = mTransformationInfo;
9608        if (info.mScaleY != scaleY) {
9609            invalidateViewProperty(true, false);
9610            info.mScaleY = scaleY;
9611            info.mMatrixDirty = true;
9612            invalidateViewProperty(false, true);
9613            if (mDisplayList != null) {
9614                mDisplayList.setScaleY(scaleY);
9615            }
9616            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9617                // View was rejected last time it was drawn by its parent; this may have changed
9618                invalidateParentIfNeeded();
9619            }
9620        }
9621    }
9622
9623    /**
9624     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9625     * and {@link #setScaleX(float) scaled}.
9626     *
9627     * @see #getRotation()
9628     * @see #getScaleX()
9629     * @see #getScaleY()
9630     * @see #getPivotY()
9631     * @return The x location of the pivot point.
9632     *
9633     * @attr ref android.R.styleable#View_transformPivotX
9634     */
9635    @ViewDebug.ExportedProperty(category = "drawing")
9636    public float getPivotX() {
9637        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9638    }
9639
9640    /**
9641     * Sets the x location of the point around which the view is
9642     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9643     * By default, the pivot point is centered on the object.
9644     * Setting this property disables this behavior and causes the view to use only the
9645     * explicitly set pivotX and pivotY values.
9646     *
9647     * @param pivotX The x location of the pivot point.
9648     * @see #getRotation()
9649     * @see #getScaleX()
9650     * @see #getScaleY()
9651     * @see #getPivotY()
9652     *
9653     * @attr ref android.R.styleable#View_transformPivotX
9654     */
9655    public void setPivotX(float pivotX) {
9656        ensureTransformationInfo();
9657        final TransformationInfo info = mTransformationInfo;
9658        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9659                PFLAG_PIVOT_EXPLICITLY_SET;
9660        if (info.mPivotX != pivotX || !pivotSet) {
9661            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9662            invalidateViewProperty(true, false);
9663            info.mPivotX = pivotX;
9664            info.mMatrixDirty = true;
9665            invalidateViewProperty(false, true);
9666            if (mDisplayList != null) {
9667                mDisplayList.setPivotX(pivotX);
9668            }
9669            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9670                // View was rejected last time it was drawn by its parent; this may have changed
9671                invalidateParentIfNeeded();
9672            }
9673        }
9674    }
9675
9676    /**
9677     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9678     * and {@link #setScaleY(float) scaled}.
9679     *
9680     * @see #getRotation()
9681     * @see #getScaleX()
9682     * @see #getScaleY()
9683     * @see #getPivotY()
9684     * @return The y location of the pivot point.
9685     *
9686     * @attr ref android.R.styleable#View_transformPivotY
9687     */
9688    @ViewDebug.ExportedProperty(category = "drawing")
9689    public float getPivotY() {
9690        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9691    }
9692
9693    /**
9694     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9695     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9696     * Setting this property disables this behavior and causes the view to use only the
9697     * explicitly set pivotX and pivotY values.
9698     *
9699     * @param pivotY The y location of the pivot point.
9700     * @see #getRotation()
9701     * @see #getScaleX()
9702     * @see #getScaleY()
9703     * @see #getPivotY()
9704     *
9705     * @attr ref android.R.styleable#View_transformPivotY
9706     */
9707    public void setPivotY(float pivotY) {
9708        ensureTransformationInfo();
9709        final TransformationInfo info = mTransformationInfo;
9710        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9711                PFLAG_PIVOT_EXPLICITLY_SET;
9712        if (info.mPivotY != pivotY || !pivotSet) {
9713            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9714            invalidateViewProperty(true, false);
9715            info.mPivotY = pivotY;
9716            info.mMatrixDirty = true;
9717            invalidateViewProperty(false, true);
9718            if (mDisplayList != null) {
9719                mDisplayList.setPivotY(pivotY);
9720            }
9721            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9722                // View was rejected last time it was drawn by its parent; this may have changed
9723                invalidateParentIfNeeded();
9724            }
9725        }
9726    }
9727
9728    /**
9729     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9730     * completely transparent and 1 means the view is completely opaque.
9731     *
9732     * <p>By default this is 1.0f.
9733     * @return The opacity of the view.
9734     */
9735    @ViewDebug.ExportedProperty(category = "drawing")
9736    public float getAlpha() {
9737        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9738    }
9739
9740    /**
9741     * Returns whether this View has content which overlaps. This function, intended to be
9742     * overridden by specific View types, is an optimization when alpha is set on a view. If
9743     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9744     * and then composited it into place, which can be expensive. If the view has no overlapping
9745     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9746     * An example of overlapping rendering is a TextView with a background image, such as a
9747     * Button. An example of non-overlapping rendering is a TextView with no background, or
9748     * an ImageView with only the foreground image. The default implementation returns true;
9749     * subclasses should override if they have cases which can be optimized.
9750     *
9751     * @return true if the content in this view might overlap, false otherwise.
9752     */
9753    public boolean hasOverlappingRendering() {
9754        return true;
9755    }
9756
9757    /**
9758     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9759     * completely transparent and 1 means the view is completely opaque.</p>
9760     *
9761     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9762     * performance implications, especially for large views. It is best to use the alpha property
9763     * sparingly and transiently, as in the case of fading animations.</p>
9764     *
9765     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9766     * strongly recommended for performance reasons to either override
9767     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9768     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9769     *
9770     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9771     * responsible for applying the opacity itself.</p>
9772     *
9773     * <p>Note that if the view is backed by a
9774     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9775     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9776     * 1.0 will supercede the alpha of the layer paint.</p>
9777     *
9778     * @param alpha The opacity of the view.
9779     *
9780     * @see #hasOverlappingRendering()
9781     * @see #setLayerType(int, android.graphics.Paint)
9782     *
9783     * @attr ref android.R.styleable#View_alpha
9784     */
9785    public void setAlpha(float alpha) {
9786        ensureTransformationInfo();
9787        if (mTransformationInfo.mAlpha != alpha) {
9788            mTransformationInfo.mAlpha = alpha;
9789            if (onSetAlpha((int) (alpha * 255))) {
9790                mPrivateFlags |= PFLAG_ALPHA_SET;
9791                // subclass is handling alpha - don't optimize rendering cache invalidation
9792                invalidateParentCaches();
9793                invalidate(true);
9794            } else {
9795                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9796                invalidateViewProperty(true, false);
9797                if (mDisplayList != null) {
9798                    mDisplayList.setAlpha(getFinalAlpha());
9799                }
9800            }
9801        }
9802    }
9803
9804    /**
9805     * Faster version of setAlpha() which performs the same steps except there are
9806     * no calls to invalidate(). The caller of this function should perform proper invalidation
9807     * on the parent and this object. The return value indicates whether the subclass handles
9808     * alpha (the return value for onSetAlpha()).
9809     *
9810     * @param alpha The new value for the alpha property
9811     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9812     *         the new value for the alpha property is different from the old value
9813     */
9814    boolean setAlphaNoInvalidation(float alpha) {
9815        ensureTransformationInfo();
9816        if (mTransformationInfo.mAlpha != alpha) {
9817            mTransformationInfo.mAlpha = alpha;
9818            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9819            if (subclassHandlesAlpha) {
9820                mPrivateFlags |= PFLAG_ALPHA_SET;
9821                return true;
9822            } else {
9823                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9824                if (mDisplayList != null) {
9825                    mDisplayList.setAlpha(getFinalAlpha());
9826                }
9827            }
9828        }
9829        return false;
9830    }
9831
9832    /**
9833     * This property is hidden and intended only for use by the Fade transition, which
9834     * animates it to produce a visual translucency that does not side-effect (or get
9835     * affected by) the real alpha property. This value is composited with the other
9836     * alpha value (and the AlphaAnimation value, when that is present) to produce
9837     * a final visual translucency result, which is what is passed into the DisplayList.
9838     *
9839     * @hide
9840     */
9841    public void setTransitionAlpha(float alpha) {
9842        ensureTransformationInfo();
9843        if (mTransformationInfo.mTransitionAlpha != alpha) {
9844            mTransformationInfo.mTransitionAlpha = alpha;
9845            mPrivateFlags &= ~PFLAG_ALPHA_SET;
9846            invalidateViewProperty(true, false);
9847            if (mDisplayList != null) {
9848                mDisplayList.setAlpha(getFinalAlpha());
9849            }
9850        }
9851    }
9852
9853    /**
9854     * Calculates the visual alpha of this view, which is a combination of the actual
9855     * alpha value and the transitionAlpha value (if set).
9856     */
9857    private float getFinalAlpha() {
9858        if (mTransformationInfo != null) {
9859            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
9860        }
9861        return 1;
9862    }
9863
9864    /**
9865     * This property is hidden and intended only for use by the Fade transition, which
9866     * animates it to produce a visual translucency that does not side-effect (or get
9867     * affected by) the real alpha property. This value is composited with the other
9868     * alpha value (and the AlphaAnimation value, when that is present) to produce
9869     * a final visual translucency result, which is what is passed into the DisplayList.
9870     *
9871     * @hide
9872     */
9873    public float getTransitionAlpha() {
9874        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
9875    }
9876
9877    /**
9878     * Top position of this view relative to its parent.
9879     *
9880     * @return The top of this view, in pixels.
9881     */
9882    @ViewDebug.CapturedViewProperty
9883    public final int getTop() {
9884        return mTop;
9885    }
9886
9887    /**
9888     * Sets the top position of this view relative to its parent. This method is meant to be called
9889     * by the layout system and should not generally be called otherwise, because the property
9890     * may be changed at any time by the layout.
9891     *
9892     * @param top The top of this view, in pixels.
9893     */
9894    public final void setTop(int top) {
9895        if (top != mTop) {
9896            updateMatrix();
9897            final boolean matrixIsIdentity = mTransformationInfo == null
9898                    || mTransformationInfo.mMatrixIsIdentity;
9899            if (matrixIsIdentity) {
9900                if (mAttachInfo != null) {
9901                    int minTop;
9902                    int yLoc;
9903                    if (top < mTop) {
9904                        minTop = top;
9905                        yLoc = top - mTop;
9906                    } else {
9907                        minTop = mTop;
9908                        yLoc = 0;
9909                    }
9910                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9911                }
9912            } else {
9913                // Double-invalidation is necessary to capture view's old and new areas
9914                invalidate(true);
9915            }
9916
9917            int width = mRight - mLeft;
9918            int oldHeight = mBottom - mTop;
9919
9920            mTop = top;
9921            if (mDisplayList != null) {
9922                mDisplayList.setTop(mTop);
9923            }
9924
9925            sizeChange(width, mBottom - mTop, width, oldHeight);
9926
9927            if (!matrixIsIdentity) {
9928                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9929                    // A change in dimension means an auto-centered pivot point changes, too
9930                    mTransformationInfo.mMatrixDirty = true;
9931                }
9932                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9933                invalidate(true);
9934            }
9935            mBackgroundSizeChanged = true;
9936            invalidateParentIfNeeded();
9937            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9938                // View was rejected last time it was drawn by its parent; this may have changed
9939                invalidateParentIfNeeded();
9940            }
9941        }
9942    }
9943
9944    /**
9945     * Bottom position of this view relative to its parent.
9946     *
9947     * @return The bottom of this view, in pixels.
9948     */
9949    @ViewDebug.CapturedViewProperty
9950    public final int getBottom() {
9951        return mBottom;
9952    }
9953
9954    /**
9955     * True if this view has changed since the last time being drawn.
9956     *
9957     * @return The dirty state of this view.
9958     */
9959    public boolean isDirty() {
9960        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9961    }
9962
9963    /**
9964     * Sets the bottom position of this view relative to its parent. This method is meant to be
9965     * called by the layout system and should not generally be called otherwise, because the
9966     * property may be changed at any time by the layout.
9967     *
9968     * @param bottom The bottom of this view, in pixels.
9969     */
9970    public final void setBottom(int bottom) {
9971        if (bottom != mBottom) {
9972            updateMatrix();
9973            final boolean matrixIsIdentity = mTransformationInfo == null
9974                    || mTransformationInfo.mMatrixIsIdentity;
9975            if (matrixIsIdentity) {
9976                if (mAttachInfo != null) {
9977                    int maxBottom;
9978                    if (bottom < mBottom) {
9979                        maxBottom = mBottom;
9980                    } else {
9981                        maxBottom = bottom;
9982                    }
9983                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9984                }
9985            } else {
9986                // Double-invalidation is necessary to capture view's old and new areas
9987                invalidate(true);
9988            }
9989
9990            int width = mRight - mLeft;
9991            int oldHeight = mBottom - mTop;
9992
9993            mBottom = bottom;
9994            if (mDisplayList != null) {
9995                mDisplayList.setBottom(mBottom);
9996            }
9997
9998            sizeChange(width, mBottom - mTop, width, oldHeight);
9999
10000            if (!matrixIsIdentity) {
10001                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10002                    // A change in dimension means an auto-centered pivot point changes, too
10003                    mTransformationInfo.mMatrixDirty = true;
10004                }
10005                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10006                invalidate(true);
10007            }
10008            mBackgroundSizeChanged = true;
10009            invalidateParentIfNeeded();
10010            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10011                // View was rejected last time it was drawn by its parent; this may have changed
10012                invalidateParentIfNeeded();
10013            }
10014        }
10015    }
10016
10017    /**
10018     * Left position of this view relative to its parent.
10019     *
10020     * @return The left edge of this view, in pixels.
10021     */
10022    @ViewDebug.CapturedViewProperty
10023    public final int getLeft() {
10024        return mLeft;
10025    }
10026
10027    /**
10028     * Sets the left position of this view relative to its parent. This method is meant to be called
10029     * by the layout system and should not generally be called otherwise, because the property
10030     * may be changed at any time by the layout.
10031     *
10032     * @param left The bottom of this view, in pixels.
10033     */
10034    public final void setLeft(int left) {
10035        if (left != mLeft) {
10036            updateMatrix();
10037            final boolean matrixIsIdentity = mTransformationInfo == null
10038                    || mTransformationInfo.mMatrixIsIdentity;
10039            if (matrixIsIdentity) {
10040                if (mAttachInfo != null) {
10041                    int minLeft;
10042                    int xLoc;
10043                    if (left < mLeft) {
10044                        minLeft = left;
10045                        xLoc = left - mLeft;
10046                    } else {
10047                        minLeft = mLeft;
10048                        xLoc = 0;
10049                    }
10050                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10051                }
10052            } else {
10053                // Double-invalidation is necessary to capture view's old and new areas
10054                invalidate(true);
10055            }
10056
10057            int oldWidth = mRight - mLeft;
10058            int height = mBottom - mTop;
10059
10060            mLeft = left;
10061            if (mDisplayList != null) {
10062                mDisplayList.setLeft(left);
10063            }
10064
10065            sizeChange(mRight - mLeft, height, oldWidth, height);
10066
10067            if (!matrixIsIdentity) {
10068                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10069                    // A change in dimension means an auto-centered pivot point changes, too
10070                    mTransformationInfo.mMatrixDirty = true;
10071                }
10072                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10073                invalidate(true);
10074            }
10075            mBackgroundSizeChanged = true;
10076            invalidateParentIfNeeded();
10077            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10078                // View was rejected last time it was drawn by its parent; this may have changed
10079                invalidateParentIfNeeded();
10080            }
10081        }
10082    }
10083
10084    /**
10085     * Right position of this view relative to its parent.
10086     *
10087     * @return The right edge of this view, in pixels.
10088     */
10089    @ViewDebug.CapturedViewProperty
10090    public final int getRight() {
10091        return mRight;
10092    }
10093
10094    /**
10095     * Sets the right position of this view relative to its parent. This method is meant to be called
10096     * by the layout system and should not generally be called otherwise, because the property
10097     * may be changed at any time by the layout.
10098     *
10099     * @param right The bottom of this view, in pixels.
10100     */
10101    public final void setRight(int right) {
10102        if (right != mRight) {
10103            updateMatrix();
10104            final boolean matrixIsIdentity = mTransformationInfo == null
10105                    || mTransformationInfo.mMatrixIsIdentity;
10106            if (matrixIsIdentity) {
10107                if (mAttachInfo != null) {
10108                    int maxRight;
10109                    if (right < mRight) {
10110                        maxRight = mRight;
10111                    } else {
10112                        maxRight = right;
10113                    }
10114                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10115                }
10116            } else {
10117                // Double-invalidation is necessary to capture view's old and new areas
10118                invalidate(true);
10119            }
10120
10121            int oldWidth = mRight - mLeft;
10122            int height = mBottom - mTop;
10123
10124            mRight = right;
10125            if (mDisplayList != null) {
10126                mDisplayList.setRight(mRight);
10127            }
10128
10129            sizeChange(mRight - mLeft, height, oldWidth, height);
10130
10131            if (!matrixIsIdentity) {
10132                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10133                    // A change in dimension means an auto-centered pivot point changes, too
10134                    mTransformationInfo.mMatrixDirty = true;
10135                }
10136                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10137                invalidate(true);
10138            }
10139            mBackgroundSizeChanged = true;
10140            invalidateParentIfNeeded();
10141            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10142                // View was rejected last time it was drawn by its parent; this may have changed
10143                invalidateParentIfNeeded();
10144            }
10145        }
10146    }
10147
10148    /**
10149     * The visual x position of this view, in pixels. This is equivalent to the
10150     * {@link #setTranslationX(float) translationX} property plus the current
10151     * {@link #getLeft() left} property.
10152     *
10153     * @return The visual x position of this view, in pixels.
10154     */
10155    @ViewDebug.ExportedProperty(category = "drawing")
10156    public float getX() {
10157        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10158    }
10159
10160    /**
10161     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10162     * {@link #setTranslationX(float) translationX} property to be the difference between
10163     * the x value passed in and the current {@link #getLeft() left} property.
10164     *
10165     * @param x The visual x position of this view, in pixels.
10166     */
10167    public void setX(float x) {
10168        setTranslationX(x - mLeft);
10169    }
10170
10171    /**
10172     * The visual y position of this view, in pixels. This is equivalent to the
10173     * {@link #setTranslationY(float) translationY} property plus the current
10174     * {@link #getTop() top} property.
10175     *
10176     * @return The visual y position of this view, in pixels.
10177     */
10178    @ViewDebug.ExportedProperty(category = "drawing")
10179    public float getY() {
10180        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10181    }
10182
10183    /**
10184     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10185     * {@link #setTranslationY(float) translationY} property to be the difference between
10186     * the y value passed in and the current {@link #getTop() top} property.
10187     *
10188     * @param y The visual y position of this view, in pixels.
10189     */
10190    public void setY(float y) {
10191        setTranslationY(y - mTop);
10192    }
10193
10194
10195    /**
10196     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10197     * This position is post-layout, in addition to wherever the object's
10198     * layout placed it.
10199     *
10200     * @return The horizontal position of this view relative to its left position, in pixels.
10201     */
10202    @ViewDebug.ExportedProperty(category = "drawing")
10203    public float getTranslationX() {
10204        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10205    }
10206
10207    /**
10208     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10209     * This effectively positions the object post-layout, in addition to wherever the object's
10210     * layout placed it.
10211     *
10212     * @param translationX The horizontal position of this view relative to its left position,
10213     * in pixels.
10214     *
10215     * @attr ref android.R.styleable#View_translationX
10216     */
10217    public void setTranslationX(float translationX) {
10218        ensureTransformationInfo();
10219        final TransformationInfo info = mTransformationInfo;
10220        if (info.mTranslationX != translationX) {
10221            // Double-invalidation is necessary to capture view's old and new areas
10222            invalidateViewProperty(true, false);
10223            info.mTranslationX = translationX;
10224            info.mMatrixDirty = true;
10225            invalidateViewProperty(false, true);
10226            if (mDisplayList != null) {
10227                mDisplayList.setTranslationX(translationX);
10228            }
10229            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10230                // View was rejected last time it was drawn by its parent; this may have changed
10231                invalidateParentIfNeeded();
10232            }
10233        }
10234    }
10235
10236    /**
10237     * The horizontal location of this view relative to its {@link #getTop() top} position.
10238     * This position is post-layout, in addition to wherever the object's
10239     * layout placed it.
10240     *
10241     * @return The vertical position of this view relative to its top position,
10242     * in pixels.
10243     */
10244    @ViewDebug.ExportedProperty(category = "drawing")
10245    public float getTranslationY() {
10246        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10247    }
10248
10249    /**
10250     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10251     * This effectively positions the object post-layout, in addition to wherever the object's
10252     * layout placed it.
10253     *
10254     * @param translationY The vertical position of this view relative to its top position,
10255     * in pixels.
10256     *
10257     * @attr ref android.R.styleable#View_translationY
10258     */
10259    public void setTranslationY(float translationY) {
10260        ensureTransformationInfo();
10261        final TransformationInfo info = mTransformationInfo;
10262        if (info.mTranslationY != translationY) {
10263            invalidateViewProperty(true, false);
10264            info.mTranslationY = translationY;
10265            info.mMatrixDirty = true;
10266            invalidateViewProperty(false, true);
10267            if (mDisplayList != null) {
10268                mDisplayList.setTranslationY(translationY);
10269            }
10270            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10271                // View was rejected last time it was drawn by its parent; this may have changed
10272                invalidateParentIfNeeded();
10273            }
10274        }
10275    }
10276
10277    /**
10278     * Hit rectangle in parent's coordinates
10279     *
10280     * @param outRect The hit rectangle of the view.
10281     */
10282    public void getHitRect(Rect outRect) {
10283        updateMatrix();
10284        final TransformationInfo info = mTransformationInfo;
10285        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10286            outRect.set(mLeft, mTop, mRight, mBottom);
10287        } else {
10288            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10289            tmpRect.set(0, 0, getWidth(), getHeight());
10290            info.mMatrix.mapRect(tmpRect);
10291            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10292                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10293        }
10294    }
10295
10296    /**
10297     * Determines whether the given point, in local coordinates is inside the view.
10298     */
10299    /*package*/ final boolean pointInView(float localX, float localY) {
10300        return localX >= 0 && localX < (mRight - mLeft)
10301                && localY >= 0 && localY < (mBottom - mTop);
10302    }
10303
10304    /**
10305     * Utility method to determine whether the given point, in local coordinates,
10306     * is inside the view, where the area of the view is expanded by the slop factor.
10307     * This method is called while processing touch-move events to determine if the event
10308     * is still within the view.
10309     *
10310     * @hide
10311     */
10312    public boolean pointInView(float localX, float localY, float slop) {
10313        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10314                localY < ((mBottom - mTop) + slop);
10315    }
10316
10317    /**
10318     * When a view has focus and the user navigates away from it, the next view is searched for
10319     * starting from the rectangle filled in by this method.
10320     *
10321     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10322     * of the view.  However, if your view maintains some idea of internal selection,
10323     * such as a cursor, or a selected row or column, you should override this method and
10324     * fill in a more specific rectangle.
10325     *
10326     * @param r The rectangle to fill in, in this view's coordinates.
10327     */
10328    public void getFocusedRect(Rect r) {
10329        getDrawingRect(r);
10330    }
10331
10332    /**
10333     * If some part of this view is not clipped by any of its parents, then
10334     * return that area in r in global (root) coordinates. To convert r to local
10335     * coordinates (without taking possible View rotations into account), offset
10336     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10337     * If the view is completely clipped or translated out, return false.
10338     *
10339     * @param r If true is returned, r holds the global coordinates of the
10340     *        visible portion of this view.
10341     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10342     *        between this view and its root. globalOffet may be null.
10343     * @return true if r is non-empty (i.e. part of the view is visible at the
10344     *         root level.
10345     */
10346    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10347        int width = mRight - mLeft;
10348        int height = mBottom - mTop;
10349        if (width > 0 && height > 0) {
10350            r.set(0, 0, width, height);
10351            if (globalOffset != null) {
10352                globalOffset.set(-mScrollX, -mScrollY);
10353            }
10354            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10355        }
10356        return false;
10357    }
10358
10359    public final boolean getGlobalVisibleRect(Rect r) {
10360        return getGlobalVisibleRect(r, null);
10361    }
10362
10363    public final boolean getLocalVisibleRect(Rect r) {
10364        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10365        if (getGlobalVisibleRect(r, offset)) {
10366            r.offset(-offset.x, -offset.y); // make r local
10367            return true;
10368        }
10369        return false;
10370    }
10371
10372    /**
10373     * Offset this view's vertical location by the specified number of pixels.
10374     *
10375     * @param offset the number of pixels to offset the view by
10376     */
10377    public void offsetTopAndBottom(int offset) {
10378        if (offset != 0) {
10379            updateMatrix();
10380            final boolean matrixIsIdentity = mTransformationInfo == null
10381                    || mTransformationInfo.mMatrixIsIdentity;
10382            if (matrixIsIdentity) {
10383                if (mDisplayList != null) {
10384                    invalidateViewProperty(false, false);
10385                } else {
10386                    final ViewParent p = mParent;
10387                    if (p != null && mAttachInfo != null) {
10388                        final Rect r = mAttachInfo.mTmpInvalRect;
10389                        int minTop;
10390                        int maxBottom;
10391                        int yLoc;
10392                        if (offset < 0) {
10393                            minTop = mTop + offset;
10394                            maxBottom = mBottom;
10395                            yLoc = offset;
10396                        } else {
10397                            minTop = mTop;
10398                            maxBottom = mBottom + offset;
10399                            yLoc = 0;
10400                        }
10401                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10402                        p.invalidateChild(this, r);
10403                    }
10404                }
10405            } else {
10406                invalidateViewProperty(false, false);
10407            }
10408
10409            mTop += offset;
10410            mBottom += offset;
10411            if (mDisplayList != null) {
10412                mDisplayList.offsetTopAndBottom(offset);
10413                invalidateViewProperty(false, false);
10414            } else {
10415                if (!matrixIsIdentity) {
10416                    invalidateViewProperty(false, true);
10417                }
10418                invalidateParentIfNeeded();
10419            }
10420        }
10421    }
10422
10423    /**
10424     * Offset this view's horizontal location by the specified amount of pixels.
10425     *
10426     * @param offset the number of pixels to offset the view by
10427     */
10428    public void offsetLeftAndRight(int offset) {
10429        if (offset != 0) {
10430            updateMatrix();
10431            final boolean matrixIsIdentity = mTransformationInfo == null
10432                    || mTransformationInfo.mMatrixIsIdentity;
10433            if (matrixIsIdentity) {
10434                if (mDisplayList != null) {
10435                    invalidateViewProperty(false, false);
10436                } else {
10437                    final ViewParent p = mParent;
10438                    if (p != null && mAttachInfo != null) {
10439                        final Rect r = mAttachInfo.mTmpInvalRect;
10440                        int minLeft;
10441                        int maxRight;
10442                        if (offset < 0) {
10443                            minLeft = mLeft + offset;
10444                            maxRight = mRight;
10445                        } else {
10446                            minLeft = mLeft;
10447                            maxRight = mRight + offset;
10448                        }
10449                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10450                        p.invalidateChild(this, r);
10451                    }
10452                }
10453            } else {
10454                invalidateViewProperty(false, false);
10455            }
10456
10457            mLeft += offset;
10458            mRight += offset;
10459            if (mDisplayList != null) {
10460                mDisplayList.offsetLeftAndRight(offset);
10461                invalidateViewProperty(false, false);
10462            } else {
10463                if (!matrixIsIdentity) {
10464                    invalidateViewProperty(false, true);
10465                }
10466                invalidateParentIfNeeded();
10467            }
10468        }
10469    }
10470
10471    /**
10472     * Get the LayoutParams associated with this view. All views should have
10473     * layout parameters. These supply parameters to the <i>parent</i> of this
10474     * view specifying how it should be arranged. There are many subclasses of
10475     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10476     * of ViewGroup that are responsible for arranging their children.
10477     *
10478     * This method may return null if this View is not attached to a parent
10479     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10480     * was not invoked successfully. When a View is attached to a parent
10481     * ViewGroup, this method must not return null.
10482     *
10483     * @return The LayoutParams associated with this view, or null if no
10484     *         parameters have been set yet
10485     */
10486    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10487    public ViewGroup.LayoutParams getLayoutParams() {
10488        return mLayoutParams;
10489    }
10490
10491    /**
10492     * Set the layout parameters associated with this view. These supply
10493     * parameters to the <i>parent</i> of this view specifying how it should be
10494     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10495     * correspond to the different subclasses of ViewGroup that are responsible
10496     * for arranging their children.
10497     *
10498     * @param params The layout parameters for this view, cannot be null
10499     */
10500    public void setLayoutParams(ViewGroup.LayoutParams params) {
10501        if (params == null) {
10502            throw new NullPointerException("Layout parameters cannot be null");
10503        }
10504        mLayoutParams = params;
10505        resolveLayoutParams();
10506        if (mParent instanceof ViewGroup) {
10507            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10508        }
10509        requestLayout();
10510    }
10511
10512    /**
10513     * Resolve the layout parameters depending on the resolved layout direction
10514     *
10515     * @hide
10516     */
10517    public void resolveLayoutParams() {
10518        if (mLayoutParams != null) {
10519            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10520        }
10521    }
10522
10523    /**
10524     * Set the scrolled position of your view. This will cause a call to
10525     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10526     * invalidated.
10527     * @param x the x position to scroll to
10528     * @param y the y position to scroll to
10529     */
10530    public void scrollTo(int x, int y) {
10531        if (mScrollX != x || mScrollY != y) {
10532            int oldX = mScrollX;
10533            int oldY = mScrollY;
10534            mScrollX = x;
10535            mScrollY = y;
10536            invalidateParentCaches();
10537            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10538            if (!awakenScrollBars()) {
10539                postInvalidateOnAnimation();
10540            }
10541        }
10542    }
10543
10544    /**
10545     * Move the scrolled position of your view. This will cause a call to
10546     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10547     * invalidated.
10548     * @param x the amount of pixels to scroll by horizontally
10549     * @param y the amount of pixels to scroll by vertically
10550     */
10551    public void scrollBy(int x, int y) {
10552        scrollTo(mScrollX + x, mScrollY + y);
10553    }
10554
10555    /**
10556     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10557     * animation to fade the scrollbars out after a default delay. If a subclass
10558     * provides animated scrolling, the start delay should equal the duration
10559     * of the scrolling animation.</p>
10560     *
10561     * <p>The animation starts only if at least one of the scrollbars is
10562     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10563     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10564     * this method returns true, and false otherwise. If the animation is
10565     * started, this method calls {@link #invalidate()}; in that case the
10566     * caller should not call {@link #invalidate()}.</p>
10567     *
10568     * <p>This method should be invoked every time a subclass directly updates
10569     * the scroll parameters.</p>
10570     *
10571     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10572     * and {@link #scrollTo(int, int)}.</p>
10573     *
10574     * @return true if the animation is played, false otherwise
10575     *
10576     * @see #awakenScrollBars(int)
10577     * @see #scrollBy(int, int)
10578     * @see #scrollTo(int, int)
10579     * @see #isHorizontalScrollBarEnabled()
10580     * @see #isVerticalScrollBarEnabled()
10581     * @see #setHorizontalScrollBarEnabled(boolean)
10582     * @see #setVerticalScrollBarEnabled(boolean)
10583     */
10584    protected boolean awakenScrollBars() {
10585        return mScrollCache != null &&
10586                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10587    }
10588
10589    /**
10590     * Trigger the scrollbars to draw.
10591     * This method differs from awakenScrollBars() only in its default duration.
10592     * initialAwakenScrollBars() will show the scroll bars for longer than
10593     * usual to give the user more of a chance to notice them.
10594     *
10595     * @return true if the animation is played, false otherwise.
10596     */
10597    private boolean initialAwakenScrollBars() {
10598        return mScrollCache != null &&
10599                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10600    }
10601
10602    /**
10603     * <p>
10604     * Trigger the scrollbars to draw. When invoked this method starts an
10605     * animation to fade the scrollbars out after a fixed delay. If a subclass
10606     * provides animated scrolling, the start delay should equal the duration of
10607     * the scrolling animation.
10608     * </p>
10609     *
10610     * <p>
10611     * The animation starts only if at least one of the scrollbars is enabled,
10612     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10613     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10614     * this method returns true, and false otherwise. If the animation is
10615     * started, this method calls {@link #invalidate()}; in that case the caller
10616     * should not call {@link #invalidate()}.
10617     * </p>
10618     *
10619     * <p>
10620     * This method should be invoked everytime a subclass directly updates the
10621     * scroll parameters.
10622     * </p>
10623     *
10624     * @param startDelay the delay, in milliseconds, after which the animation
10625     *        should start; when the delay is 0, the animation starts
10626     *        immediately
10627     * @return true if the animation is played, false otherwise
10628     *
10629     * @see #scrollBy(int, int)
10630     * @see #scrollTo(int, int)
10631     * @see #isHorizontalScrollBarEnabled()
10632     * @see #isVerticalScrollBarEnabled()
10633     * @see #setHorizontalScrollBarEnabled(boolean)
10634     * @see #setVerticalScrollBarEnabled(boolean)
10635     */
10636    protected boolean awakenScrollBars(int startDelay) {
10637        return awakenScrollBars(startDelay, true);
10638    }
10639
10640    /**
10641     * <p>
10642     * Trigger the scrollbars to draw. When invoked this method starts an
10643     * animation to fade the scrollbars out after a fixed delay. If a subclass
10644     * provides animated scrolling, the start delay should equal the duration of
10645     * the scrolling animation.
10646     * </p>
10647     *
10648     * <p>
10649     * The animation starts only if at least one of the scrollbars is enabled,
10650     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10651     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10652     * this method returns true, and false otherwise. If the animation is
10653     * started, this method calls {@link #invalidate()} if the invalidate parameter
10654     * is set to true; in that case the caller
10655     * should not call {@link #invalidate()}.
10656     * </p>
10657     *
10658     * <p>
10659     * This method should be invoked everytime a subclass directly updates the
10660     * scroll parameters.
10661     * </p>
10662     *
10663     * @param startDelay the delay, in milliseconds, after which the animation
10664     *        should start; when the delay is 0, the animation starts
10665     *        immediately
10666     *
10667     * @param invalidate Wheter this method should call invalidate
10668     *
10669     * @return true if the animation is played, false otherwise
10670     *
10671     * @see #scrollBy(int, int)
10672     * @see #scrollTo(int, int)
10673     * @see #isHorizontalScrollBarEnabled()
10674     * @see #isVerticalScrollBarEnabled()
10675     * @see #setHorizontalScrollBarEnabled(boolean)
10676     * @see #setVerticalScrollBarEnabled(boolean)
10677     */
10678    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10679        final ScrollabilityCache scrollCache = mScrollCache;
10680
10681        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10682            return false;
10683        }
10684
10685        if (scrollCache.scrollBar == null) {
10686            scrollCache.scrollBar = new ScrollBarDrawable();
10687        }
10688
10689        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10690
10691            if (invalidate) {
10692                // Invalidate to show the scrollbars
10693                postInvalidateOnAnimation();
10694            }
10695
10696            if (scrollCache.state == ScrollabilityCache.OFF) {
10697                // FIXME: this is copied from WindowManagerService.
10698                // We should get this value from the system when it
10699                // is possible to do so.
10700                final int KEY_REPEAT_FIRST_DELAY = 750;
10701                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10702            }
10703
10704            // Tell mScrollCache when we should start fading. This may
10705            // extend the fade start time if one was already scheduled
10706            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10707            scrollCache.fadeStartTime = fadeStartTime;
10708            scrollCache.state = ScrollabilityCache.ON;
10709
10710            // Schedule our fader to run, unscheduling any old ones first
10711            if (mAttachInfo != null) {
10712                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10713                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10714            }
10715
10716            return true;
10717        }
10718
10719        return false;
10720    }
10721
10722    /**
10723     * Do not invalidate views which are not visible and which are not running an animation. They
10724     * will not get drawn and they should not set dirty flags as if they will be drawn
10725     */
10726    private boolean skipInvalidate() {
10727        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10728                (!(mParent instanceof ViewGroup) ||
10729                        !((ViewGroup) mParent).isViewTransitioning(this));
10730    }
10731    /**
10732     * Mark the area defined by dirty as needing to be drawn. If the view is
10733     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10734     * in the future. This must be called from a UI thread. To call from a non-UI
10735     * thread, call {@link #postInvalidate()}.
10736     *
10737     * WARNING: This method is destructive to dirty.
10738     * @param dirty the rectangle representing the bounds of the dirty region
10739     */
10740    public void invalidate(Rect dirty) {
10741        if (skipInvalidate()) {
10742            return;
10743        }
10744        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10745                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10746                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10747            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10748            mPrivateFlags |= PFLAG_INVALIDATED;
10749            mPrivateFlags |= PFLAG_DIRTY;
10750            final ViewParent p = mParent;
10751            final AttachInfo ai = mAttachInfo;
10752            //noinspection PointlessBooleanExpression,ConstantConditions
10753            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10754                if (p != null && ai != null && ai.mHardwareAccelerated) {
10755                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10756                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10757                    p.invalidateChild(this, null);
10758                    return;
10759                }
10760            }
10761            if (p != null && ai != null) {
10762                final int scrollX = mScrollX;
10763                final int scrollY = mScrollY;
10764                final Rect r = ai.mTmpInvalRect;
10765                r.set(dirty.left - scrollX, dirty.top - scrollY,
10766                        dirty.right - scrollX, dirty.bottom - scrollY);
10767                mParent.invalidateChild(this, r);
10768            }
10769        }
10770    }
10771
10772    /**
10773     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10774     * The coordinates of the dirty rect are relative to the view.
10775     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10776     * will be called at some point in the future. This must be called from
10777     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10778     * @param l the left position of the dirty region
10779     * @param t the top position of the dirty region
10780     * @param r the right position of the dirty region
10781     * @param b the bottom position of the dirty region
10782     */
10783    public void invalidate(int l, int t, int r, int b) {
10784        if (skipInvalidate()) {
10785            return;
10786        }
10787        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10788                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10789                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10790            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10791            mPrivateFlags |= PFLAG_INVALIDATED;
10792            mPrivateFlags |= PFLAG_DIRTY;
10793            final ViewParent p = mParent;
10794            final AttachInfo ai = mAttachInfo;
10795            //noinspection PointlessBooleanExpression,ConstantConditions
10796            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10797                if (p != null && ai != null && ai.mHardwareAccelerated) {
10798                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10799                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10800                    p.invalidateChild(this, null);
10801                    return;
10802                }
10803            }
10804            if (p != null && ai != null && l < r && t < b) {
10805                final int scrollX = mScrollX;
10806                final int scrollY = mScrollY;
10807                final Rect tmpr = ai.mTmpInvalRect;
10808                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10809                p.invalidateChild(this, tmpr);
10810            }
10811        }
10812    }
10813
10814    /**
10815     * Invalidate the whole view. If the view is visible,
10816     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10817     * the future. This must be called from a UI thread. To call from a non-UI thread,
10818     * call {@link #postInvalidate()}.
10819     */
10820    public void invalidate() {
10821        invalidate(true);
10822    }
10823
10824    /**
10825     * This is where the invalidate() work actually happens. A full invalidate()
10826     * causes the drawing cache to be invalidated, but this function can be called with
10827     * invalidateCache set to false to skip that invalidation step for cases that do not
10828     * need it (for example, a component that remains at the same dimensions with the same
10829     * content).
10830     *
10831     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10832     * well. This is usually true for a full invalidate, but may be set to false if the
10833     * View's contents or dimensions have not changed.
10834     */
10835    void invalidate(boolean invalidateCache) {
10836        if (skipInvalidate()) {
10837            return;
10838        }
10839        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10840                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10841                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10842            mLastIsOpaque = isOpaque();
10843            mPrivateFlags &= ~PFLAG_DRAWN;
10844            mPrivateFlags |= PFLAG_DIRTY;
10845            if (invalidateCache) {
10846                mPrivateFlags |= PFLAG_INVALIDATED;
10847                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10848            }
10849            final AttachInfo ai = mAttachInfo;
10850            final ViewParent p = mParent;
10851            //noinspection PointlessBooleanExpression,ConstantConditions
10852            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10853                if (p != null && ai != null && ai.mHardwareAccelerated) {
10854                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10855                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10856                    p.invalidateChild(this, null);
10857                    return;
10858                }
10859            }
10860
10861            if (p != null && ai != null) {
10862                final Rect r = ai.mTmpInvalRect;
10863                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10864                // Don't call invalidate -- we don't want to internally scroll
10865                // our own bounds
10866                p.invalidateChild(this, r);
10867            }
10868        }
10869    }
10870
10871    /**
10872     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10873     * set any flags or handle all of the cases handled by the default invalidation methods.
10874     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10875     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10876     * walk up the hierarchy, transforming the dirty rect as necessary.
10877     *
10878     * The method also handles normal invalidation logic if display list properties are not
10879     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10880     * backup approach, to handle these cases used in the various property-setting methods.
10881     *
10882     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10883     * are not being used in this view
10884     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10885     * list properties are not being used in this view
10886     */
10887    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10888        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10889            if (invalidateParent) {
10890                invalidateParentCaches();
10891            }
10892            if (forceRedraw) {
10893                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10894            }
10895            invalidate(false);
10896        } else {
10897            final AttachInfo ai = mAttachInfo;
10898            final ViewParent p = mParent;
10899            if (p != null && ai != null) {
10900                final Rect r = ai.mTmpInvalRect;
10901                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10902                if (mParent instanceof ViewGroup) {
10903                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10904                } else {
10905                    mParent.invalidateChild(this, r);
10906                }
10907            }
10908        }
10909    }
10910
10911    /**
10912     * Utility method to transform a given Rect by the current matrix of this view.
10913     */
10914    void transformRect(final Rect rect) {
10915        if (!getMatrix().isIdentity()) {
10916            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10917            boundingRect.set(rect);
10918            getMatrix().mapRect(boundingRect);
10919            rect.set((int) Math.floor(boundingRect.left),
10920                    (int) Math.floor(boundingRect.top),
10921                    (int) Math.ceil(boundingRect.right),
10922                    (int) Math.ceil(boundingRect.bottom));
10923        }
10924    }
10925
10926    /**
10927     * Used to indicate that the parent of this view should clear its caches. This functionality
10928     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10929     * which is necessary when various parent-managed properties of the view change, such as
10930     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10931     * clears the parent caches and does not causes an invalidate event.
10932     *
10933     * @hide
10934     */
10935    protected void invalidateParentCaches() {
10936        if (mParent instanceof View) {
10937            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10938        }
10939    }
10940
10941    /**
10942     * Used to indicate that the parent of this view should be invalidated. This functionality
10943     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10944     * which is necessary when various parent-managed properties of the view change, such as
10945     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10946     * an invalidation event to the parent.
10947     *
10948     * @hide
10949     */
10950    protected void invalidateParentIfNeeded() {
10951        if (isHardwareAccelerated() && mParent instanceof View) {
10952            ((View) mParent).invalidate(true);
10953        }
10954    }
10955
10956    /**
10957     * Indicates whether this View is opaque. An opaque View guarantees that it will
10958     * draw all the pixels overlapping its bounds using a fully opaque color.
10959     *
10960     * Subclasses of View should override this method whenever possible to indicate
10961     * whether an instance is opaque. Opaque Views are treated in a special way by
10962     * the View hierarchy, possibly allowing it to perform optimizations during
10963     * invalidate/draw passes.
10964     *
10965     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10966     */
10967    @ViewDebug.ExportedProperty(category = "drawing")
10968    public boolean isOpaque() {
10969        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10970                getFinalAlpha() >= 1.0f;
10971    }
10972
10973    /**
10974     * @hide
10975     */
10976    protected void computeOpaqueFlags() {
10977        // Opaque if:
10978        //   - Has a background
10979        //   - Background is opaque
10980        //   - Doesn't have scrollbars or scrollbars overlay
10981
10982        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10983            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10984        } else {
10985            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10986        }
10987
10988        final int flags = mViewFlags;
10989        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10990                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10991                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10992            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10993        } else {
10994            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10995        }
10996    }
10997
10998    /**
10999     * @hide
11000     */
11001    protected boolean hasOpaqueScrollbars() {
11002        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11003    }
11004
11005    /**
11006     * @return A handler associated with the thread running the View. This
11007     * handler can be used to pump events in the UI events queue.
11008     */
11009    public Handler getHandler() {
11010        final AttachInfo attachInfo = mAttachInfo;
11011        if (attachInfo != null) {
11012            return attachInfo.mHandler;
11013        }
11014        return null;
11015    }
11016
11017    /**
11018     * Gets the view root associated with the View.
11019     * @return The view root, or null if none.
11020     * @hide
11021     */
11022    public ViewRootImpl getViewRootImpl() {
11023        if (mAttachInfo != null) {
11024            return mAttachInfo.mViewRootImpl;
11025        }
11026        return null;
11027    }
11028
11029    /**
11030     * <p>Causes the Runnable to be added to the message queue.
11031     * The runnable will be run on the user interface thread.</p>
11032     *
11033     * @param action The Runnable that will be executed.
11034     *
11035     * @return Returns true if the Runnable was successfully placed in to the
11036     *         message queue.  Returns false on failure, usually because the
11037     *         looper processing the message queue is exiting.
11038     *
11039     * @see #postDelayed
11040     * @see #removeCallbacks
11041     */
11042    public boolean post(Runnable action) {
11043        final AttachInfo attachInfo = mAttachInfo;
11044        if (attachInfo != null) {
11045            return attachInfo.mHandler.post(action);
11046        }
11047        // Assume that post will succeed later
11048        ViewRootImpl.getRunQueue().post(action);
11049        return true;
11050    }
11051
11052    /**
11053     * <p>Causes the Runnable to be added to the message queue, to be run
11054     * after the specified amount of time elapses.
11055     * The runnable will be run on the user interface thread.</p>
11056     *
11057     * @param action The Runnable that will be executed.
11058     * @param delayMillis The delay (in milliseconds) until the Runnable
11059     *        will be executed.
11060     *
11061     * @return true if the Runnable was successfully placed in to the
11062     *         message queue.  Returns false on failure, usually because the
11063     *         looper processing the message queue is exiting.  Note that a
11064     *         result of true does not mean the Runnable will be processed --
11065     *         if the looper is quit before the delivery time of the message
11066     *         occurs then the message will be dropped.
11067     *
11068     * @see #post
11069     * @see #removeCallbacks
11070     */
11071    public boolean postDelayed(Runnable action, long delayMillis) {
11072        final AttachInfo attachInfo = mAttachInfo;
11073        if (attachInfo != null) {
11074            return attachInfo.mHandler.postDelayed(action, delayMillis);
11075        }
11076        // Assume that post will succeed later
11077        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11078        return true;
11079    }
11080
11081    /**
11082     * <p>Causes the Runnable to execute on the next animation time step.
11083     * The runnable will be run on the user interface thread.</p>
11084     *
11085     * @param action The Runnable that will be executed.
11086     *
11087     * @see #postOnAnimationDelayed
11088     * @see #removeCallbacks
11089     */
11090    public void postOnAnimation(Runnable action) {
11091        final AttachInfo attachInfo = mAttachInfo;
11092        if (attachInfo != null) {
11093            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11094                    Choreographer.CALLBACK_ANIMATION, action, null);
11095        } else {
11096            // Assume that post will succeed later
11097            ViewRootImpl.getRunQueue().post(action);
11098        }
11099    }
11100
11101    /**
11102     * <p>Causes the Runnable to execute on the next animation time step,
11103     * after the specified amount of time elapses.
11104     * The runnable will be run on the user interface thread.</p>
11105     *
11106     * @param action The Runnable that will be executed.
11107     * @param delayMillis The delay (in milliseconds) until the Runnable
11108     *        will be executed.
11109     *
11110     * @see #postOnAnimation
11111     * @see #removeCallbacks
11112     */
11113    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11114        final AttachInfo attachInfo = mAttachInfo;
11115        if (attachInfo != null) {
11116            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11117                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11118        } else {
11119            // Assume that post will succeed later
11120            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11121        }
11122    }
11123
11124    /**
11125     * <p>Removes the specified Runnable from the message queue.</p>
11126     *
11127     * @param action The Runnable to remove from the message handling queue
11128     *
11129     * @return true if this view could ask the Handler to remove the Runnable,
11130     *         false otherwise. When the returned value is true, the Runnable
11131     *         may or may not have been actually removed from the message queue
11132     *         (for instance, if the Runnable was not in the queue already.)
11133     *
11134     * @see #post
11135     * @see #postDelayed
11136     * @see #postOnAnimation
11137     * @see #postOnAnimationDelayed
11138     */
11139    public boolean removeCallbacks(Runnable action) {
11140        if (action != null) {
11141            final AttachInfo attachInfo = mAttachInfo;
11142            if (attachInfo != null) {
11143                attachInfo.mHandler.removeCallbacks(action);
11144                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11145                        Choreographer.CALLBACK_ANIMATION, action, null);
11146            } else {
11147                // Assume that post will succeed later
11148                ViewRootImpl.getRunQueue().removeCallbacks(action);
11149            }
11150        }
11151        return true;
11152    }
11153
11154    /**
11155     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11156     * Use this to invalidate the View from a non-UI thread.</p>
11157     *
11158     * <p>This method can be invoked from outside of the UI thread
11159     * only when this View is attached to a window.</p>
11160     *
11161     * @see #invalidate()
11162     * @see #postInvalidateDelayed(long)
11163     */
11164    public void postInvalidate() {
11165        postInvalidateDelayed(0);
11166    }
11167
11168    /**
11169     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11170     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11171     *
11172     * <p>This method can be invoked from outside of the UI thread
11173     * only when this View is attached to a window.</p>
11174     *
11175     * @param left The left coordinate of the rectangle to invalidate.
11176     * @param top The top coordinate of the rectangle to invalidate.
11177     * @param right The right coordinate of the rectangle to invalidate.
11178     * @param bottom The bottom coordinate of the rectangle to invalidate.
11179     *
11180     * @see #invalidate(int, int, int, int)
11181     * @see #invalidate(Rect)
11182     * @see #postInvalidateDelayed(long, int, int, int, int)
11183     */
11184    public void postInvalidate(int left, int top, int right, int bottom) {
11185        postInvalidateDelayed(0, left, top, right, bottom);
11186    }
11187
11188    /**
11189     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11190     * loop. Waits for the specified amount of time.</p>
11191     *
11192     * <p>This method can be invoked from outside of the UI thread
11193     * only when this View is attached to a window.</p>
11194     *
11195     * @param delayMilliseconds the duration in milliseconds to delay the
11196     *         invalidation by
11197     *
11198     * @see #invalidate()
11199     * @see #postInvalidate()
11200     */
11201    public void postInvalidateDelayed(long delayMilliseconds) {
11202        // We try only with the AttachInfo because there's no point in invalidating
11203        // if we are not attached to our window
11204        final AttachInfo attachInfo = mAttachInfo;
11205        if (attachInfo != null) {
11206            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11207        }
11208    }
11209
11210    /**
11211     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11212     * through the event loop. Waits for the specified amount of time.</p>
11213     *
11214     * <p>This method can be invoked from outside of the UI thread
11215     * only when this View is attached to a window.</p>
11216     *
11217     * @param delayMilliseconds the duration in milliseconds to delay the
11218     *         invalidation by
11219     * @param left The left coordinate of the rectangle to invalidate.
11220     * @param top The top coordinate of the rectangle to invalidate.
11221     * @param right The right coordinate of the rectangle to invalidate.
11222     * @param bottom The bottom coordinate of the rectangle to invalidate.
11223     *
11224     * @see #invalidate(int, int, int, int)
11225     * @see #invalidate(Rect)
11226     * @see #postInvalidate(int, int, int, int)
11227     */
11228    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11229            int right, int bottom) {
11230
11231        // We try only with the AttachInfo because there's no point in invalidating
11232        // if we are not attached to our window
11233        final AttachInfo attachInfo = mAttachInfo;
11234        if (attachInfo != null) {
11235            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11236            info.target = this;
11237            info.left = left;
11238            info.top = top;
11239            info.right = right;
11240            info.bottom = bottom;
11241
11242            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11243        }
11244    }
11245
11246    /**
11247     * <p>Cause an invalidate to happen on the next animation time step, typically the
11248     * next display frame.</p>
11249     *
11250     * <p>This method can be invoked from outside of the UI thread
11251     * only when this View is attached to a window.</p>
11252     *
11253     * @see #invalidate()
11254     */
11255    public void postInvalidateOnAnimation() {
11256        // We try only with the AttachInfo because there's no point in invalidating
11257        // if we are not attached to our window
11258        final AttachInfo attachInfo = mAttachInfo;
11259        if (attachInfo != null) {
11260            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11261        }
11262    }
11263
11264    /**
11265     * <p>Cause an invalidate of the specified area to happen on the next animation
11266     * time step, typically the next display frame.</p>
11267     *
11268     * <p>This method can be invoked from outside of the UI thread
11269     * only when this View is attached to a window.</p>
11270     *
11271     * @param left The left coordinate of the rectangle to invalidate.
11272     * @param top The top coordinate of the rectangle to invalidate.
11273     * @param right The right coordinate of the rectangle to invalidate.
11274     * @param bottom The bottom coordinate of the rectangle to invalidate.
11275     *
11276     * @see #invalidate(int, int, int, int)
11277     * @see #invalidate(Rect)
11278     */
11279    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11280        // We try only with the AttachInfo because there's no point in invalidating
11281        // if we are not attached to our window
11282        final AttachInfo attachInfo = mAttachInfo;
11283        if (attachInfo != null) {
11284            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11285            info.target = this;
11286            info.left = left;
11287            info.top = top;
11288            info.right = right;
11289            info.bottom = bottom;
11290
11291            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11292        }
11293    }
11294
11295    /**
11296     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11297     * This event is sent at most once every
11298     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11299     */
11300    private void postSendViewScrolledAccessibilityEventCallback() {
11301        if (mSendViewScrolledAccessibilityEvent == null) {
11302            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11303        }
11304        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11305            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11306            postDelayed(mSendViewScrolledAccessibilityEvent,
11307                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11308        }
11309    }
11310
11311    /**
11312     * Called by a parent to request that a child update its values for mScrollX
11313     * and mScrollY if necessary. This will typically be done if the child is
11314     * animating a scroll using a {@link android.widget.Scroller Scroller}
11315     * object.
11316     */
11317    public void computeScroll() {
11318    }
11319
11320    /**
11321     * <p>Indicate whether the horizontal edges are faded when the view is
11322     * scrolled horizontally.</p>
11323     *
11324     * @return true if the horizontal edges should are faded on scroll, false
11325     *         otherwise
11326     *
11327     * @see #setHorizontalFadingEdgeEnabled(boolean)
11328     *
11329     * @attr ref android.R.styleable#View_requiresFadingEdge
11330     */
11331    public boolean isHorizontalFadingEdgeEnabled() {
11332        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11333    }
11334
11335    /**
11336     * <p>Define whether the horizontal edges should be faded when this view
11337     * is scrolled horizontally.</p>
11338     *
11339     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11340     *                                    be faded when the view is scrolled
11341     *                                    horizontally
11342     *
11343     * @see #isHorizontalFadingEdgeEnabled()
11344     *
11345     * @attr ref android.R.styleable#View_requiresFadingEdge
11346     */
11347    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11348        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11349            if (horizontalFadingEdgeEnabled) {
11350                initScrollCache();
11351            }
11352
11353            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11354        }
11355    }
11356
11357    /**
11358     * <p>Indicate whether the vertical edges are faded when the view is
11359     * scrolled horizontally.</p>
11360     *
11361     * @return true if the vertical edges should are faded on scroll, false
11362     *         otherwise
11363     *
11364     * @see #setVerticalFadingEdgeEnabled(boolean)
11365     *
11366     * @attr ref android.R.styleable#View_requiresFadingEdge
11367     */
11368    public boolean isVerticalFadingEdgeEnabled() {
11369        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11370    }
11371
11372    /**
11373     * <p>Define whether the vertical edges should be faded when this view
11374     * is scrolled vertically.</p>
11375     *
11376     * @param verticalFadingEdgeEnabled true if the vertical edges should
11377     *                                  be faded when the view is scrolled
11378     *                                  vertically
11379     *
11380     * @see #isVerticalFadingEdgeEnabled()
11381     *
11382     * @attr ref android.R.styleable#View_requiresFadingEdge
11383     */
11384    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11385        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11386            if (verticalFadingEdgeEnabled) {
11387                initScrollCache();
11388            }
11389
11390            mViewFlags ^= FADING_EDGE_VERTICAL;
11391        }
11392    }
11393
11394    /**
11395     * Returns the strength, or intensity, of the top faded edge. The strength is
11396     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11397     * returns 0.0 or 1.0 but no value in between.
11398     *
11399     * Subclasses should override this method to provide a smoother fade transition
11400     * when scrolling occurs.
11401     *
11402     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11403     */
11404    protected float getTopFadingEdgeStrength() {
11405        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11406    }
11407
11408    /**
11409     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11410     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11411     * returns 0.0 or 1.0 but no value in between.
11412     *
11413     * Subclasses should override this method to provide a smoother fade transition
11414     * when scrolling occurs.
11415     *
11416     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11417     */
11418    protected float getBottomFadingEdgeStrength() {
11419        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11420                computeVerticalScrollRange() ? 1.0f : 0.0f;
11421    }
11422
11423    /**
11424     * Returns the strength, or intensity, of the left faded edge. The strength is
11425     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11426     * returns 0.0 or 1.0 but no value in between.
11427     *
11428     * Subclasses should override this method to provide a smoother fade transition
11429     * when scrolling occurs.
11430     *
11431     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11432     */
11433    protected float getLeftFadingEdgeStrength() {
11434        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11435    }
11436
11437    /**
11438     * Returns the strength, or intensity, of the right faded edge. The strength is
11439     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11440     * returns 0.0 or 1.0 but no value in between.
11441     *
11442     * Subclasses should override this method to provide a smoother fade transition
11443     * when scrolling occurs.
11444     *
11445     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11446     */
11447    protected float getRightFadingEdgeStrength() {
11448        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11449                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11450    }
11451
11452    /**
11453     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11454     * scrollbar is not drawn by default.</p>
11455     *
11456     * @return true if the horizontal scrollbar should be painted, false
11457     *         otherwise
11458     *
11459     * @see #setHorizontalScrollBarEnabled(boolean)
11460     */
11461    public boolean isHorizontalScrollBarEnabled() {
11462        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11463    }
11464
11465    /**
11466     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11467     * scrollbar is not drawn by default.</p>
11468     *
11469     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11470     *                                   be painted
11471     *
11472     * @see #isHorizontalScrollBarEnabled()
11473     */
11474    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11475        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11476            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11477            computeOpaqueFlags();
11478            resolvePadding();
11479        }
11480    }
11481
11482    /**
11483     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11484     * scrollbar is not drawn by default.</p>
11485     *
11486     * @return true if the vertical scrollbar should be painted, false
11487     *         otherwise
11488     *
11489     * @see #setVerticalScrollBarEnabled(boolean)
11490     */
11491    public boolean isVerticalScrollBarEnabled() {
11492        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11493    }
11494
11495    /**
11496     * <p>Define whether the vertical scrollbar should be drawn or not. The
11497     * scrollbar is not drawn by default.</p>
11498     *
11499     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11500     *                                 be painted
11501     *
11502     * @see #isVerticalScrollBarEnabled()
11503     */
11504    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11505        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11506            mViewFlags ^= SCROLLBARS_VERTICAL;
11507            computeOpaqueFlags();
11508            resolvePadding();
11509        }
11510    }
11511
11512    /**
11513     * @hide
11514     */
11515    protected void recomputePadding() {
11516        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11517    }
11518
11519    /**
11520     * Define whether scrollbars will fade when the view is not scrolling.
11521     *
11522     * @param fadeScrollbars wheter to enable fading
11523     *
11524     * @attr ref android.R.styleable#View_fadeScrollbars
11525     */
11526    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11527        initScrollCache();
11528        final ScrollabilityCache scrollabilityCache = mScrollCache;
11529        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11530        if (fadeScrollbars) {
11531            scrollabilityCache.state = ScrollabilityCache.OFF;
11532        } else {
11533            scrollabilityCache.state = ScrollabilityCache.ON;
11534        }
11535    }
11536
11537    /**
11538     *
11539     * Returns true if scrollbars will fade when this view is not scrolling
11540     *
11541     * @return true if scrollbar fading is enabled
11542     *
11543     * @attr ref android.R.styleable#View_fadeScrollbars
11544     */
11545    public boolean isScrollbarFadingEnabled() {
11546        return mScrollCache != null && mScrollCache.fadeScrollBars;
11547    }
11548
11549    /**
11550     *
11551     * Returns the delay before scrollbars fade.
11552     *
11553     * @return the delay before scrollbars fade
11554     *
11555     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11556     */
11557    public int getScrollBarDefaultDelayBeforeFade() {
11558        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11559                mScrollCache.scrollBarDefaultDelayBeforeFade;
11560    }
11561
11562    /**
11563     * Define the delay before scrollbars fade.
11564     *
11565     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11566     *
11567     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11568     */
11569    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11570        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11571    }
11572
11573    /**
11574     *
11575     * Returns the scrollbar fade duration.
11576     *
11577     * @return the scrollbar fade duration
11578     *
11579     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11580     */
11581    public int getScrollBarFadeDuration() {
11582        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11583                mScrollCache.scrollBarFadeDuration;
11584    }
11585
11586    /**
11587     * Define the scrollbar fade duration.
11588     *
11589     * @param scrollBarFadeDuration - the scrollbar fade duration
11590     *
11591     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11592     */
11593    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11594        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11595    }
11596
11597    /**
11598     *
11599     * Returns the scrollbar size.
11600     *
11601     * @return the scrollbar size
11602     *
11603     * @attr ref android.R.styleable#View_scrollbarSize
11604     */
11605    public int getScrollBarSize() {
11606        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11607                mScrollCache.scrollBarSize;
11608    }
11609
11610    /**
11611     * Define the scrollbar size.
11612     *
11613     * @param scrollBarSize - the scrollbar size
11614     *
11615     * @attr ref android.R.styleable#View_scrollbarSize
11616     */
11617    public void setScrollBarSize(int scrollBarSize) {
11618        getScrollCache().scrollBarSize = scrollBarSize;
11619    }
11620
11621    /**
11622     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11623     * inset. When inset, they add to the padding of the view. And the scrollbars
11624     * can be drawn inside the padding area or on the edge of the view. For example,
11625     * if a view has a background drawable and you want to draw the scrollbars
11626     * inside the padding specified by the drawable, you can use
11627     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11628     * appear at the edge of the view, ignoring the padding, then you can use
11629     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11630     * @param style the style of the scrollbars. Should be one of
11631     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11632     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11633     * @see #SCROLLBARS_INSIDE_OVERLAY
11634     * @see #SCROLLBARS_INSIDE_INSET
11635     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11636     * @see #SCROLLBARS_OUTSIDE_INSET
11637     *
11638     * @attr ref android.R.styleable#View_scrollbarStyle
11639     */
11640    public void setScrollBarStyle(int style) {
11641        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11642            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11643            computeOpaqueFlags();
11644            resolvePadding();
11645        }
11646    }
11647
11648    /**
11649     * <p>Returns the current scrollbar style.</p>
11650     * @return the current scrollbar style
11651     * @see #SCROLLBARS_INSIDE_OVERLAY
11652     * @see #SCROLLBARS_INSIDE_INSET
11653     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11654     * @see #SCROLLBARS_OUTSIDE_INSET
11655     *
11656     * @attr ref android.R.styleable#View_scrollbarStyle
11657     */
11658    @ViewDebug.ExportedProperty(mapping = {
11659            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11660            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11661            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11662            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11663    })
11664    public int getScrollBarStyle() {
11665        return mViewFlags & SCROLLBARS_STYLE_MASK;
11666    }
11667
11668    /**
11669     * <p>Compute the horizontal range that the horizontal scrollbar
11670     * represents.</p>
11671     *
11672     * <p>The range is expressed in arbitrary units that must be the same as the
11673     * units used by {@link #computeHorizontalScrollExtent()} and
11674     * {@link #computeHorizontalScrollOffset()}.</p>
11675     *
11676     * <p>The default range is the drawing width of this view.</p>
11677     *
11678     * @return the total horizontal range represented by the horizontal
11679     *         scrollbar
11680     *
11681     * @see #computeHorizontalScrollExtent()
11682     * @see #computeHorizontalScrollOffset()
11683     * @see android.widget.ScrollBarDrawable
11684     */
11685    protected int computeHorizontalScrollRange() {
11686        return getWidth();
11687    }
11688
11689    /**
11690     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11691     * within the horizontal range. This value is used to compute the position
11692     * of the thumb within the scrollbar's track.</p>
11693     *
11694     * <p>The range is expressed in arbitrary units that must be the same as the
11695     * units used by {@link #computeHorizontalScrollRange()} and
11696     * {@link #computeHorizontalScrollExtent()}.</p>
11697     *
11698     * <p>The default offset is the scroll offset of this view.</p>
11699     *
11700     * @return the horizontal offset of the scrollbar's thumb
11701     *
11702     * @see #computeHorizontalScrollRange()
11703     * @see #computeHorizontalScrollExtent()
11704     * @see android.widget.ScrollBarDrawable
11705     */
11706    protected int computeHorizontalScrollOffset() {
11707        return mScrollX;
11708    }
11709
11710    /**
11711     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11712     * within the horizontal range. This value is used to compute the length
11713     * of the thumb within the scrollbar's track.</p>
11714     *
11715     * <p>The range is expressed in arbitrary units that must be the same as the
11716     * units used by {@link #computeHorizontalScrollRange()} and
11717     * {@link #computeHorizontalScrollOffset()}.</p>
11718     *
11719     * <p>The default extent is the drawing width of this view.</p>
11720     *
11721     * @return the horizontal extent of the scrollbar's thumb
11722     *
11723     * @see #computeHorizontalScrollRange()
11724     * @see #computeHorizontalScrollOffset()
11725     * @see android.widget.ScrollBarDrawable
11726     */
11727    protected int computeHorizontalScrollExtent() {
11728        return getWidth();
11729    }
11730
11731    /**
11732     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11733     *
11734     * <p>The range is expressed in arbitrary units that must be the same as the
11735     * units used by {@link #computeVerticalScrollExtent()} and
11736     * {@link #computeVerticalScrollOffset()}.</p>
11737     *
11738     * @return the total vertical range represented by the vertical scrollbar
11739     *
11740     * <p>The default range is the drawing height of this view.</p>
11741     *
11742     * @see #computeVerticalScrollExtent()
11743     * @see #computeVerticalScrollOffset()
11744     * @see android.widget.ScrollBarDrawable
11745     */
11746    protected int computeVerticalScrollRange() {
11747        return getHeight();
11748    }
11749
11750    /**
11751     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11752     * within the horizontal range. This value is used to compute the position
11753     * of the thumb within the scrollbar's track.</p>
11754     *
11755     * <p>The range is expressed in arbitrary units that must be the same as the
11756     * units used by {@link #computeVerticalScrollRange()} and
11757     * {@link #computeVerticalScrollExtent()}.</p>
11758     *
11759     * <p>The default offset is the scroll offset of this view.</p>
11760     *
11761     * @return the vertical offset of the scrollbar's thumb
11762     *
11763     * @see #computeVerticalScrollRange()
11764     * @see #computeVerticalScrollExtent()
11765     * @see android.widget.ScrollBarDrawable
11766     */
11767    protected int computeVerticalScrollOffset() {
11768        return mScrollY;
11769    }
11770
11771    /**
11772     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11773     * within the vertical range. This value is used to compute the length
11774     * of the thumb within the scrollbar's track.</p>
11775     *
11776     * <p>The range is expressed in arbitrary units that must be the same as the
11777     * units used by {@link #computeVerticalScrollRange()} and
11778     * {@link #computeVerticalScrollOffset()}.</p>
11779     *
11780     * <p>The default extent is the drawing height of this view.</p>
11781     *
11782     * @return the vertical extent of the scrollbar's thumb
11783     *
11784     * @see #computeVerticalScrollRange()
11785     * @see #computeVerticalScrollOffset()
11786     * @see android.widget.ScrollBarDrawable
11787     */
11788    protected int computeVerticalScrollExtent() {
11789        return getHeight();
11790    }
11791
11792    /**
11793     * Check if this view can be scrolled horizontally in a certain direction.
11794     *
11795     * @param direction Negative to check scrolling left, positive to check scrolling right.
11796     * @return true if this view can be scrolled in the specified direction, false otherwise.
11797     */
11798    public boolean canScrollHorizontally(int direction) {
11799        final int offset = computeHorizontalScrollOffset();
11800        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11801        if (range == 0) return false;
11802        if (direction < 0) {
11803            return offset > 0;
11804        } else {
11805            return offset < range - 1;
11806        }
11807    }
11808
11809    /**
11810     * Check if this view can be scrolled vertically in a certain direction.
11811     *
11812     * @param direction Negative to check scrolling up, positive to check scrolling down.
11813     * @return true if this view can be scrolled in the specified direction, false otherwise.
11814     */
11815    public boolean canScrollVertically(int direction) {
11816        final int offset = computeVerticalScrollOffset();
11817        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11818        if (range == 0) return false;
11819        if (direction < 0) {
11820            return offset > 0;
11821        } else {
11822            return offset < range - 1;
11823        }
11824    }
11825
11826    /**
11827     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11828     * scrollbars are painted only if they have been awakened first.</p>
11829     *
11830     * @param canvas the canvas on which to draw the scrollbars
11831     *
11832     * @see #awakenScrollBars(int)
11833     */
11834    protected final void onDrawScrollBars(Canvas canvas) {
11835        // scrollbars are drawn only when the animation is running
11836        final ScrollabilityCache cache = mScrollCache;
11837        if (cache != null) {
11838
11839            int state = cache.state;
11840
11841            if (state == ScrollabilityCache.OFF) {
11842                return;
11843            }
11844
11845            boolean invalidate = false;
11846
11847            if (state == ScrollabilityCache.FADING) {
11848                // We're fading -- get our fade interpolation
11849                if (cache.interpolatorValues == null) {
11850                    cache.interpolatorValues = new float[1];
11851                }
11852
11853                float[] values = cache.interpolatorValues;
11854
11855                // Stops the animation if we're done
11856                if (cache.scrollBarInterpolator.timeToValues(values) ==
11857                        Interpolator.Result.FREEZE_END) {
11858                    cache.state = ScrollabilityCache.OFF;
11859                } else {
11860                    cache.scrollBar.setAlpha(Math.round(values[0]));
11861                }
11862
11863                // This will make the scroll bars inval themselves after
11864                // drawing. We only want this when we're fading so that
11865                // we prevent excessive redraws
11866                invalidate = true;
11867            } else {
11868                // We're just on -- but we may have been fading before so
11869                // reset alpha
11870                cache.scrollBar.setAlpha(255);
11871            }
11872
11873
11874            final int viewFlags = mViewFlags;
11875
11876            final boolean drawHorizontalScrollBar =
11877                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11878            final boolean drawVerticalScrollBar =
11879                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11880                && !isVerticalScrollBarHidden();
11881
11882            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11883                final int width = mRight - mLeft;
11884                final int height = mBottom - mTop;
11885
11886                final ScrollBarDrawable scrollBar = cache.scrollBar;
11887
11888                final int scrollX = mScrollX;
11889                final int scrollY = mScrollY;
11890                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11891
11892                int left;
11893                int top;
11894                int right;
11895                int bottom;
11896
11897                if (drawHorizontalScrollBar) {
11898                    int size = scrollBar.getSize(false);
11899                    if (size <= 0) {
11900                        size = cache.scrollBarSize;
11901                    }
11902
11903                    scrollBar.setParameters(computeHorizontalScrollRange(),
11904                                            computeHorizontalScrollOffset(),
11905                                            computeHorizontalScrollExtent(), false);
11906                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11907                            getVerticalScrollbarWidth() : 0;
11908                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11909                    left = scrollX + (mPaddingLeft & inside);
11910                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11911                    bottom = top + size;
11912                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11913                    if (invalidate) {
11914                        invalidate(left, top, right, bottom);
11915                    }
11916                }
11917
11918                if (drawVerticalScrollBar) {
11919                    int size = scrollBar.getSize(true);
11920                    if (size <= 0) {
11921                        size = cache.scrollBarSize;
11922                    }
11923
11924                    scrollBar.setParameters(computeVerticalScrollRange(),
11925                                            computeVerticalScrollOffset(),
11926                                            computeVerticalScrollExtent(), true);
11927                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11928                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11929                        verticalScrollbarPosition = isLayoutRtl() ?
11930                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11931                    }
11932                    switch (verticalScrollbarPosition) {
11933                        default:
11934                        case SCROLLBAR_POSITION_RIGHT:
11935                            left = scrollX + width - size - (mUserPaddingRight & inside);
11936                            break;
11937                        case SCROLLBAR_POSITION_LEFT:
11938                            left = scrollX + (mUserPaddingLeft & inside);
11939                            break;
11940                    }
11941                    top = scrollY + (mPaddingTop & inside);
11942                    right = left + size;
11943                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11944                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11945                    if (invalidate) {
11946                        invalidate(left, top, right, bottom);
11947                    }
11948                }
11949            }
11950        }
11951    }
11952
11953    /**
11954     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11955     * FastScroller is visible.
11956     * @return whether to temporarily hide the vertical scrollbar
11957     * @hide
11958     */
11959    protected boolean isVerticalScrollBarHidden() {
11960        return false;
11961    }
11962
11963    /**
11964     * <p>Draw the horizontal scrollbar if
11965     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11966     *
11967     * @param canvas the canvas on which to draw the scrollbar
11968     * @param scrollBar the scrollbar's drawable
11969     *
11970     * @see #isHorizontalScrollBarEnabled()
11971     * @see #computeHorizontalScrollRange()
11972     * @see #computeHorizontalScrollExtent()
11973     * @see #computeHorizontalScrollOffset()
11974     * @see android.widget.ScrollBarDrawable
11975     * @hide
11976     */
11977    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11978            int l, int t, int r, int b) {
11979        scrollBar.setBounds(l, t, r, b);
11980        scrollBar.draw(canvas);
11981    }
11982
11983    /**
11984     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11985     * returns true.</p>
11986     *
11987     * @param canvas the canvas on which to draw the scrollbar
11988     * @param scrollBar the scrollbar's drawable
11989     *
11990     * @see #isVerticalScrollBarEnabled()
11991     * @see #computeVerticalScrollRange()
11992     * @see #computeVerticalScrollExtent()
11993     * @see #computeVerticalScrollOffset()
11994     * @see android.widget.ScrollBarDrawable
11995     * @hide
11996     */
11997    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11998            int l, int t, int r, int b) {
11999        scrollBar.setBounds(l, t, r, b);
12000        scrollBar.draw(canvas);
12001    }
12002
12003    /**
12004     * Implement this to do your drawing.
12005     *
12006     * @param canvas the canvas on which the background will be drawn
12007     */
12008    protected void onDraw(Canvas canvas) {
12009    }
12010
12011    /*
12012     * Caller is responsible for calling requestLayout if necessary.
12013     * (This allows addViewInLayout to not request a new layout.)
12014     */
12015    void assignParent(ViewParent parent) {
12016        if (mParent == null) {
12017            mParent = parent;
12018        } else if (parent == null) {
12019            mParent = null;
12020        } else {
12021            throw new RuntimeException("view " + this + " being added, but"
12022                    + " it already has a parent");
12023        }
12024    }
12025
12026    /**
12027     * This is called when the view is attached to a window.  At this point it
12028     * has a Surface and will start drawing.  Note that this function is
12029     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12030     * however it may be called any time before the first onDraw -- including
12031     * before or after {@link #onMeasure(int, int)}.
12032     *
12033     * @see #onDetachedFromWindow()
12034     */
12035    protected void onAttachedToWindow() {
12036        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12037            mParent.requestTransparentRegion(this);
12038        }
12039
12040        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12041            initialAwakenScrollBars();
12042            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12043        }
12044
12045        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12046
12047        jumpDrawablesToCurrentState();
12048
12049        resetSubtreeAccessibilityStateChanged();
12050
12051        if (isFocused()) {
12052            InputMethodManager imm = InputMethodManager.peekInstance();
12053            imm.focusIn(this);
12054        }
12055
12056        if (mDisplayList != null) {
12057            mDisplayList.clearDirty();
12058        }
12059    }
12060
12061    /**
12062     * Resolve all RTL related properties.
12063     *
12064     * @return true if resolution of RTL properties has been done
12065     *
12066     * @hide
12067     */
12068    public boolean resolveRtlPropertiesIfNeeded() {
12069        if (!needRtlPropertiesResolution()) return false;
12070
12071        // Order is important here: LayoutDirection MUST be resolved first
12072        if (!isLayoutDirectionResolved()) {
12073            resolveLayoutDirection();
12074            resolveLayoutParams();
12075        }
12076        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12077        if (!isTextDirectionResolved()) {
12078            resolveTextDirection();
12079        }
12080        if (!isTextAlignmentResolved()) {
12081            resolveTextAlignment();
12082        }
12083        if (!isPaddingResolved()) {
12084            resolvePadding();
12085        }
12086        if (!isDrawablesResolved()) {
12087            resolveDrawables();
12088        }
12089        onRtlPropertiesChanged(getLayoutDirection());
12090        return true;
12091    }
12092
12093    /**
12094     * Reset resolution of all RTL related properties.
12095     *
12096     * @hide
12097     */
12098    public void resetRtlProperties() {
12099        resetResolvedLayoutDirection();
12100        resetResolvedTextDirection();
12101        resetResolvedTextAlignment();
12102        resetResolvedPadding();
12103        resetResolvedDrawables();
12104    }
12105
12106    /**
12107     * @see #onScreenStateChanged(int)
12108     */
12109    void dispatchScreenStateChanged(int screenState) {
12110        onScreenStateChanged(screenState);
12111    }
12112
12113    /**
12114     * This method is called whenever the state of the screen this view is
12115     * attached to changes. A state change will usually occurs when the screen
12116     * turns on or off (whether it happens automatically or the user does it
12117     * manually.)
12118     *
12119     * @param screenState The new state of the screen. Can be either
12120     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12121     */
12122    public void onScreenStateChanged(int screenState) {
12123    }
12124
12125    /**
12126     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12127     */
12128    private boolean hasRtlSupport() {
12129        return mContext.getApplicationInfo().hasRtlSupport();
12130    }
12131
12132    /**
12133     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12134     * RTL not supported)
12135     */
12136    private boolean isRtlCompatibilityMode() {
12137        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12138        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12139    }
12140
12141    /**
12142     * @return true if RTL properties need resolution.
12143     *
12144     */
12145    private boolean needRtlPropertiesResolution() {
12146        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12147    }
12148
12149    /**
12150     * Called when any RTL property (layout direction or text direction or text alignment) has
12151     * been changed.
12152     *
12153     * Subclasses need to override this method to take care of cached information that depends on the
12154     * resolved layout direction, or to inform child views that inherit their layout direction.
12155     *
12156     * The default implementation does nothing.
12157     *
12158     * @param layoutDirection the direction of the layout
12159     *
12160     * @see #LAYOUT_DIRECTION_LTR
12161     * @see #LAYOUT_DIRECTION_RTL
12162     */
12163    public void onRtlPropertiesChanged(int layoutDirection) {
12164    }
12165
12166    /**
12167     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12168     * that the parent directionality can and will be resolved before its children.
12169     *
12170     * @return true if resolution has been done, false otherwise.
12171     *
12172     * @hide
12173     */
12174    public boolean resolveLayoutDirection() {
12175        // Clear any previous layout direction resolution
12176        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12177
12178        if (hasRtlSupport()) {
12179            // Set resolved depending on layout direction
12180            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12181                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12182                case LAYOUT_DIRECTION_INHERIT:
12183                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12184                    // later to get the correct resolved value
12185                    if (!canResolveLayoutDirection()) return false;
12186
12187                    // Parent has not yet resolved, LTR is still the default
12188                    try {
12189                        if (!mParent.isLayoutDirectionResolved()) return false;
12190
12191                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12192                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12193                        }
12194                    } catch (AbstractMethodError e) {
12195                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12196                                " does not fully implement ViewParent", e);
12197                    }
12198                    break;
12199                case LAYOUT_DIRECTION_RTL:
12200                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12201                    break;
12202                case LAYOUT_DIRECTION_LOCALE:
12203                    if((LAYOUT_DIRECTION_RTL ==
12204                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12205                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12206                    }
12207                    break;
12208                default:
12209                    // Nothing to do, LTR by default
12210            }
12211        }
12212
12213        // Set to resolved
12214        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12215        return true;
12216    }
12217
12218    /**
12219     * Check if layout direction resolution can be done.
12220     *
12221     * @return true if layout direction resolution can be done otherwise return false.
12222     */
12223    public boolean canResolveLayoutDirection() {
12224        switch (getRawLayoutDirection()) {
12225            case LAYOUT_DIRECTION_INHERIT:
12226                if (mParent != null) {
12227                    try {
12228                        return mParent.canResolveLayoutDirection();
12229                    } catch (AbstractMethodError e) {
12230                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12231                                " does not fully implement ViewParent", e);
12232                    }
12233                }
12234                return false;
12235
12236            default:
12237                return true;
12238        }
12239    }
12240
12241    /**
12242     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12243     * {@link #onMeasure(int, int)}.
12244     *
12245     * @hide
12246     */
12247    public void resetResolvedLayoutDirection() {
12248        // Reset the current resolved bits
12249        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12250    }
12251
12252    /**
12253     * @return true if the layout direction is inherited.
12254     *
12255     * @hide
12256     */
12257    public boolean isLayoutDirectionInherited() {
12258        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12259    }
12260
12261    /**
12262     * @return true if layout direction has been resolved.
12263     */
12264    public boolean isLayoutDirectionResolved() {
12265        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12266    }
12267
12268    /**
12269     * Return if padding has been resolved
12270     *
12271     * @hide
12272     */
12273    boolean isPaddingResolved() {
12274        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12275    }
12276
12277    /**
12278     * Resolves padding depending on layout direction, if applicable, and
12279     * recomputes internal padding values to adjust for scroll bars.
12280     *
12281     * @hide
12282     */
12283    public void resolvePadding() {
12284        final int resolvedLayoutDirection = getLayoutDirection();
12285
12286        if (!isRtlCompatibilityMode()) {
12287            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12288            // If start / end padding are defined, they will be resolved (hence overriding) to
12289            // left / right or right / left depending on the resolved layout direction.
12290            // If start / end padding are not defined, use the left / right ones.
12291            switch (resolvedLayoutDirection) {
12292                case LAYOUT_DIRECTION_RTL:
12293                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12294                        mUserPaddingRight = mUserPaddingStart;
12295                    } else {
12296                        mUserPaddingRight = mUserPaddingRightInitial;
12297                    }
12298                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12299                        mUserPaddingLeft = mUserPaddingEnd;
12300                    } else {
12301                        mUserPaddingLeft = mUserPaddingLeftInitial;
12302                    }
12303                    break;
12304                case LAYOUT_DIRECTION_LTR:
12305                default:
12306                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12307                        mUserPaddingLeft = mUserPaddingStart;
12308                    } else {
12309                        mUserPaddingLeft = mUserPaddingLeftInitial;
12310                    }
12311                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12312                        mUserPaddingRight = mUserPaddingEnd;
12313                    } else {
12314                        mUserPaddingRight = mUserPaddingRightInitial;
12315                    }
12316            }
12317
12318            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12319        }
12320
12321        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12322        onRtlPropertiesChanged(resolvedLayoutDirection);
12323
12324        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12325    }
12326
12327    /**
12328     * Reset the resolved layout direction.
12329     *
12330     * @hide
12331     */
12332    public void resetResolvedPadding() {
12333        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12334    }
12335
12336    /**
12337     * This is called when the view is detached from a window.  At this point it
12338     * no longer has a surface for drawing.
12339     *
12340     * @see #onAttachedToWindow()
12341     */
12342    protected void onDetachedFromWindow() {
12343        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12344        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12345
12346        removeUnsetPressCallback();
12347        removeLongPressCallback();
12348        removePerformClickCallback();
12349        removeSendViewScrolledAccessibilityEventCallback();
12350
12351        destroyDrawingCache();
12352        destroyLayer(false);
12353
12354        cleanupDraw();
12355
12356        mCurrentAnimation = null;
12357    }
12358
12359    private void cleanupDraw() {
12360        if (mAttachInfo != null) {
12361            if (mDisplayList != null) {
12362                mDisplayList.markDirty();
12363                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12364            }
12365            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12366        } else {
12367            // Should never happen
12368            resetDisplayList();
12369        }
12370    }
12371
12372    /**
12373     * This method ensures the hardware renderer is in a valid state
12374     * before executing the specified action.
12375     *
12376     * This method will attempt to set a valid state even if the window
12377     * the renderer is attached to was destroyed.
12378     *
12379     * This method is not guaranteed to work. If the hardware renderer
12380     * does not exist or cannot be put in a valid state, this method
12381     * will not executed the specified action.
12382     *
12383     * The specified action is executed synchronously.
12384     *
12385     * @param action The action to execute after the renderer is in a valid state
12386     *
12387     * @return True if the specified Runnable was executed, false otherwise
12388     *
12389     * @hide
12390     */
12391    public boolean executeHardwareAction(Runnable action) {
12392        //noinspection SimplifiableIfStatement
12393        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12394            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12395        }
12396        return false;
12397    }
12398
12399    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12400    }
12401
12402    /**
12403     * @return The number of times this view has been attached to a window
12404     */
12405    protected int getWindowAttachCount() {
12406        return mWindowAttachCount;
12407    }
12408
12409    /**
12410     * Retrieve a unique token identifying the window this view is attached to.
12411     * @return Return the window's token for use in
12412     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12413     */
12414    public IBinder getWindowToken() {
12415        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12416    }
12417
12418    /**
12419     * Retrieve the {@link WindowId} for the window this view is
12420     * currently attached to.
12421     */
12422    public WindowId getWindowId() {
12423        if (mAttachInfo == null) {
12424            return null;
12425        }
12426        if (mAttachInfo.mWindowId == null) {
12427            try {
12428                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12429                        mAttachInfo.mWindowToken);
12430                mAttachInfo.mWindowId = new WindowId(
12431                        mAttachInfo.mIWindowId);
12432            } catch (RemoteException e) {
12433            }
12434        }
12435        return mAttachInfo.mWindowId;
12436    }
12437
12438    /**
12439     * Retrieve a unique token identifying the top-level "real" window of
12440     * the window that this view is attached to.  That is, this is like
12441     * {@link #getWindowToken}, except if the window this view in is a panel
12442     * window (attached to another containing window), then the token of
12443     * the containing window is returned instead.
12444     *
12445     * @return Returns the associated window token, either
12446     * {@link #getWindowToken()} or the containing window's token.
12447     */
12448    public IBinder getApplicationWindowToken() {
12449        AttachInfo ai = mAttachInfo;
12450        if (ai != null) {
12451            IBinder appWindowToken = ai.mPanelParentWindowToken;
12452            if (appWindowToken == null) {
12453                appWindowToken = ai.mWindowToken;
12454            }
12455            return appWindowToken;
12456        }
12457        return null;
12458    }
12459
12460    /**
12461     * Gets the logical display to which the view's window has been attached.
12462     *
12463     * @return The logical display, or null if the view is not currently attached to a window.
12464     */
12465    public Display getDisplay() {
12466        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12467    }
12468
12469    /**
12470     * Retrieve private session object this view hierarchy is using to
12471     * communicate with the window manager.
12472     * @return the session object to communicate with the window manager
12473     */
12474    /*package*/ IWindowSession getWindowSession() {
12475        return mAttachInfo != null ? mAttachInfo.mSession : null;
12476    }
12477
12478    /**
12479     * @param info the {@link android.view.View.AttachInfo} to associated with
12480     *        this view
12481     */
12482    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12483        //System.out.println("Attached! " + this);
12484        mAttachInfo = info;
12485        if (mOverlay != null) {
12486            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12487        }
12488        mWindowAttachCount++;
12489        // We will need to evaluate the drawable state at least once.
12490        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12491        if (mFloatingTreeObserver != null) {
12492            info.mTreeObserver.merge(mFloatingTreeObserver);
12493            mFloatingTreeObserver = null;
12494        }
12495        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12496            mAttachInfo.mScrollContainers.add(this);
12497            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12498        }
12499        performCollectViewAttributes(mAttachInfo, visibility);
12500        onAttachedToWindow();
12501
12502        ListenerInfo li = mListenerInfo;
12503        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12504                li != null ? li.mOnAttachStateChangeListeners : null;
12505        if (listeners != null && listeners.size() > 0) {
12506            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12507            // perform the dispatching. The iterator is a safe guard against listeners that
12508            // could mutate the list by calling the various add/remove methods. This prevents
12509            // the array from being modified while we iterate it.
12510            for (OnAttachStateChangeListener listener : listeners) {
12511                listener.onViewAttachedToWindow(this);
12512            }
12513        }
12514
12515        int vis = info.mWindowVisibility;
12516        if (vis != GONE) {
12517            onWindowVisibilityChanged(vis);
12518        }
12519        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12520            // If nobody has evaluated the drawable state yet, then do it now.
12521            refreshDrawableState();
12522        }
12523        needGlobalAttributesUpdate(false);
12524    }
12525
12526    void dispatchDetachedFromWindow() {
12527        AttachInfo info = mAttachInfo;
12528        if (info != null) {
12529            int vis = info.mWindowVisibility;
12530            if (vis != GONE) {
12531                onWindowVisibilityChanged(GONE);
12532            }
12533        }
12534
12535        onDetachedFromWindow();
12536
12537        ListenerInfo li = mListenerInfo;
12538        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12539                li != null ? li.mOnAttachStateChangeListeners : null;
12540        if (listeners != null && listeners.size() > 0) {
12541            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12542            // perform the dispatching. The iterator is a safe guard against listeners that
12543            // could mutate the list by calling the various add/remove methods. This prevents
12544            // the array from being modified while we iterate it.
12545            for (OnAttachStateChangeListener listener : listeners) {
12546                listener.onViewDetachedFromWindow(this);
12547            }
12548        }
12549
12550        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12551            mAttachInfo.mScrollContainers.remove(this);
12552            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12553        }
12554
12555        mAttachInfo = null;
12556        if (mOverlay != null) {
12557            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12558        }
12559    }
12560
12561    /**
12562     * Cancel any deferred high-level input events that were previously posted to the event queue.
12563     *
12564     * <p>Many views post high-level events such as click handlers to the event queue
12565     * to run deferred in order to preserve a desired user experience - clearing visible
12566     * pressed states before executing, etc. This method will abort any events of this nature
12567     * that are currently in flight.</p>
12568     *
12569     * <p>Custom views that generate their own high-level deferred input events should override
12570     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
12571     *
12572     * <p>This will also cancel pending input events for any child views.</p>
12573     *
12574     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
12575     * This will not impact newer events posted after this call that may occur as a result of
12576     * lower-level input events still waiting in the queue. If you are trying to prevent
12577     * double-submitted  events for the duration of some sort of asynchronous transaction
12578     * you should also take other steps to protect against unexpected double inputs e.g. calling
12579     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
12580     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
12581     */
12582    public final void cancelPendingInputEvents() {
12583        dispatchCancelPendingInputEvents();
12584    }
12585
12586    /**
12587     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
12588     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
12589     */
12590    void dispatchCancelPendingInputEvents() {
12591        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
12592        onCancelPendingInputEvents();
12593        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
12594            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
12595                    " did not call through to super.onCancelPendingInputEvents()");
12596        }
12597    }
12598
12599    /**
12600     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
12601     * a parent view.
12602     *
12603     * <p>This method is responsible for removing any pending high-level input events that were
12604     * posted to the event queue to run later. Custom view classes that post their own deferred
12605     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
12606     * {@link android.os.Handler} should override this method, call
12607     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
12608     * </p>
12609     */
12610    public void onCancelPendingInputEvents() {
12611        removePerformClickCallback();
12612        cancelLongPress();
12613        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
12614    }
12615
12616    /**
12617     * Store this view hierarchy's frozen state into the given container.
12618     *
12619     * @param container The SparseArray in which to save the view's state.
12620     *
12621     * @see #restoreHierarchyState(android.util.SparseArray)
12622     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12623     * @see #onSaveInstanceState()
12624     */
12625    public void saveHierarchyState(SparseArray<Parcelable> container) {
12626        dispatchSaveInstanceState(container);
12627    }
12628
12629    /**
12630     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12631     * this view and its children. May be overridden to modify how freezing happens to a
12632     * view's children; for example, some views may want to not store state for their children.
12633     *
12634     * @param container The SparseArray in which to save the view's state.
12635     *
12636     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12637     * @see #saveHierarchyState(android.util.SparseArray)
12638     * @see #onSaveInstanceState()
12639     */
12640    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12641        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12642            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12643            Parcelable state = onSaveInstanceState();
12644            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12645                throw new IllegalStateException(
12646                        "Derived class did not call super.onSaveInstanceState()");
12647            }
12648            if (state != null) {
12649                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12650                // + ": " + state);
12651                container.put(mID, state);
12652            }
12653        }
12654    }
12655
12656    /**
12657     * Hook allowing a view to generate a representation of its internal state
12658     * that can later be used to create a new instance with that same state.
12659     * This state should only contain information that is not persistent or can
12660     * not be reconstructed later. For example, you will never store your
12661     * current position on screen because that will be computed again when a
12662     * new instance of the view is placed in its view hierarchy.
12663     * <p>
12664     * Some examples of things you may store here: the current cursor position
12665     * in a text view (but usually not the text itself since that is stored in a
12666     * content provider or other persistent storage), the currently selected
12667     * item in a list view.
12668     *
12669     * @return Returns a Parcelable object containing the view's current dynamic
12670     *         state, or null if there is nothing interesting to save. The
12671     *         default implementation returns null.
12672     * @see #onRestoreInstanceState(android.os.Parcelable)
12673     * @see #saveHierarchyState(android.util.SparseArray)
12674     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12675     * @see #setSaveEnabled(boolean)
12676     */
12677    protected Parcelable onSaveInstanceState() {
12678        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12679        return BaseSavedState.EMPTY_STATE;
12680    }
12681
12682    /**
12683     * Restore this view hierarchy's frozen state from the given container.
12684     *
12685     * @param container The SparseArray which holds previously frozen states.
12686     *
12687     * @see #saveHierarchyState(android.util.SparseArray)
12688     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12689     * @see #onRestoreInstanceState(android.os.Parcelable)
12690     */
12691    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12692        dispatchRestoreInstanceState(container);
12693    }
12694
12695    /**
12696     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12697     * state for this view and its children. May be overridden to modify how restoring
12698     * happens to a view's children; for example, some views may want to not store state
12699     * for their children.
12700     *
12701     * @param container The SparseArray which holds previously saved state.
12702     *
12703     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12704     * @see #restoreHierarchyState(android.util.SparseArray)
12705     * @see #onRestoreInstanceState(android.os.Parcelable)
12706     */
12707    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12708        if (mID != NO_ID) {
12709            Parcelable state = container.get(mID);
12710            if (state != null) {
12711                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12712                // + ": " + state);
12713                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12714                onRestoreInstanceState(state);
12715                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12716                    throw new IllegalStateException(
12717                            "Derived class did not call super.onRestoreInstanceState()");
12718                }
12719            }
12720        }
12721    }
12722
12723    /**
12724     * Hook allowing a view to re-apply a representation of its internal state that had previously
12725     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12726     * null state.
12727     *
12728     * @param state The frozen state that had previously been returned by
12729     *        {@link #onSaveInstanceState}.
12730     *
12731     * @see #onSaveInstanceState()
12732     * @see #restoreHierarchyState(android.util.SparseArray)
12733     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12734     */
12735    protected void onRestoreInstanceState(Parcelable state) {
12736        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12737        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12738            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12739                    + "received " + state.getClass().toString() + " instead. This usually happens "
12740                    + "when two views of different type have the same id in the same hierarchy. "
12741                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12742                    + "other views do not use the same id.");
12743        }
12744    }
12745
12746    /**
12747     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12748     *
12749     * @return the drawing start time in milliseconds
12750     */
12751    public long getDrawingTime() {
12752        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12753    }
12754
12755    /**
12756     * <p>Enables or disables the duplication of the parent's state into this view. When
12757     * duplication is enabled, this view gets its drawable state from its parent rather
12758     * than from its own internal properties.</p>
12759     *
12760     * <p>Note: in the current implementation, setting this property to true after the
12761     * view was added to a ViewGroup might have no effect at all. This property should
12762     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12763     *
12764     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12765     * property is enabled, an exception will be thrown.</p>
12766     *
12767     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12768     * parent, these states should not be affected by this method.</p>
12769     *
12770     * @param enabled True to enable duplication of the parent's drawable state, false
12771     *                to disable it.
12772     *
12773     * @see #getDrawableState()
12774     * @see #isDuplicateParentStateEnabled()
12775     */
12776    public void setDuplicateParentStateEnabled(boolean enabled) {
12777        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12778    }
12779
12780    /**
12781     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12782     *
12783     * @return True if this view's drawable state is duplicated from the parent,
12784     *         false otherwise
12785     *
12786     * @see #getDrawableState()
12787     * @see #setDuplicateParentStateEnabled(boolean)
12788     */
12789    public boolean isDuplicateParentStateEnabled() {
12790        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12791    }
12792
12793    /**
12794     * <p>Specifies the type of layer backing this view. The layer can be
12795     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12796     * {@link #LAYER_TYPE_HARDWARE}.</p>
12797     *
12798     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12799     * instance that controls how the layer is composed on screen. The following
12800     * properties of the paint are taken into account when composing the layer:</p>
12801     * <ul>
12802     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12803     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12804     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12805     * </ul>
12806     *
12807     * <p>If this view has an alpha value set to < 1.0 by calling
12808     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12809     * by this view's alpha value.</p>
12810     *
12811     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12812     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12813     * for more information on when and how to use layers.</p>
12814     *
12815     * @param layerType The type of layer to use with this view, must be one of
12816     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12817     *        {@link #LAYER_TYPE_HARDWARE}
12818     * @param paint The paint used to compose the layer. This argument is optional
12819     *        and can be null. It is ignored when the layer type is
12820     *        {@link #LAYER_TYPE_NONE}
12821     *
12822     * @see #getLayerType()
12823     * @see #LAYER_TYPE_NONE
12824     * @see #LAYER_TYPE_SOFTWARE
12825     * @see #LAYER_TYPE_HARDWARE
12826     * @see #setAlpha(float)
12827     *
12828     * @attr ref android.R.styleable#View_layerType
12829     */
12830    public void setLayerType(int layerType, Paint paint) {
12831        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12832            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12833                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12834        }
12835
12836        if (layerType == mLayerType) {
12837            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12838                mLayerPaint = paint == null ? new Paint() : paint;
12839                invalidateParentCaches();
12840                invalidate(true);
12841            }
12842            return;
12843        }
12844
12845        // Destroy any previous software drawing cache if needed
12846        switch (mLayerType) {
12847            case LAYER_TYPE_HARDWARE:
12848                destroyLayer(false);
12849                // fall through - non-accelerated views may use software layer mechanism instead
12850            case LAYER_TYPE_SOFTWARE:
12851                destroyDrawingCache();
12852                break;
12853            default:
12854                break;
12855        }
12856
12857        mLayerType = layerType;
12858        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12859        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12860        mLocalDirtyRect = layerDisabled ? null : new Rect();
12861
12862        invalidateParentCaches();
12863        invalidate(true);
12864    }
12865
12866    /**
12867     * Updates the {@link Paint} object used with the current layer (used only if the current
12868     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12869     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12870     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12871     * ensure that the view gets redrawn immediately.
12872     *
12873     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12874     * instance that controls how the layer is composed on screen. The following
12875     * properties of the paint are taken into account when composing the layer:</p>
12876     * <ul>
12877     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12878     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12879     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12880     * </ul>
12881     *
12882     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12883     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12884     *
12885     * @param paint The paint used to compose the layer. This argument is optional
12886     *        and can be null. It is ignored when the layer type is
12887     *        {@link #LAYER_TYPE_NONE}
12888     *
12889     * @see #setLayerType(int, android.graphics.Paint)
12890     */
12891    public void setLayerPaint(Paint paint) {
12892        int layerType = getLayerType();
12893        if (layerType != LAYER_TYPE_NONE) {
12894            mLayerPaint = paint == null ? new Paint() : paint;
12895            if (layerType == LAYER_TYPE_HARDWARE) {
12896                HardwareLayer layer = getHardwareLayer();
12897                if (layer != null) {
12898                    layer.setLayerPaint(paint);
12899                }
12900                invalidateViewProperty(false, false);
12901            } else {
12902                invalidate();
12903            }
12904        }
12905    }
12906
12907    /**
12908     * Indicates whether this view has a static layer. A view with layer type
12909     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12910     * dynamic.
12911     */
12912    boolean hasStaticLayer() {
12913        return true;
12914    }
12915
12916    /**
12917     * Indicates what type of layer is currently associated with this view. By default
12918     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12919     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12920     * for more information on the different types of layers.
12921     *
12922     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12923     *         {@link #LAYER_TYPE_HARDWARE}
12924     *
12925     * @see #setLayerType(int, android.graphics.Paint)
12926     * @see #buildLayer()
12927     * @see #LAYER_TYPE_NONE
12928     * @see #LAYER_TYPE_SOFTWARE
12929     * @see #LAYER_TYPE_HARDWARE
12930     */
12931    public int getLayerType() {
12932        return mLayerType;
12933    }
12934
12935    /**
12936     * Forces this view's layer to be created and this view to be rendered
12937     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12938     * invoking this method will have no effect.
12939     *
12940     * This method can for instance be used to render a view into its layer before
12941     * starting an animation. If this view is complex, rendering into the layer
12942     * before starting the animation will avoid skipping frames.
12943     *
12944     * @throws IllegalStateException If this view is not attached to a window
12945     *
12946     * @see #setLayerType(int, android.graphics.Paint)
12947     */
12948    public void buildLayer() {
12949        if (mLayerType == LAYER_TYPE_NONE) return;
12950
12951        final AttachInfo attachInfo = mAttachInfo;
12952        if (attachInfo == null) {
12953            throw new IllegalStateException("This view must be attached to a window first");
12954        }
12955
12956        switch (mLayerType) {
12957            case LAYER_TYPE_HARDWARE:
12958                if (attachInfo.mHardwareRenderer != null &&
12959                        attachInfo.mHardwareRenderer.isEnabled() &&
12960                        attachInfo.mHardwareRenderer.validate()) {
12961                    getHardwareLayer();
12962                    // TODO: We need a better way to handle this case
12963                    // If views have registered pre-draw listeners they need
12964                    // to be notified before we build the layer. Those listeners
12965                    // may however rely on other events to happen first so we
12966                    // cannot just invoke them here until they don't cancel the
12967                    // current frame
12968                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12969                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12970                    }
12971                }
12972                break;
12973            case LAYER_TYPE_SOFTWARE:
12974                buildDrawingCache(true);
12975                break;
12976        }
12977    }
12978
12979    /**
12980     * <p>Returns a hardware layer that can be used to draw this view again
12981     * without executing its draw method.</p>
12982     *
12983     * @return A HardwareLayer ready to render, or null if an error occurred.
12984     */
12985    HardwareLayer getHardwareLayer() {
12986        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12987                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12988            return null;
12989        }
12990
12991        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12992
12993        final int width = mRight - mLeft;
12994        final int height = mBottom - mTop;
12995
12996        if (width == 0 || height == 0) {
12997            return null;
12998        }
12999
13000        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13001            if (mHardwareLayer == null) {
13002                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
13003                        width, height, isOpaque());
13004                mLocalDirtyRect.set(0, 0, width, height);
13005            } else {
13006                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
13007                    if (mHardwareLayer.resize(width, height)) {
13008                        mLocalDirtyRect.set(0, 0, width, height);
13009                    }
13010                }
13011
13012                // This should not be necessary but applications that change
13013                // the parameters of their background drawable without calling
13014                // this.setBackground(Drawable) can leave the view in a bad state
13015                // (for instance isOpaque() returns true, but the background is
13016                // not opaque.)
13017                computeOpaqueFlags();
13018
13019                final boolean opaque = isOpaque();
13020                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
13021                    mHardwareLayer.setOpaque(opaque);
13022                    mLocalDirtyRect.set(0, 0, width, height);
13023                }
13024            }
13025
13026            // The layer is not valid if the underlying GPU resources cannot be allocated
13027            if (!mHardwareLayer.isValid()) {
13028                return null;
13029            }
13030
13031            mHardwareLayer.setLayerPaint(mLayerPaint);
13032            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
13033            ViewRootImpl viewRoot = getViewRootImpl();
13034            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
13035
13036            mLocalDirtyRect.setEmpty();
13037        }
13038
13039        return mHardwareLayer;
13040    }
13041
13042    /**
13043     * Destroys this View's hardware layer if possible.
13044     *
13045     * @return True if the layer was destroyed, false otherwise.
13046     *
13047     * @see #setLayerType(int, android.graphics.Paint)
13048     * @see #LAYER_TYPE_HARDWARE
13049     */
13050    boolean destroyLayer(boolean valid) {
13051        if (mHardwareLayer != null) {
13052            AttachInfo info = mAttachInfo;
13053            if (info != null && info.mHardwareRenderer != null &&
13054                    info.mHardwareRenderer.isEnabled() &&
13055                    (valid || info.mHardwareRenderer.validate())) {
13056
13057                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
13058                mHardwareLayer.destroy();
13059                mHardwareLayer = null;
13060
13061                invalidate(true);
13062                invalidateParentCaches();
13063            }
13064            return true;
13065        }
13066        return false;
13067    }
13068
13069    /**
13070     * Destroys all hardware rendering resources. This method is invoked
13071     * when the system needs to reclaim resources. Upon execution of this
13072     * method, you should free any OpenGL resources created by the view.
13073     *
13074     * Note: you <strong>must</strong> call
13075     * <code>super.destroyHardwareResources()</code> when overriding
13076     * this method.
13077     *
13078     * @hide
13079     */
13080    protected void destroyHardwareResources() {
13081        resetDisplayList();
13082        destroyLayer(true);
13083    }
13084
13085    /**
13086     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13087     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13088     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13089     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13090     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13091     * null.</p>
13092     *
13093     * <p>Enabling the drawing cache is similar to
13094     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13095     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13096     * drawing cache has no effect on rendering because the system uses a different mechanism
13097     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13098     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13099     * for information on how to enable software and hardware layers.</p>
13100     *
13101     * <p>This API can be used to manually generate
13102     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13103     * {@link #getDrawingCache()}.</p>
13104     *
13105     * @param enabled true to enable the drawing cache, false otherwise
13106     *
13107     * @see #isDrawingCacheEnabled()
13108     * @see #getDrawingCache()
13109     * @see #buildDrawingCache()
13110     * @see #setLayerType(int, android.graphics.Paint)
13111     */
13112    public void setDrawingCacheEnabled(boolean enabled) {
13113        mCachingFailed = false;
13114        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13115    }
13116
13117    /**
13118     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13119     *
13120     * @return true if the drawing cache is enabled
13121     *
13122     * @see #setDrawingCacheEnabled(boolean)
13123     * @see #getDrawingCache()
13124     */
13125    @ViewDebug.ExportedProperty(category = "drawing")
13126    public boolean isDrawingCacheEnabled() {
13127        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13128    }
13129
13130    /**
13131     * Debugging utility which recursively outputs the dirty state of a view and its
13132     * descendants.
13133     *
13134     * @hide
13135     */
13136    @SuppressWarnings({"UnusedDeclaration"})
13137    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13138        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13139                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13140                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13141                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13142        if (clear) {
13143            mPrivateFlags &= clearMask;
13144        }
13145        if (this instanceof ViewGroup) {
13146            ViewGroup parent = (ViewGroup) this;
13147            final int count = parent.getChildCount();
13148            for (int i = 0; i < count; i++) {
13149                final View child = parent.getChildAt(i);
13150                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13151            }
13152        }
13153    }
13154
13155    /**
13156     * This method is used by ViewGroup to cause its children to restore or recreate their
13157     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13158     * to recreate its own display list, which would happen if it went through the normal
13159     * draw/dispatchDraw mechanisms.
13160     *
13161     * @hide
13162     */
13163    protected void dispatchGetDisplayList() {}
13164
13165    /**
13166     * A view that is not attached or hardware accelerated cannot create a display list.
13167     * This method checks these conditions and returns the appropriate result.
13168     *
13169     * @return true if view has the ability to create a display list, false otherwise.
13170     *
13171     * @hide
13172     */
13173    public boolean canHaveDisplayList() {
13174        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13175    }
13176
13177    /**
13178     * @return The {@link HardwareRenderer} associated with that view or null if
13179     *         hardware rendering is not supported or this view is not attached
13180     *         to a window.
13181     *
13182     * @hide
13183     */
13184    public HardwareRenderer getHardwareRenderer() {
13185        if (mAttachInfo != null) {
13186            return mAttachInfo.mHardwareRenderer;
13187        }
13188        return null;
13189    }
13190
13191    /**
13192     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13193     * Otherwise, the same display list will be returned (after having been rendered into
13194     * along the way, depending on the invalidation state of the view).
13195     *
13196     * @param displayList The previous version of this displayList, could be null.
13197     * @param isLayer Whether the requester of the display list is a layer. If so,
13198     * the view will avoid creating a layer inside the resulting display list.
13199     * @return A new or reused DisplayList object.
13200     */
13201    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13202        if (!canHaveDisplayList()) {
13203            return null;
13204        }
13205
13206        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13207                displayList == null || !displayList.isValid() ||
13208                (!isLayer && mRecreateDisplayList))) {
13209            // Don't need to recreate the display list, just need to tell our
13210            // children to restore/recreate theirs
13211            if (displayList != null && displayList.isValid() &&
13212                    !isLayer && !mRecreateDisplayList) {
13213                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13214                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13215                dispatchGetDisplayList();
13216
13217                return displayList;
13218            }
13219
13220            if (!isLayer) {
13221                // If we got here, we're recreating it. Mark it as such to ensure that
13222                // we copy in child display lists into ours in drawChild()
13223                mRecreateDisplayList = true;
13224            }
13225            if (displayList == null) {
13226                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
13227                // If we're creating a new display list, make sure our parent gets invalidated
13228                // since they will need to recreate their display list to account for this
13229                // new child display list.
13230                invalidateParentCaches();
13231            }
13232
13233            boolean caching = false;
13234            int width = mRight - mLeft;
13235            int height = mBottom - mTop;
13236            int layerType = getLayerType();
13237
13238            final HardwareCanvas canvas = displayList.start(width, height);
13239
13240            try {
13241                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13242                    if (layerType == LAYER_TYPE_HARDWARE) {
13243                        final HardwareLayer layer = getHardwareLayer();
13244                        if (layer != null && layer.isValid()) {
13245                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13246                        } else {
13247                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13248                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13249                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13250                        }
13251                        caching = true;
13252                    } else {
13253                        buildDrawingCache(true);
13254                        Bitmap cache = getDrawingCache(true);
13255                        if (cache != null) {
13256                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13257                            caching = true;
13258                        }
13259                    }
13260                } else {
13261
13262                    computeScroll();
13263
13264                    canvas.translate(-mScrollX, -mScrollY);
13265                    if (!isLayer) {
13266                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13267                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13268                    }
13269
13270                    // Fast path for layouts with no backgrounds
13271                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13272                        dispatchDraw(canvas);
13273                        if (mOverlay != null && !mOverlay.isEmpty()) {
13274                            mOverlay.getOverlayView().draw(canvas);
13275                        }
13276                    } else {
13277                        draw(canvas);
13278                    }
13279                }
13280            } finally {
13281                displayList.end();
13282                displayList.setCaching(caching);
13283                if (isLayer) {
13284                    displayList.setLeftTopRightBottom(0, 0, width, height);
13285                } else {
13286                    setDisplayListProperties(displayList);
13287                }
13288            }
13289        } else if (!isLayer) {
13290            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13291            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13292        }
13293
13294        return displayList;
13295    }
13296
13297    /**
13298     * Get the DisplayList for the HardwareLayer
13299     *
13300     * @param layer The HardwareLayer whose DisplayList we want
13301     * @return A DisplayList fopr the specified HardwareLayer
13302     */
13303    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13304        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13305        layer.setDisplayList(displayList);
13306        return displayList;
13307    }
13308
13309
13310    /**
13311     * <p>Returns a display list that can be used to draw this view again
13312     * without executing its draw method.</p>
13313     *
13314     * @return A DisplayList ready to replay, or null if caching is not enabled.
13315     *
13316     * @hide
13317     */
13318    public DisplayList getDisplayList() {
13319        mDisplayList = getDisplayList(mDisplayList, false);
13320        return mDisplayList;
13321    }
13322
13323    private void clearDisplayList() {
13324        if (mDisplayList != null) {
13325            mDisplayList.clear();
13326        }
13327    }
13328
13329    private void resetDisplayList() {
13330        if (mDisplayList != null) {
13331            mDisplayList.reset();
13332        }
13333    }
13334
13335    /**
13336     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13337     *
13338     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13339     *
13340     * @see #getDrawingCache(boolean)
13341     */
13342    public Bitmap getDrawingCache() {
13343        return getDrawingCache(false);
13344    }
13345
13346    /**
13347     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13348     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13349     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13350     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13351     * request the drawing cache by calling this method and draw it on screen if the
13352     * returned bitmap is not null.</p>
13353     *
13354     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13355     * this method will create a bitmap of the same size as this view. Because this bitmap
13356     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13357     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13358     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13359     * size than the view. This implies that your application must be able to handle this
13360     * size.</p>
13361     *
13362     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13363     *        the current density of the screen when the application is in compatibility
13364     *        mode.
13365     *
13366     * @return A bitmap representing this view or null if cache is disabled.
13367     *
13368     * @see #setDrawingCacheEnabled(boolean)
13369     * @see #isDrawingCacheEnabled()
13370     * @see #buildDrawingCache(boolean)
13371     * @see #destroyDrawingCache()
13372     */
13373    public Bitmap getDrawingCache(boolean autoScale) {
13374        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13375            return null;
13376        }
13377        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13378            buildDrawingCache(autoScale);
13379        }
13380        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13381    }
13382
13383    /**
13384     * <p>Frees the resources used by the drawing cache. If you call
13385     * {@link #buildDrawingCache()} manually without calling
13386     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13387     * should cleanup the cache with this method afterwards.</p>
13388     *
13389     * @see #setDrawingCacheEnabled(boolean)
13390     * @see #buildDrawingCache()
13391     * @see #getDrawingCache()
13392     */
13393    public void destroyDrawingCache() {
13394        if (mDrawingCache != null) {
13395            mDrawingCache.recycle();
13396            mDrawingCache = null;
13397        }
13398        if (mUnscaledDrawingCache != null) {
13399            mUnscaledDrawingCache.recycle();
13400            mUnscaledDrawingCache = null;
13401        }
13402    }
13403
13404    /**
13405     * Setting a solid background color for the drawing cache's bitmaps will improve
13406     * performance and memory usage. Note, though that this should only be used if this
13407     * view will always be drawn on top of a solid color.
13408     *
13409     * @param color The background color to use for the drawing cache's bitmap
13410     *
13411     * @see #setDrawingCacheEnabled(boolean)
13412     * @see #buildDrawingCache()
13413     * @see #getDrawingCache()
13414     */
13415    public void setDrawingCacheBackgroundColor(int color) {
13416        if (color != mDrawingCacheBackgroundColor) {
13417            mDrawingCacheBackgroundColor = color;
13418            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13419        }
13420    }
13421
13422    /**
13423     * @see #setDrawingCacheBackgroundColor(int)
13424     *
13425     * @return The background color to used for the drawing cache's bitmap
13426     */
13427    public int getDrawingCacheBackgroundColor() {
13428        return mDrawingCacheBackgroundColor;
13429    }
13430
13431    /**
13432     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13433     *
13434     * @see #buildDrawingCache(boolean)
13435     */
13436    public void buildDrawingCache() {
13437        buildDrawingCache(false);
13438    }
13439
13440    /**
13441     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13442     *
13443     * <p>If you call {@link #buildDrawingCache()} manually without calling
13444     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13445     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13446     *
13447     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13448     * this method will create a bitmap of the same size as this view. Because this bitmap
13449     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13450     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13451     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13452     * size than the view. This implies that your application must be able to handle this
13453     * size.</p>
13454     *
13455     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13456     * you do not need the drawing cache bitmap, calling this method will increase memory
13457     * usage and cause the view to be rendered in software once, thus negatively impacting
13458     * performance.</p>
13459     *
13460     * @see #getDrawingCache()
13461     * @see #destroyDrawingCache()
13462     */
13463    public void buildDrawingCache(boolean autoScale) {
13464        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13465                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13466            mCachingFailed = false;
13467
13468            int width = mRight - mLeft;
13469            int height = mBottom - mTop;
13470
13471            final AttachInfo attachInfo = mAttachInfo;
13472            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13473
13474            if (autoScale && scalingRequired) {
13475                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13476                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13477            }
13478
13479            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13480            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13481            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13482
13483            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13484            final long drawingCacheSize =
13485                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13486            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13487                if (width > 0 && height > 0) {
13488                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13489                            + projectedBitmapSize + " bytes, only "
13490                            + drawingCacheSize + " available");
13491                }
13492                destroyDrawingCache();
13493                mCachingFailed = true;
13494                return;
13495            }
13496
13497            boolean clear = true;
13498            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13499
13500            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13501                Bitmap.Config quality;
13502                if (!opaque) {
13503                    // Never pick ARGB_4444 because it looks awful
13504                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13505                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13506                        case DRAWING_CACHE_QUALITY_AUTO:
13507                        case DRAWING_CACHE_QUALITY_LOW:
13508                        case DRAWING_CACHE_QUALITY_HIGH:
13509                        default:
13510                            quality = Bitmap.Config.ARGB_8888;
13511                            break;
13512                    }
13513                } else {
13514                    // Optimization for translucent windows
13515                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13516                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13517                }
13518
13519                // Try to cleanup memory
13520                if (bitmap != null) bitmap.recycle();
13521
13522                try {
13523                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13524                            width, height, quality);
13525                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13526                    if (autoScale) {
13527                        mDrawingCache = bitmap;
13528                    } else {
13529                        mUnscaledDrawingCache = bitmap;
13530                    }
13531                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13532                } catch (OutOfMemoryError e) {
13533                    // If there is not enough memory to create the bitmap cache, just
13534                    // ignore the issue as bitmap caches are not required to draw the
13535                    // view hierarchy
13536                    if (autoScale) {
13537                        mDrawingCache = null;
13538                    } else {
13539                        mUnscaledDrawingCache = null;
13540                    }
13541                    mCachingFailed = true;
13542                    return;
13543                }
13544
13545                clear = drawingCacheBackgroundColor != 0;
13546            }
13547
13548            Canvas canvas;
13549            if (attachInfo != null) {
13550                canvas = attachInfo.mCanvas;
13551                if (canvas == null) {
13552                    canvas = new Canvas();
13553                }
13554                canvas.setBitmap(bitmap);
13555                // Temporarily clobber the cached Canvas in case one of our children
13556                // is also using a drawing cache. Without this, the children would
13557                // steal the canvas by attaching their own bitmap to it and bad, bad
13558                // thing would happen (invisible views, corrupted drawings, etc.)
13559                attachInfo.mCanvas = null;
13560            } else {
13561                // This case should hopefully never or seldom happen
13562                canvas = new Canvas(bitmap);
13563            }
13564
13565            if (clear) {
13566                bitmap.eraseColor(drawingCacheBackgroundColor);
13567            }
13568
13569            computeScroll();
13570            final int restoreCount = canvas.save();
13571
13572            if (autoScale && scalingRequired) {
13573                final float scale = attachInfo.mApplicationScale;
13574                canvas.scale(scale, scale);
13575            }
13576
13577            canvas.translate(-mScrollX, -mScrollY);
13578
13579            mPrivateFlags |= PFLAG_DRAWN;
13580            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13581                    mLayerType != LAYER_TYPE_NONE) {
13582                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13583            }
13584
13585            // Fast path for layouts with no backgrounds
13586            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13587                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13588                dispatchDraw(canvas);
13589                if (mOverlay != null && !mOverlay.isEmpty()) {
13590                    mOverlay.getOverlayView().draw(canvas);
13591                }
13592            } else {
13593                draw(canvas);
13594            }
13595
13596            canvas.restoreToCount(restoreCount);
13597            canvas.setBitmap(null);
13598
13599            if (attachInfo != null) {
13600                // Restore the cached Canvas for our siblings
13601                attachInfo.mCanvas = canvas;
13602            }
13603        }
13604    }
13605
13606    /**
13607     * Create a snapshot of the view into a bitmap.  We should probably make
13608     * some form of this public, but should think about the API.
13609     */
13610    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13611        int width = mRight - mLeft;
13612        int height = mBottom - mTop;
13613
13614        final AttachInfo attachInfo = mAttachInfo;
13615        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13616        width = (int) ((width * scale) + 0.5f);
13617        height = (int) ((height * scale) + 0.5f);
13618
13619        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13620                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13621        if (bitmap == null) {
13622            throw new OutOfMemoryError();
13623        }
13624
13625        Resources resources = getResources();
13626        if (resources != null) {
13627            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13628        }
13629
13630        Canvas canvas;
13631        if (attachInfo != null) {
13632            canvas = attachInfo.mCanvas;
13633            if (canvas == null) {
13634                canvas = new Canvas();
13635            }
13636            canvas.setBitmap(bitmap);
13637            // Temporarily clobber the cached Canvas in case one of our children
13638            // is also using a drawing cache. Without this, the children would
13639            // steal the canvas by attaching their own bitmap to it and bad, bad
13640            // things would happen (invisible views, corrupted drawings, etc.)
13641            attachInfo.mCanvas = null;
13642        } else {
13643            // This case should hopefully never or seldom happen
13644            canvas = new Canvas(bitmap);
13645        }
13646
13647        if ((backgroundColor & 0xff000000) != 0) {
13648            bitmap.eraseColor(backgroundColor);
13649        }
13650
13651        computeScroll();
13652        final int restoreCount = canvas.save();
13653        canvas.scale(scale, scale);
13654        canvas.translate(-mScrollX, -mScrollY);
13655
13656        // Temporarily remove the dirty mask
13657        int flags = mPrivateFlags;
13658        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13659
13660        // Fast path for layouts with no backgrounds
13661        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13662            dispatchDraw(canvas);
13663            if (mOverlay != null && !mOverlay.isEmpty()) {
13664                mOverlay.getOverlayView().draw(canvas);
13665            }
13666        } else {
13667            draw(canvas);
13668        }
13669
13670        mPrivateFlags = flags;
13671
13672        canvas.restoreToCount(restoreCount);
13673        canvas.setBitmap(null);
13674
13675        if (attachInfo != null) {
13676            // Restore the cached Canvas for our siblings
13677            attachInfo.mCanvas = canvas;
13678        }
13679
13680        return bitmap;
13681    }
13682
13683    /**
13684     * Indicates whether this View is currently in edit mode. A View is usually
13685     * in edit mode when displayed within a developer tool. For instance, if
13686     * this View is being drawn by a visual user interface builder, this method
13687     * should return true.
13688     *
13689     * Subclasses should check the return value of this method to provide
13690     * different behaviors if their normal behavior might interfere with the
13691     * host environment. For instance: the class spawns a thread in its
13692     * constructor, the drawing code relies on device-specific features, etc.
13693     *
13694     * This method is usually checked in the drawing code of custom widgets.
13695     *
13696     * @return True if this View is in edit mode, false otherwise.
13697     */
13698    public boolean isInEditMode() {
13699        return false;
13700    }
13701
13702    /**
13703     * If the View draws content inside its padding and enables fading edges,
13704     * it needs to support padding offsets. Padding offsets are added to the
13705     * fading edges to extend the length of the fade so that it covers pixels
13706     * drawn inside the padding.
13707     *
13708     * Subclasses of this class should override this method if they need
13709     * to draw content inside the padding.
13710     *
13711     * @return True if padding offset must be applied, false otherwise.
13712     *
13713     * @see #getLeftPaddingOffset()
13714     * @see #getRightPaddingOffset()
13715     * @see #getTopPaddingOffset()
13716     * @see #getBottomPaddingOffset()
13717     *
13718     * @since CURRENT
13719     */
13720    protected boolean isPaddingOffsetRequired() {
13721        return false;
13722    }
13723
13724    /**
13725     * Amount by which to extend the left fading region. Called only when
13726     * {@link #isPaddingOffsetRequired()} returns true.
13727     *
13728     * @return The left padding offset in pixels.
13729     *
13730     * @see #isPaddingOffsetRequired()
13731     *
13732     * @since CURRENT
13733     */
13734    protected int getLeftPaddingOffset() {
13735        return 0;
13736    }
13737
13738    /**
13739     * Amount by which to extend the right fading region. Called only when
13740     * {@link #isPaddingOffsetRequired()} returns true.
13741     *
13742     * @return The right padding offset in pixels.
13743     *
13744     * @see #isPaddingOffsetRequired()
13745     *
13746     * @since CURRENT
13747     */
13748    protected int getRightPaddingOffset() {
13749        return 0;
13750    }
13751
13752    /**
13753     * Amount by which to extend the top fading region. Called only when
13754     * {@link #isPaddingOffsetRequired()} returns true.
13755     *
13756     * @return The top padding offset in pixels.
13757     *
13758     * @see #isPaddingOffsetRequired()
13759     *
13760     * @since CURRENT
13761     */
13762    protected int getTopPaddingOffset() {
13763        return 0;
13764    }
13765
13766    /**
13767     * Amount by which to extend the bottom fading region. Called only when
13768     * {@link #isPaddingOffsetRequired()} returns true.
13769     *
13770     * @return The bottom padding offset in pixels.
13771     *
13772     * @see #isPaddingOffsetRequired()
13773     *
13774     * @since CURRENT
13775     */
13776    protected int getBottomPaddingOffset() {
13777        return 0;
13778    }
13779
13780    /**
13781     * @hide
13782     * @param offsetRequired
13783     */
13784    protected int getFadeTop(boolean offsetRequired) {
13785        int top = mPaddingTop;
13786        if (offsetRequired) top += getTopPaddingOffset();
13787        return top;
13788    }
13789
13790    /**
13791     * @hide
13792     * @param offsetRequired
13793     */
13794    protected int getFadeHeight(boolean offsetRequired) {
13795        int padding = mPaddingTop;
13796        if (offsetRequired) padding += getTopPaddingOffset();
13797        return mBottom - mTop - mPaddingBottom - padding;
13798    }
13799
13800    /**
13801     * <p>Indicates whether this view is attached to a hardware accelerated
13802     * window or not.</p>
13803     *
13804     * <p>Even if this method returns true, it does not mean that every call
13805     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13806     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13807     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13808     * window is hardware accelerated,
13809     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13810     * return false, and this method will return true.</p>
13811     *
13812     * @return True if the view is attached to a window and the window is
13813     *         hardware accelerated; false in any other case.
13814     */
13815    public boolean isHardwareAccelerated() {
13816        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13817    }
13818
13819    /**
13820     * Sets a rectangular area on this view to which the view will be clipped
13821     * when it is drawn. Setting the value to null will remove the clip bounds
13822     * and the view will draw normally, using its full bounds.
13823     *
13824     * @param clipBounds The rectangular area, in the local coordinates of
13825     * this view, to which future drawing operations will be clipped.
13826     */
13827    public void setClipBounds(Rect clipBounds) {
13828        if (clipBounds != null) {
13829            if (clipBounds.equals(mClipBounds)) {
13830                return;
13831            }
13832            if (mClipBounds == null) {
13833                invalidate();
13834                mClipBounds = new Rect(clipBounds);
13835            } else {
13836                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13837                        Math.min(mClipBounds.top, clipBounds.top),
13838                        Math.max(mClipBounds.right, clipBounds.right),
13839                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13840                mClipBounds.set(clipBounds);
13841            }
13842        } else {
13843            if (mClipBounds != null) {
13844                invalidate();
13845                mClipBounds = null;
13846            }
13847        }
13848    }
13849
13850    /**
13851     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13852     *
13853     * @return A copy of the current clip bounds if clip bounds are set,
13854     * otherwise null.
13855     */
13856    public Rect getClipBounds() {
13857        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13858    }
13859
13860    /**
13861     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13862     * case of an active Animation being run on the view.
13863     */
13864    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13865            Animation a, boolean scalingRequired) {
13866        Transformation invalidationTransform;
13867        final int flags = parent.mGroupFlags;
13868        final boolean initialized = a.isInitialized();
13869        if (!initialized) {
13870            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13871            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13872            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13873            onAnimationStart();
13874        }
13875
13876        final Transformation t = parent.getChildTransformation();
13877        boolean more = a.getTransformation(drawingTime, t, 1f);
13878        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13879            if (parent.mInvalidationTransformation == null) {
13880                parent.mInvalidationTransformation = new Transformation();
13881            }
13882            invalidationTransform = parent.mInvalidationTransformation;
13883            a.getTransformation(drawingTime, invalidationTransform, 1f);
13884        } else {
13885            invalidationTransform = t;
13886        }
13887
13888        if (more) {
13889            if (!a.willChangeBounds()) {
13890                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13891                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13892                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13893                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13894                    // The child need to draw an animation, potentially offscreen, so
13895                    // make sure we do not cancel invalidate requests
13896                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13897                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13898                }
13899            } else {
13900                if (parent.mInvalidateRegion == null) {
13901                    parent.mInvalidateRegion = new RectF();
13902                }
13903                final RectF region = parent.mInvalidateRegion;
13904                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13905                        invalidationTransform);
13906
13907                // The child need to draw an animation, potentially offscreen, so
13908                // make sure we do not cancel invalidate requests
13909                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13910
13911                final int left = mLeft + (int) region.left;
13912                final int top = mTop + (int) region.top;
13913                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13914                        top + (int) (region.height() + .5f));
13915            }
13916        }
13917        return more;
13918    }
13919
13920    /**
13921     * This method is called by getDisplayList() when a display list is created or re-rendered.
13922     * It sets or resets the current value of all properties on that display list (resetting is
13923     * necessary when a display list is being re-created, because we need to make sure that
13924     * previously-set transform values
13925     */
13926    void setDisplayListProperties(DisplayList displayList) {
13927        if (displayList != null) {
13928            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13929            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13930            if (mParent instanceof ViewGroup) {
13931                displayList.setClipToBounds(
13932                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13933            }
13934            float alpha = 1;
13935            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13936                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13937                ViewGroup parentVG = (ViewGroup) mParent;
13938                final Transformation t = parentVG.getChildTransformation();
13939                if (parentVG.getChildStaticTransformation(this, t)) {
13940                    final int transformType = t.getTransformationType();
13941                    if (transformType != Transformation.TYPE_IDENTITY) {
13942                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13943                            alpha = t.getAlpha();
13944                        }
13945                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13946                            displayList.setMatrix(t.getMatrix());
13947                        }
13948                    }
13949                }
13950            }
13951            if (mTransformationInfo != null) {
13952                alpha *= getFinalAlpha();
13953                if (alpha < 1) {
13954                    final int multipliedAlpha = (int) (255 * alpha);
13955                    if (onSetAlpha(multipliedAlpha)) {
13956                        alpha = 1;
13957                    }
13958                }
13959                displayList.setTransformationInfo(alpha,
13960                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13961                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13962                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13963                        mTransformationInfo.mScaleY);
13964                if (mTransformationInfo.mCamera == null) {
13965                    mTransformationInfo.mCamera = new Camera();
13966                    mTransformationInfo.matrix3D = new Matrix();
13967                }
13968                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13969                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13970                    displayList.setPivotX(getPivotX());
13971                    displayList.setPivotY(getPivotY());
13972                }
13973            } else if (alpha < 1) {
13974                displayList.setAlpha(alpha);
13975            }
13976        }
13977    }
13978
13979    /**
13980     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13981     * This draw() method is an implementation detail and is not intended to be overridden or
13982     * to be called from anywhere else other than ViewGroup.drawChild().
13983     */
13984    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13985        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13986        boolean more = false;
13987        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13988        final int flags = parent.mGroupFlags;
13989
13990        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13991            parent.getChildTransformation().clear();
13992            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13993        }
13994
13995        Transformation transformToApply = null;
13996        boolean concatMatrix = false;
13997
13998        boolean scalingRequired = false;
13999        boolean caching;
14000        int layerType = getLayerType();
14001
14002        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14003        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14004                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14005            caching = true;
14006            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14007            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14008        } else {
14009            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14010        }
14011
14012        final Animation a = getAnimation();
14013        if (a != null) {
14014            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14015            concatMatrix = a.willChangeTransformationMatrix();
14016            if (concatMatrix) {
14017                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14018            }
14019            transformToApply = parent.getChildTransformation();
14020        } else {
14021            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14022                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14023                // No longer animating: clear out old animation matrix
14024                mDisplayList.setAnimationMatrix(null);
14025                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14026            }
14027            if (!useDisplayListProperties &&
14028                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14029                final Transformation t = parent.getChildTransformation();
14030                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14031                if (hasTransform) {
14032                    final int transformType = t.getTransformationType();
14033                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14034                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14035                }
14036            }
14037        }
14038
14039        concatMatrix |= !childHasIdentityMatrix;
14040
14041        // Sets the flag as early as possible to allow draw() implementations
14042        // to call invalidate() successfully when doing animations
14043        mPrivateFlags |= PFLAG_DRAWN;
14044
14045        if (!concatMatrix &&
14046                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14047                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14048                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14049                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14050            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14051            return more;
14052        }
14053        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14054
14055        if (hardwareAccelerated) {
14056            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14057            // retain the flag's value temporarily in the mRecreateDisplayList flag
14058            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14059            mPrivateFlags &= ~PFLAG_INVALIDATED;
14060        }
14061
14062        DisplayList displayList = null;
14063        Bitmap cache = null;
14064        boolean hasDisplayList = false;
14065        if (caching) {
14066            if (!hardwareAccelerated) {
14067                if (layerType != LAYER_TYPE_NONE) {
14068                    layerType = LAYER_TYPE_SOFTWARE;
14069                    buildDrawingCache(true);
14070                }
14071                cache = getDrawingCache(true);
14072            } else {
14073                switch (layerType) {
14074                    case LAYER_TYPE_SOFTWARE:
14075                        if (useDisplayListProperties) {
14076                            hasDisplayList = canHaveDisplayList();
14077                        } else {
14078                            buildDrawingCache(true);
14079                            cache = getDrawingCache(true);
14080                        }
14081                        break;
14082                    case LAYER_TYPE_HARDWARE:
14083                        if (useDisplayListProperties) {
14084                            hasDisplayList = canHaveDisplayList();
14085                        }
14086                        break;
14087                    case LAYER_TYPE_NONE:
14088                        // Delay getting the display list until animation-driven alpha values are
14089                        // set up and possibly passed on to the view
14090                        hasDisplayList = canHaveDisplayList();
14091                        break;
14092                }
14093            }
14094        }
14095        useDisplayListProperties &= hasDisplayList;
14096        if (useDisplayListProperties) {
14097            displayList = getDisplayList();
14098            if (!displayList.isValid()) {
14099                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14100                // to getDisplayList(), the display list will be marked invalid and we should not
14101                // try to use it again.
14102                displayList = null;
14103                hasDisplayList = false;
14104                useDisplayListProperties = false;
14105            }
14106        }
14107
14108        int sx = 0;
14109        int sy = 0;
14110        if (!hasDisplayList) {
14111            computeScroll();
14112            sx = mScrollX;
14113            sy = mScrollY;
14114        }
14115
14116        final boolean hasNoCache = cache == null || hasDisplayList;
14117        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14118                layerType != LAYER_TYPE_HARDWARE;
14119
14120        int restoreTo = -1;
14121        if (!useDisplayListProperties || transformToApply != null) {
14122            restoreTo = canvas.save();
14123        }
14124        if (offsetForScroll) {
14125            canvas.translate(mLeft - sx, mTop - sy);
14126        } else {
14127            if (!useDisplayListProperties) {
14128                canvas.translate(mLeft, mTop);
14129            }
14130            if (scalingRequired) {
14131                if (useDisplayListProperties) {
14132                    // TODO: Might not need this if we put everything inside the DL
14133                    restoreTo = canvas.save();
14134                }
14135                // mAttachInfo cannot be null, otherwise scalingRequired == false
14136                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14137                canvas.scale(scale, scale);
14138            }
14139        }
14140
14141        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14142        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14143                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14144            if (transformToApply != null || !childHasIdentityMatrix) {
14145                int transX = 0;
14146                int transY = 0;
14147
14148                if (offsetForScroll) {
14149                    transX = -sx;
14150                    transY = -sy;
14151                }
14152
14153                if (transformToApply != null) {
14154                    if (concatMatrix) {
14155                        if (useDisplayListProperties) {
14156                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14157                        } else {
14158                            // Undo the scroll translation, apply the transformation matrix,
14159                            // then redo the scroll translate to get the correct result.
14160                            canvas.translate(-transX, -transY);
14161                            canvas.concat(transformToApply.getMatrix());
14162                            canvas.translate(transX, transY);
14163                        }
14164                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14165                    }
14166
14167                    float transformAlpha = transformToApply.getAlpha();
14168                    if (transformAlpha < 1) {
14169                        alpha *= transformAlpha;
14170                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14171                    }
14172                }
14173
14174                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14175                    canvas.translate(-transX, -transY);
14176                    canvas.concat(getMatrix());
14177                    canvas.translate(transX, transY);
14178                }
14179            }
14180
14181            // Deal with alpha if it is or used to be <1
14182            if (alpha < 1 ||
14183                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14184                if (alpha < 1) {
14185                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14186                } else {
14187                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14188                }
14189                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14190                if (hasNoCache) {
14191                    final int multipliedAlpha = (int) (255 * alpha);
14192                    if (!onSetAlpha(multipliedAlpha)) {
14193                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14194                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14195                                layerType != LAYER_TYPE_NONE) {
14196                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14197                        }
14198                        if (useDisplayListProperties) {
14199                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14200                        } else  if (layerType == LAYER_TYPE_NONE) {
14201                            final int scrollX = hasDisplayList ? 0 : sx;
14202                            final int scrollY = hasDisplayList ? 0 : sy;
14203                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14204                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14205                        }
14206                    } else {
14207                        // Alpha is handled by the child directly, clobber the layer's alpha
14208                        mPrivateFlags |= PFLAG_ALPHA_SET;
14209                    }
14210                }
14211            }
14212        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14213            onSetAlpha(255);
14214            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14215        }
14216
14217        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14218                !useDisplayListProperties && cache == null) {
14219            if (offsetForScroll) {
14220                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14221            } else {
14222                if (!scalingRequired || cache == null) {
14223                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14224                } else {
14225                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14226                }
14227            }
14228        }
14229
14230        if (!useDisplayListProperties && hasDisplayList) {
14231            displayList = getDisplayList();
14232            if (!displayList.isValid()) {
14233                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14234                // to getDisplayList(), the display list will be marked invalid and we should not
14235                // try to use it again.
14236                displayList = null;
14237                hasDisplayList = false;
14238            }
14239        }
14240
14241        if (hasNoCache) {
14242            boolean layerRendered = false;
14243            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14244                final HardwareLayer layer = getHardwareLayer();
14245                if (layer != null && layer.isValid()) {
14246                    mLayerPaint.setAlpha((int) (alpha * 255));
14247                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14248                    layerRendered = true;
14249                } else {
14250                    final int scrollX = hasDisplayList ? 0 : sx;
14251                    final int scrollY = hasDisplayList ? 0 : sy;
14252                    canvas.saveLayer(scrollX, scrollY,
14253                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14254                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14255                }
14256            }
14257
14258            if (!layerRendered) {
14259                if (!hasDisplayList) {
14260                    // Fast path for layouts with no backgrounds
14261                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14262                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14263                        dispatchDraw(canvas);
14264                    } else {
14265                        draw(canvas);
14266                    }
14267                } else {
14268                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14269                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14270                }
14271            }
14272        } else if (cache != null) {
14273            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14274            Paint cachePaint;
14275
14276            if (layerType == LAYER_TYPE_NONE) {
14277                cachePaint = parent.mCachePaint;
14278                if (cachePaint == null) {
14279                    cachePaint = new Paint();
14280                    cachePaint.setDither(false);
14281                    parent.mCachePaint = cachePaint;
14282                }
14283                if (alpha < 1) {
14284                    cachePaint.setAlpha((int) (alpha * 255));
14285                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14286                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14287                    cachePaint.setAlpha(255);
14288                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14289                }
14290            } else {
14291                cachePaint = mLayerPaint;
14292                cachePaint.setAlpha((int) (alpha * 255));
14293            }
14294            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14295        }
14296
14297        if (restoreTo >= 0) {
14298            canvas.restoreToCount(restoreTo);
14299        }
14300
14301        if (a != null && !more) {
14302            if (!hardwareAccelerated && !a.getFillAfter()) {
14303                onSetAlpha(255);
14304            }
14305            parent.finishAnimatingView(this, a);
14306        }
14307
14308        if (more && hardwareAccelerated) {
14309            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14310                // alpha animations should cause the child to recreate its display list
14311                invalidate(true);
14312            }
14313        }
14314
14315        mRecreateDisplayList = false;
14316
14317        return more;
14318    }
14319
14320    /**
14321     * Manually render this view (and all of its children) to the given Canvas.
14322     * The view must have already done a full layout before this function is
14323     * called.  When implementing a view, implement
14324     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14325     * If you do need to override this method, call the superclass version.
14326     *
14327     * @param canvas The Canvas to which the View is rendered.
14328     */
14329    public void draw(Canvas canvas) {
14330        if (mClipBounds != null) {
14331            canvas.clipRect(mClipBounds);
14332        }
14333        final int privateFlags = mPrivateFlags;
14334        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14335                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14336        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14337
14338        /*
14339         * Draw traversal performs several drawing steps which must be executed
14340         * in the appropriate order:
14341         *
14342         *      1. Draw the background
14343         *      2. If necessary, save the canvas' layers to prepare for fading
14344         *      3. Draw view's content
14345         *      4. Draw children
14346         *      5. If necessary, draw the fading edges and restore layers
14347         *      6. Draw decorations (scrollbars for instance)
14348         */
14349
14350        // Step 1, draw the background, if needed
14351        int saveCount;
14352
14353        if (!dirtyOpaque) {
14354            final Drawable background = mBackground;
14355            if (background != null) {
14356                final int scrollX = mScrollX;
14357                final int scrollY = mScrollY;
14358
14359                if (mBackgroundSizeChanged) {
14360                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14361                    mBackgroundSizeChanged = false;
14362                }
14363
14364                if ((scrollX | scrollY) == 0) {
14365                    background.draw(canvas);
14366                } else {
14367                    canvas.translate(scrollX, scrollY);
14368                    background.draw(canvas);
14369                    canvas.translate(-scrollX, -scrollY);
14370                }
14371            }
14372        }
14373
14374        // skip step 2 & 5 if possible (common case)
14375        final int viewFlags = mViewFlags;
14376        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14377        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14378        if (!verticalEdges && !horizontalEdges) {
14379            // Step 3, draw the content
14380            if (!dirtyOpaque) onDraw(canvas);
14381
14382            // Step 4, draw the children
14383            dispatchDraw(canvas);
14384
14385            // Step 6, draw decorations (scrollbars)
14386            onDrawScrollBars(canvas);
14387
14388            if (mOverlay != null && !mOverlay.isEmpty()) {
14389                mOverlay.getOverlayView().dispatchDraw(canvas);
14390            }
14391
14392            // we're done...
14393            return;
14394        }
14395
14396        /*
14397         * Here we do the full fledged routine...
14398         * (this is an uncommon case where speed matters less,
14399         * this is why we repeat some of the tests that have been
14400         * done above)
14401         */
14402
14403        boolean drawTop = false;
14404        boolean drawBottom = false;
14405        boolean drawLeft = false;
14406        boolean drawRight = false;
14407
14408        float topFadeStrength = 0.0f;
14409        float bottomFadeStrength = 0.0f;
14410        float leftFadeStrength = 0.0f;
14411        float rightFadeStrength = 0.0f;
14412
14413        // Step 2, save the canvas' layers
14414        int paddingLeft = mPaddingLeft;
14415
14416        final boolean offsetRequired = isPaddingOffsetRequired();
14417        if (offsetRequired) {
14418            paddingLeft += getLeftPaddingOffset();
14419        }
14420
14421        int left = mScrollX + paddingLeft;
14422        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14423        int top = mScrollY + getFadeTop(offsetRequired);
14424        int bottom = top + getFadeHeight(offsetRequired);
14425
14426        if (offsetRequired) {
14427            right += getRightPaddingOffset();
14428            bottom += getBottomPaddingOffset();
14429        }
14430
14431        final ScrollabilityCache scrollabilityCache = mScrollCache;
14432        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14433        int length = (int) fadeHeight;
14434
14435        // clip the fade length if top and bottom fades overlap
14436        // overlapping fades produce odd-looking artifacts
14437        if (verticalEdges && (top + length > bottom - length)) {
14438            length = (bottom - top) / 2;
14439        }
14440
14441        // also clip horizontal fades if necessary
14442        if (horizontalEdges && (left + length > right - length)) {
14443            length = (right - left) / 2;
14444        }
14445
14446        if (verticalEdges) {
14447            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14448            drawTop = topFadeStrength * fadeHeight > 1.0f;
14449            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14450            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14451        }
14452
14453        if (horizontalEdges) {
14454            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14455            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14456            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14457            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14458        }
14459
14460        saveCount = canvas.getSaveCount();
14461
14462        int solidColor = getSolidColor();
14463        if (solidColor == 0) {
14464            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14465
14466            if (drawTop) {
14467                canvas.saveLayer(left, top, right, top + length, null, flags);
14468            }
14469
14470            if (drawBottom) {
14471                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14472            }
14473
14474            if (drawLeft) {
14475                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14476            }
14477
14478            if (drawRight) {
14479                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14480            }
14481        } else {
14482            scrollabilityCache.setFadeColor(solidColor);
14483        }
14484
14485        // Step 3, draw the content
14486        if (!dirtyOpaque) onDraw(canvas);
14487
14488        // Step 4, draw the children
14489        dispatchDraw(canvas);
14490
14491        // Step 5, draw the fade effect and restore layers
14492        final Paint p = scrollabilityCache.paint;
14493        final Matrix matrix = scrollabilityCache.matrix;
14494        final Shader fade = scrollabilityCache.shader;
14495
14496        if (drawTop) {
14497            matrix.setScale(1, fadeHeight * topFadeStrength);
14498            matrix.postTranslate(left, top);
14499            fade.setLocalMatrix(matrix);
14500            canvas.drawRect(left, top, right, top + length, p);
14501        }
14502
14503        if (drawBottom) {
14504            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14505            matrix.postRotate(180);
14506            matrix.postTranslate(left, bottom);
14507            fade.setLocalMatrix(matrix);
14508            canvas.drawRect(left, bottom - length, right, bottom, p);
14509        }
14510
14511        if (drawLeft) {
14512            matrix.setScale(1, fadeHeight * leftFadeStrength);
14513            matrix.postRotate(-90);
14514            matrix.postTranslate(left, top);
14515            fade.setLocalMatrix(matrix);
14516            canvas.drawRect(left, top, left + length, bottom, p);
14517        }
14518
14519        if (drawRight) {
14520            matrix.setScale(1, fadeHeight * rightFadeStrength);
14521            matrix.postRotate(90);
14522            matrix.postTranslate(right, top);
14523            fade.setLocalMatrix(matrix);
14524            canvas.drawRect(right - length, top, right, bottom, p);
14525        }
14526
14527        canvas.restoreToCount(saveCount);
14528
14529        // Step 6, draw decorations (scrollbars)
14530        onDrawScrollBars(canvas);
14531
14532        if (mOverlay != null && !mOverlay.isEmpty()) {
14533            mOverlay.getOverlayView().dispatchDraw(canvas);
14534        }
14535    }
14536
14537    /**
14538     * Returns the overlay for this view, creating it if it does not yet exist.
14539     * Adding drawables to the overlay will cause them to be displayed whenever
14540     * the view itself is redrawn. Objects in the overlay should be actively
14541     * managed: remove them when they should not be displayed anymore. The
14542     * overlay will always have the same size as its host view.
14543     *
14544     * <p>Note: Overlays do not currently work correctly with {@link
14545     * SurfaceView} or {@link TextureView}; contents in overlays for these
14546     * types of views may not display correctly.</p>
14547     *
14548     * @return The ViewOverlay object for this view.
14549     * @see ViewOverlay
14550     */
14551    public ViewOverlay getOverlay() {
14552        if (mOverlay == null) {
14553            mOverlay = new ViewOverlay(mContext, this);
14554        }
14555        return mOverlay;
14556    }
14557
14558    /**
14559     * Override this if your view is known to always be drawn on top of a solid color background,
14560     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14561     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14562     * should be set to 0xFF.
14563     *
14564     * @see #setVerticalFadingEdgeEnabled(boolean)
14565     * @see #setHorizontalFadingEdgeEnabled(boolean)
14566     *
14567     * @return The known solid color background for this view, or 0 if the color may vary
14568     */
14569    @ViewDebug.ExportedProperty(category = "drawing")
14570    public int getSolidColor() {
14571        return 0;
14572    }
14573
14574    /**
14575     * Build a human readable string representation of the specified view flags.
14576     *
14577     * @param flags the view flags to convert to a string
14578     * @return a String representing the supplied flags
14579     */
14580    private static String printFlags(int flags) {
14581        String output = "";
14582        int numFlags = 0;
14583        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14584            output += "TAKES_FOCUS";
14585            numFlags++;
14586        }
14587
14588        switch (flags & VISIBILITY_MASK) {
14589        case INVISIBLE:
14590            if (numFlags > 0) {
14591                output += " ";
14592            }
14593            output += "INVISIBLE";
14594            // USELESS HERE numFlags++;
14595            break;
14596        case GONE:
14597            if (numFlags > 0) {
14598                output += " ";
14599            }
14600            output += "GONE";
14601            // USELESS HERE numFlags++;
14602            break;
14603        default:
14604            break;
14605        }
14606        return output;
14607    }
14608
14609    /**
14610     * Build a human readable string representation of the specified private
14611     * view flags.
14612     *
14613     * @param privateFlags the private view flags to convert to a string
14614     * @return a String representing the supplied flags
14615     */
14616    private static String printPrivateFlags(int privateFlags) {
14617        String output = "";
14618        int numFlags = 0;
14619
14620        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14621            output += "WANTS_FOCUS";
14622            numFlags++;
14623        }
14624
14625        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14626            if (numFlags > 0) {
14627                output += " ";
14628            }
14629            output += "FOCUSED";
14630            numFlags++;
14631        }
14632
14633        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14634            if (numFlags > 0) {
14635                output += " ";
14636            }
14637            output += "SELECTED";
14638            numFlags++;
14639        }
14640
14641        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14642            if (numFlags > 0) {
14643                output += " ";
14644            }
14645            output += "IS_ROOT_NAMESPACE";
14646            numFlags++;
14647        }
14648
14649        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14650            if (numFlags > 0) {
14651                output += " ";
14652            }
14653            output += "HAS_BOUNDS";
14654            numFlags++;
14655        }
14656
14657        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14658            if (numFlags > 0) {
14659                output += " ";
14660            }
14661            output += "DRAWN";
14662            // USELESS HERE numFlags++;
14663        }
14664        return output;
14665    }
14666
14667    /**
14668     * <p>Indicates whether or not this view's layout will be requested during
14669     * the next hierarchy layout pass.</p>
14670     *
14671     * @return true if the layout will be forced during next layout pass
14672     */
14673    public boolean isLayoutRequested() {
14674        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14675    }
14676
14677    /**
14678     * Return true if o is a ViewGroup that is laying out using optical bounds.
14679     * @hide
14680     */
14681    public static boolean isLayoutModeOptical(Object o) {
14682        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14683    }
14684
14685    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14686        Insets parentInsets = mParent instanceof View ?
14687                ((View) mParent).getOpticalInsets() : Insets.NONE;
14688        Insets childInsets = getOpticalInsets();
14689        return setFrame(
14690                left   + parentInsets.left - childInsets.left,
14691                top    + parentInsets.top  - childInsets.top,
14692                right  + parentInsets.left + childInsets.right,
14693                bottom + parentInsets.top  + childInsets.bottom);
14694    }
14695
14696    /**
14697     * Assign a size and position to a view and all of its
14698     * descendants
14699     *
14700     * <p>This is the second phase of the layout mechanism.
14701     * (The first is measuring). In this phase, each parent calls
14702     * layout on all of its children to position them.
14703     * This is typically done using the child measurements
14704     * that were stored in the measure pass().</p>
14705     *
14706     * <p>Derived classes should not override this method.
14707     * Derived classes with children should override
14708     * onLayout. In that method, they should
14709     * call layout on each of their children.</p>
14710     *
14711     * @param l Left position, relative to parent
14712     * @param t Top position, relative to parent
14713     * @param r Right position, relative to parent
14714     * @param b Bottom position, relative to parent
14715     */
14716    @SuppressWarnings({"unchecked"})
14717    public void layout(int l, int t, int r, int b) {
14718        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14719            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14720            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14721        }
14722
14723        int oldL = mLeft;
14724        int oldT = mTop;
14725        int oldB = mBottom;
14726        int oldR = mRight;
14727
14728        boolean changed = isLayoutModeOptical(mParent) ?
14729                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14730
14731        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14732            onLayout(changed, l, t, r, b);
14733            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14734
14735            ListenerInfo li = mListenerInfo;
14736            if (li != null && li.mOnLayoutChangeListeners != null) {
14737                ArrayList<OnLayoutChangeListener> listenersCopy =
14738                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14739                int numListeners = listenersCopy.size();
14740                for (int i = 0; i < numListeners; ++i) {
14741                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14742                }
14743            }
14744        }
14745
14746        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14747        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14748    }
14749
14750    /**
14751     * Called from layout when this view should
14752     * assign a size and position to each of its children.
14753     *
14754     * Derived classes with children should override
14755     * this method and call layout on each of
14756     * their children.
14757     * @param changed This is a new size or position for this view
14758     * @param left Left position, relative to parent
14759     * @param top Top position, relative to parent
14760     * @param right Right position, relative to parent
14761     * @param bottom Bottom position, relative to parent
14762     */
14763    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14764    }
14765
14766    /**
14767     * Assign a size and position to this view.
14768     *
14769     * This is called from layout.
14770     *
14771     * @param left Left position, relative to parent
14772     * @param top Top position, relative to parent
14773     * @param right Right position, relative to parent
14774     * @param bottom Bottom position, relative to parent
14775     * @return true if the new size and position are different than the
14776     *         previous ones
14777     * {@hide}
14778     */
14779    protected boolean setFrame(int left, int top, int right, int bottom) {
14780        boolean changed = false;
14781
14782        if (DBG) {
14783            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14784                    + right + "," + bottom + ")");
14785        }
14786
14787        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14788            changed = true;
14789
14790            // Remember our drawn bit
14791            int drawn = mPrivateFlags & PFLAG_DRAWN;
14792
14793            int oldWidth = mRight - mLeft;
14794            int oldHeight = mBottom - mTop;
14795            int newWidth = right - left;
14796            int newHeight = bottom - top;
14797            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14798
14799            // Invalidate our old position
14800            invalidate(sizeChanged);
14801
14802            mLeft = left;
14803            mTop = top;
14804            mRight = right;
14805            mBottom = bottom;
14806            if (mDisplayList != null) {
14807                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14808            }
14809
14810            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14811
14812
14813            if (sizeChanged) {
14814                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14815                    // A change in dimension means an auto-centered pivot point changes, too
14816                    if (mTransformationInfo != null) {
14817                        mTransformationInfo.mMatrixDirty = true;
14818                    }
14819                }
14820                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14821            }
14822
14823            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14824                // If we are visible, force the DRAWN bit to on so that
14825                // this invalidate will go through (at least to our parent).
14826                // This is because someone may have invalidated this view
14827                // before this call to setFrame came in, thereby clearing
14828                // the DRAWN bit.
14829                mPrivateFlags |= PFLAG_DRAWN;
14830                invalidate(sizeChanged);
14831                // parent display list may need to be recreated based on a change in the bounds
14832                // of any child
14833                invalidateParentCaches();
14834            }
14835
14836            // Reset drawn bit to original value (invalidate turns it off)
14837            mPrivateFlags |= drawn;
14838
14839            mBackgroundSizeChanged = true;
14840
14841            notifySubtreeAccessibilityStateChangedIfNeeded();
14842        }
14843        return changed;
14844    }
14845
14846    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14847        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14848        if (mOverlay != null) {
14849            mOverlay.getOverlayView().setRight(newWidth);
14850            mOverlay.getOverlayView().setBottom(newHeight);
14851        }
14852    }
14853
14854    /**
14855     * Finalize inflating a view from XML.  This is called as the last phase
14856     * of inflation, after all child views have been added.
14857     *
14858     * <p>Even if the subclass overrides onFinishInflate, they should always be
14859     * sure to call the super method, so that we get called.
14860     */
14861    protected void onFinishInflate() {
14862    }
14863
14864    /**
14865     * Returns the resources associated with this view.
14866     *
14867     * @return Resources object.
14868     */
14869    public Resources getResources() {
14870        return mResources;
14871    }
14872
14873    /**
14874     * Invalidates the specified Drawable.
14875     *
14876     * @param drawable the drawable to invalidate
14877     */
14878    public void invalidateDrawable(Drawable drawable) {
14879        if (verifyDrawable(drawable)) {
14880            final Rect dirty = drawable.getBounds();
14881            final int scrollX = mScrollX;
14882            final int scrollY = mScrollY;
14883
14884            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14885                    dirty.right + scrollX, dirty.bottom + scrollY);
14886        }
14887    }
14888
14889    /**
14890     * Schedules an action on a drawable to occur at a specified time.
14891     *
14892     * @param who the recipient of the action
14893     * @param what the action to run on the drawable
14894     * @param when the time at which the action must occur. Uses the
14895     *        {@link SystemClock#uptimeMillis} timebase.
14896     */
14897    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14898        if (verifyDrawable(who) && what != null) {
14899            final long delay = when - SystemClock.uptimeMillis();
14900            if (mAttachInfo != null) {
14901                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14902                        Choreographer.CALLBACK_ANIMATION, what, who,
14903                        Choreographer.subtractFrameDelay(delay));
14904            } else {
14905                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14906            }
14907        }
14908    }
14909
14910    /**
14911     * Cancels a scheduled action on a drawable.
14912     *
14913     * @param who the recipient of the action
14914     * @param what the action to cancel
14915     */
14916    public void unscheduleDrawable(Drawable who, Runnable what) {
14917        if (verifyDrawable(who) && what != null) {
14918            if (mAttachInfo != null) {
14919                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14920                        Choreographer.CALLBACK_ANIMATION, what, who);
14921            } else {
14922                ViewRootImpl.getRunQueue().removeCallbacks(what);
14923            }
14924        }
14925    }
14926
14927    /**
14928     * Unschedule any events associated with the given Drawable.  This can be
14929     * used when selecting a new Drawable into a view, so that the previous
14930     * one is completely unscheduled.
14931     *
14932     * @param who The Drawable to unschedule.
14933     *
14934     * @see #drawableStateChanged
14935     */
14936    public void unscheduleDrawable(Drawable who) {
14937        if (mAttachInfo != null && who != null) {
14938            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14939                    Choreographer.CALLBACK_ANIMATION, null, who);
14940        }
14941    }
14942
14943    /**
14944     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14945     * that the View directionality can and will be resolved before its Drawables.
14946     *
14947     * Will call {@link View#onResolveDrawables} when resolution is done.
14948     *
14949     * @hide
14950     */
14951    protected void resolveDrawables() {
14952        // Drawables resolution may need to happen before resolving the layout direction (which is
14953        // done only during the measure() call).
14954        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
14955        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
14956        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
14957        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
14958        // direction to be resolved as its resolved value will be the same as its raw value.
14959        if (!isLayoutDirectionResolved() &&
14960                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
14961            return;
14962        }
14963
14964        final int layoutDirection = isLayoutDirectionResolved() ?
14965                getLayoutDirection() : getRawLayoutDirection();
14966
14967        if (mBackground != null) {
14968            mBackground.setLayoutDirection(layoutDirection);
14969        }
14970        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14971        onResolveDrawables(layoutDirection);
14972    }
14973
14974    /**
14975     * Called when layout direction has been resolved.
14976     *
14977     * The default implementation does nothing.
14978     *
14979     * @param layoutDirection The resolved layout direction.
14980     *
14981     * @see #LAYOUT_DIRECTION_LTR
14982     * @see #LAYOUT_DIRECTION_RTL
14983     *
14984     * @hide
14985     */
14986    public void onResolveDrawables(int layoutDirection) {
14987    }
14988
14989    /**
14990     * @hide
14991     */
14992    protected void resetResolvedDrawables() {
14993        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14994    }
14995
14996    private boolean isDrawablesResolved() {
14997        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14998    }
14999
15000    /**
15001     * If your view subclass is displaying its own Drawable objects, it should
15002     * override this function and return true for any Drawable it is
15003     * displaying.  This allows animations for those drawables to be
15004     * scheduled.
15005     *
15006     * <p>Be sure to call through to the super class when overriding this
15007     * function.
15008     *
15009     * @param who The Drawable to verify.  Return true if it is one you are
15010     *            displaying, else return the result of calling through to the
15011     *            super class.
15012     *
15013     * @return boolean If true than the Drawable is being displayed in the
15014     *         view; else false and it is not allowed to animate.
15015     *
15016     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15017     * @see #drawableStateChanged()
15018     */
15019    protected boolean verifyDrawable(Drawable who) {
15020        return who == mBackground;
15021    }
15022
15023    /**
15024     * This function is called whenever the state of the view changes in such
15025     * a way that it impacts the state of drawables being shown.
15026     *
15027     * <p>Be sure to call through to the superclass when overriding this
15028     * function.
15029     *
15030     * @see Drawable#setState(int[])
15031     */
15032    protected void drawableStateChanged() {
15033        Drawable d = mBackground;
15034        if (d != null && d.isStateful()) {
15035            d.setState(getDrawableState());
15036        }
15037    }
15038
15039    /**
15040     * Call this to force a view to update its drawable state. This will cause
15041     * drawableStateChanged to be called on this view. Views that are interested
15042     * in the new state should call getDrawableState.
15043     *
15044     * @see #drawableStateChanged
15045     * @see #getDrawableState
15046     */
15047    public void refreshDrawableState() {
15048        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15049        drawableStateChanged();
15050
15051        ViewParent parent = mParent;
15052        if (parent != null) {
15053            parent.childDrawableStateChanged(this);
15054        }
15055    }
15056
15057    /**
15058     * Return an array of resource IDs of the drawable states representing the
15059     * current state of the view.
15060     *
15061     * @return The current drawable state
15062     *
15063     * @see Drawable#setState(int[])
15064     * @see #drawableStateChanged()
15065     * @see #onCreateDrawableState(int)
15066     */
15067    public final int[] getDrawableState() {
15068        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15069            return mDrawableState;
15070        } else {
15071            mDrawableState = onCreateDrawableState(0);
15072            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15073            return mDrawableState;
15074        }
15075    }
15076
15077    /**
15078     * Generate the new {@link android.graphics.drawable.Drawable} state for
15079     * this view. This is called by the view
15080     * system when the cached Drawable state is determined to be invalid.  To
15081     * retrieve the current state, you should use {@link #getDrawableState}.
15082     *
15083     * @param extraSpace if non-zero, this is the number of extra entries you
15084     * would like in the returned array in which you can place your own
15085     * states.
15086     *
15087     * @return Returns an array holding the current {@link Drawable} state of
15088     * the view.
15089     *
15090     * @see #mergeDrawableStates(int[], int[])
15091     */
15092    protected int[] onCreateDrawableState(int extraSpace) {
15093        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15094                mParent instanceof View) {
15095            return ((View) mParent).onCreateDrawableState(extraSpace);
15096        }
15097
15098        int[] drawableState;
15099
15100        int privateFlags = mPrivateFlags;
15101
15102        int viewStateIndex = 0;
15103        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15104        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15105        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15106        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15107        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15108        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15109        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15110                HardwareRenderer.isAvailable()) {
15111            // This is set if HW acceleration is requested, even if the current
15112            // process doesn't allow it.  This is just to allow app preview
15113            // windows to better match their app.
15114            viewStateIndex |= VIEW_STATE_ACCELERATED;
15115        }
15116        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15117
15118        final int privateFlags2 = mPrivateFlags2;
15119        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15120        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15121
15122        drawableState = VIEW_STATE_SETS[viewStateIndex];
15123
15124        //noinspection ConstantIfStatement
15125        if (false) {
15126            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15127            Log.i("View", toString()
15128                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15129                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15130                    + " fo=" + hasFocus()
15131                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15132                    + " wf=" + hasWindowFocus()
15133                    + ": " + Arrays.toString(drawableState));
15134        }
15135
15136        if (extraSpace == 0) {
15137            return drawableState;
15138        }
15139
15140        final int[] fullState;
15141        if (drawableState != null) {
15142            fullState = new int[drawableState.length + extraSpace];
15143            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15144        } else {
15145            fullState = new int[extraSpace];
15146        }
15147
15148        return fullState;
15149    }
15150
15151    /**
15152     * Merge your own state values in <var>additionalState</var> into the base
15153     * state values <var>baseState</var> that were returned by
15154     * {@link #onCreateDrawableState(int)}.
15155     *
15156     * @param baseState The base state values returned by
15157     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15158     * own additional state values.
15159     *
15160     * @param additionalState The additional state values you would like
15161     * added to <var>baseState</var>; this array is not modified.
15162     *
15163     * @return As a convenience, the <var>baseState</var> array you originally
15164     * passed into the function is returned.
15165     *
15166     * @see #onCreateDrawableState(int)
15167     */
15168    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15169        final int N = baseState.length;
15170        int i = N - 1;
15171        while (i >= 0 && baseState[i] == 0) {
15172            i--;
15173        }
15174        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15175        return baseState;
15176    }
15177
15178    /**
15179     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15180     * on all Drawable objects associated with this view.
15181     */
15182    public void jumpDrawablesToCurrentState() {
15183        if (mBackground != null) {
15184            mBackground.jumpToCurrentState();
15185        }
15186    }
15187
15188    /**
15189     * Sets the background color for this view.
15190     * @param color the color of the background
15191     */
15192    @RemotableViewMethod
15193    public void setBackgroundColor(int color) {
15194        if (mBackground instanceof ColorDrawable) {
15195            ((ColorDrawable) mBackground.mutate()).setColor(color);
15196            computeOpaqueFlags();
15197            mBackgroundResource = 0;
15198        } else {
15199            setBackground(new ColorDrawable(color));
15200        }
15201    }
15202
15203    /**
15204     * Set the background to a given resource. The resource should refer to
15205     * a Drawable object or 0 to remove the background.
15206     * @param resid The identifier of the resource.
15207     *
15208     * @attr ref android.R.styleable#View_background
15209     */
15210    @RemotableViewMethod
15211    public void setBackgroundResource(int resid) {
15212        if (resid != 0 && resid == mBackgroundResource) {
15213            return;
15214        }
15215
15216        Drawable d= null;
15217        if (resid != 0) {
15218            d = mResources.getDrawable(resid);
15219        }
15220        setBackground(d);
15221
15222        mBackgroundResource = resid;
15223    }
15224
15225    /**
15226     * Set the background to a given Drawable, or remove the background. If the
15227     * background has padding, this View's padding is set to the background's
15228     * padding. However, when a background is removed, this View's padding isn't
15229     * touched. If setting the padding is desired, please use
15230     * {@link #setPadding(int, int, int, int)}.
15231     *
15232     * @param background The Drawable to use as the background, or null to remove the
15233     *        background
15234     */
15235    public void setBackground(Drawable background) {
15236        //noinspection deprecation
15237        setBackgroundDrawable(background);
15238    }
15239
15240    /**
15241     * @deprecated use {@link #setBackground(Drawable)} instead
15242     */
15243    @Deprecated
15244    public void setBackgroundDrawable(Drawable background) {
15245        computeOpaqueFlags();
15246
15247        if (background == mBackground) {
15248            return;
15249        }
15250
15251        boolean requestLayout = false;
15252
15253        mBackgroundResource = 0;
15254
15255        /*
15256         * Regardless of whether we're setting a new background or not, we want
15257         * to clear the previous drawable.
15258         */
15259        if (mBackground != null) {
15260            mBackground.setCallback(null);
15261            unscheduleDrawable(mBackground);
15262        }
15263
15264        if (background != null) {
15265            Rect padding = sThreadLocal.get();
15266            if (padding == null) {
15267                padding = new Rect();
15268                sThreadLocal.set(padding);
15269            }
15270            resetResolvedDrawables();
15271            background.setLayoutDirection(getLayoutDirection());
15272            if (background.getPadding(padding)) {
15273                resetResolvedPadding();
15274                switch (background.getLayoutDirection()) {
15275                    case LAYOUT_DIRECTION_RTL:
15276                        mUserPaddingLeftInitial = padding.right;
15277                        mUserPaddingRightInitial = padding.left;
15278                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15279                        break;
15280                    case LAYOUT_DIRECTION_LTR:
15281                    default:
15282                        mUserPaddingLeftInitial = padding.left;
15283                        mUserPaddingRightInitial = padding.right;
15284                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15285                }
15286            }
15287
15288            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15289            // if it has a different minimum size, we should layout again
15290            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15291                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15292                requestLayout = true;
15293            }
15294
15295            background.setCallback(this);
15296            if (background.isStateful()) {
15297                background.setState(getDrawableState());
15298            }
15299            background.setVisible(getVisibility() == VISIBLE, false);
15300            mBackground = background;
15301
15302            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15303                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15304                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15305                requestLayout = true;
15306            }
15307        } else {
15308            /* Remove the background */
15309            mBackground = null;
15310
15311            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15312                /*
15313                 * This view ONLY drew the background before and we're removing
15314                 * the background, so now it won't draw anything
15315                 * (hence we SKIP_DRAW)
15316                 */
15317                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15318                mPrivateFlags |= PFLAG_SKIP_DRAW;
15319            }
15320
15321            /*
15322             * When the background is set, we try to apply its padding to this
15323             * View. When the background is removed, we don't touch this View's
15324             * padding. This is noted in the Javadocs. Hence, we don't need to
15325             * requestLayout(), the invalidate() below is sufficient.
15326             */
15327
15328            // The old background's minimum size could have affected this
15329            // View's layout, so let's requestLayout
15330            requestLayout = true;
15331        }
15332
15333        computeOpaqueFlags();
15334
15335        if (requestLayout) {
15336            requestLayout();
15337        }
15338
15339        mBackgroundSizeChanged = true;
15340        invalidate(true);
15341    }
15342
15343    /**
15344     * Gets the background drawable
15345     *
15346     * @return The drawable used as the background for this view, if any.
15347     *
15348     * @see #setBackground(Drawable)
15349     *
15350     * @attr ref android.R.styleable#View_background
15351     */
15352    public Drawable getBackground() {
15353        return mBackground;
15354    }
15355
15356    /**
15357     * Sets the padding. The view may add on the space required to display
15358     * the scrollbars, depending on the style and visibility of the scrollbars.
15359     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15360     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15361     * from the values set in this call.
15362     *
15363     * @attr ref android.R.styleable#View_padding
15364     * @attr ref android.R.styleable#View_paddingBottom
15365     * @attr ref android.R.styleable#View_paddingLeft
15366     * @attr ref android.R.styleable#View_paddingRight
15367     * @attr ref android.R.styleable#View_paddingTop
15368     * @param left the left padding in pixels
15369     * @param top the top padding in pixels
15370     * @param right the right padding in pixels
15371     * @param bottom the bottom padding in pixels
15372     */
15373    public void setPadding(int left, int top, int right, int bottom) {
15374        resetResolvedPadding();
15375
15376        mUserPaddingStart = UNDEFINED_PADDING;
15377        mUserPaddingEnd = UNDEFINED_PADDING;
15378
15379        mUserPaddingLeftInitial = left;
15380        mUserPaddingRightInitial = right;
15381
15382        internalSetPadding(left, top, right, bottom);
15383    }
15384
15385    /**
15386     * @hide
15387     */
15388    protected void internalSetPadding(int left, int top, int right, int bottom) {
15389        mUserPaddingLeft = left;
15390        mUserPaddingRight = right;
15391        mUserPaddingBottom = bottom;
15392
15393        final int viewFlags = mViewFlags;
15394        boolean changed = false;
15395
15396        // Common case is there are no scroll bars.
15397        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15398            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15399                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15400                        ? 0 : getVerticalScrollbarWidth();
15401                switch (mVerticalScrollbarPosition) {
15402                    case SCROLLBAR_POSITION_DEFAULT:
15403                        if (isLayoutRtl()) {
15404                            left += offset;
15405                        } else {
15406                            right += offset;
15407                        }
15408                        break;
15409                    case SCROLLBAR_POSITION_RIGHT:
15410                        right += offset;
15411                        break;
15412                    case SCROLLBAR_POSITION_LEFT:
15413                        left += offset;
15414                        break;
15415                }
15416            }
15417            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15418                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15419                        ? 0 : getHorizontalScrollbarHeight();
15420            }
15421        }
15422
15423        if (mPaddingLeft != left) {
15424            changed = true;
15425            mPaddingLeft = left;
15426        }
15427        if (mPaddingTop != top) {
15428            changed = true;
15429            mPaddingTop = top;
15430        }
15431        if (mPaddingRight != right) {
15432            changed = true;
15433            mPaddingRight = right;
15434        }
15435        if (mPaddingBottom != bottom) {
15436            changed = true;
15437            mPaddingBottom = bottom;
15438        }
15439
15440        if (changed) {
15441            requestLayout();
15442        }
15443    }
15444
15445    /**
15446     * Sets the relative padding. The view may add on the space required to display
15447     * the scrollbars, depending on the style and visibility of the scrollbars.
15448     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15449     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15450     * from the values set in this call.
15451     *
15452     * @attr ref android.R.styleable#View_padding
15453     * @attr ref android.R.styleable#View_paddingBottom
15454     * @attr ref android.R.styleable#View_paddingStart
15455     * @attr ref android.R.styleable#View_paddingEnd
15456     * @attr ref android.R.styleable#View_paddingTop
15457     * @param start the start padding in pixels
15458     * @param top the top padding in pixels
15459     * @param end the end padding in pixels
15460     * @param bottom the bottom padding in pixels
15461     */
15462    public void setPaddingRelative(int start, int top, int end, int bottom) {
15463        resetResolvedPadding();
15464
15465        mUserPaddingStart = start;
15466        mUserPaddingEnd = end;
15467
15468        switch(getLayoutDirection()) {
15469            case LAYOUT_DIRECTION_RTL:
15470                mUserPaddingLeftInitial = end;
15471                mUserPaddingRightInitial = start;
15472                internalSetPadding(end, top, start, bottom);
15473                break;
15474            case LAYOUT_DIRECTION_LTR:
15475            default:
15476                mUserPaddingLeftInitial = start;
15477                mUserPaddingRightInitial = end;
15478                internalSetPadding(start, top, end, bottom);
15479        }
15480    }
15481
15482    /**
15483     * Returns the top padding of this view.
15484     *
15485     * @return the top padding in pixels
15486     */
15487    public int getPaddingTop() {
15488        return mPaddingTop;
15489    }
15490
15491    /**
15492     * Returns the bottom padding of this view. If there are inset and enabled
15493     * scrollbars, this value may include the space required to display the
15494     * scrollbars as well.
15495     *
15496     * @return the bottom padding in pixels
15497     */
15498    public int getPaddingBottom() {
15499        return mPaddingBottom;
15500    }
15501
15502    /**
15503     * Returns the left padding of this view. If there are inset and enabled
15504     * scrollbars, this value may include the space required to display the
15505     * scrollbars as well.
15506     *
15507     * @return the left padding in pixels
15508     */
15509    public int getPaddingLeft() {
15510        if (!isPaddingResolved()) {
15511            resolvePadding();
15512        }
15513        return mPaddingLeft;
15514    }
15515
15516    /**
15517     * Returns the start padding of this view depending on its resolved layout direction.
15518     * If there are inset and enabled scrollbars, this value may include the space
15519     * required to display the scrollbars as well.
15520     *
15521     * @return the start padding in pixels
15522     */
15523    public int getPaddingStart() {
15524        if (!isPaddingResolved()) {
15525            resolvePadding();
15526        }
15527        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15528                mPaddingRight : mPaddingLeft;
15529    }
15530
15531    /**
15532     * Returns the right padding of this view. If there are inset and enabled
15533     * scrollbars, this value may include the space required to display the
15534     * scrollbars as well.
15535     *
15536     * @return the right padding in pixels
15537     */
15538    public int getPaddingRight() {
15539        if (!isPaddingResolved()) {
15540            resolvePadding();
15541        }
15542        return mPaddingRight;
15543    }
15544
15545    /**
15546     * Returns the end padding of this view depending on its resolved layout direction.
15547     * If there are inset and enabled scrollbars, this value may include the space
15548     * required to display the scrollbars as well.
15549     *
15550     * @return the end padding in pixels
15551     */
15552    public int getPaddingEnd() {
15553        if (!isPaddingResolved()) {
15554            resolvePadding();
15555        }
15556        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15557                mPaddingLeft : mPaddingRight;
15558    }
15559
15560    /**
15561     * Return if the padding as been set thru relative values
15562     * {@link #setPaddingRelative(int, int, int, int)} or thru
15563     * @attr ref android.R.styleable#View_paddingStart or
15564     * @attr ref android.R.styleable#View_paddingEnd
15565     *
15566     * @return true if the padding is relative or false if it is not.
15567     */
15568    public boolean isPaddingRelative() {
15569        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15570    }
15571
15572    Insets computeOpticalInsets() {
15573        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15574    }
15575
15576    /**
15577     * @hide
15578     */
15579    public void resetPaddingToInitialValues() {
15580        if (isRtlCompatibilityMode()) {
15581            mPaddingLeft = mUserPaddingLeftInitial;
15582            mPaddingRight = mUserPaddingRightInitial;
15583            return;
15584        }
15585        if (isLayoutRtl()) {
15586            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15587            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15588        } else {
15589            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15590            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15591        }
15592    }
15593
15594    /**
15595     * @hide
15596     */
15597    public Insets getOpticalInsets() {
15598        if (mLayoutInsets == null) {
15599            mLayoutInsets = computeOpticalInsets();
15600        }
15601        return mLayoutInsets;
15602    }
15603
15604    /**
15605     * Changes the selection state of this view. A view can be selected or not.
15606     * Note that selection is not the same as focus. Views are typically
15607     * selected in the context of an AdapterView like ListView or GridView;
15608     * the selected view is the view that is highlighted.
15609     *
15610     * @param selected true if the view must be selected, false otherwise
15611     */
15612    public void setSelected(boolean selected) {
15613        //noinspection DoubleNegation
15614        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15615            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15616            if (!selected) resetPressedState();
15617            invalidate(true);
15618            refreshDrawableState();
15619            dispatchSetSelected(selected);
15620            notifyViewAccessibilityStateChangedIfNeeded(
15621                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
15622        }
15623    }
15624
15625    /**
15626     * Dispatch setSelected to all of this View's children.
15627     *
15628     * @see #setSelected(boolean)
15629     *
15630     * @param selected The new selected state
15631     */
15632    protected void dispatchSetSelected(boolean selected) {
15633    }
15634
15635    /**
15636     * Indicates the selection state of this view.
15637     *
15638     * @return true if the view is selected, false otherwise
15639     */
15640    @ViewDebug.ExportedProperty
15641    public boolean isSelected() {
15642        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15643    }
15644
15645    /**
15646     * Changes the activated state of this view. A view can be activated or not.
15647     * Note that activation is not the same as selection.  Selection is
15648     * a transient property, representing the view (hierarchy) the user is
15649     * currently interacting with.  Activation is a longer-term state that the
15650     * user can move views in and out of.  For example, in a list view with
15651     * single or multiple selection enabled, the views in the current selection
15652     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15653     * here.)  The activated state is propagated down to children of the view it
15654     * is set on.
15655     *
15656     * @param activated true if the view must be activated, false otherwise
15657     */
15658    public void setActivated(boolean activated) {
15659        //noinspection DoubleNegation
15660        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15661            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15662            invalidate(true);
15663            refreshDrawableState();
15664            dispatchSetActivated(activated);
15665        }
15666    }
15667
15668    /**
15669     * Dispatch setActivated to all of this View's children.
15670     *
15671     * @see #setActivated(boolean)
15672     *
15673     * @param activated The new activated state
15674     */
15675    protected void dispatchSetActivated(boolean activated) {
15676    }
15677
15678    /**
15679     * Indicates the activation state of this view.
15680     *
15681     * @return true if the view is activated, false otherwise
15682     */
15683    @ViewDebug.ExportedProperty
15684    public boolean isActivated() {
15685        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15686    }
15687
15688    /**
15689     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15690     * observer can be used to get notifications when global events, like
15691     * layout, happen.
15692     *
15693     * The returned ViewTreeObserver observer is not guaranteed to remain
15694     * valid for the lifetime of this View. If the caller of this method keeps
15695     * a long-lived reference to ViewTreeObserver, it should always check for
15696     * the return value of {@link ViewTreeObserver#isAlive()}.
15697     *
15698     * @return The ViewTreeObserver for this view's hierarchy.
15699     */
15700    public ViewTreeObserver getViewTreeObserver() {
15701        if (mAttachInfo != null) {
15702            return mAttachInfo.mTreeObserver;
15703        }
15704        if (mFloatingTreeObserver == null) {
15705            mFloatingTreeObserver = new ViewTreeObserver();
15706        }
15707        return mFloatingTreeObserver;
15708    }
15709
15710    /**
15711     * <p>Finds the topmost view in the current view hierarchy.</p>
15712     *
15713     * @return the topmost view containing this view
15714     */
15715    public View getRootView() {
15716        if (mAttachInfo != null) {
15717            final View v = mAttachInfo.mRootView;
15718            if (v != null) {
15719                return v;
15720            }
15721        }
15722
15723        View parent = this;
15724
15725        while (parent.mParent != null && parent.mParent instanceof View) {
15726            parent = (View) parent.mParent;
15727        }
15728
15729        return parent;
15730    }
15731
15732    /**
15733     * Transforms a motion event from view-local coordinates to on-screen
15734     * coordinates.
15735     *
15736     * @param ev the view-local motion event
15737     * @return false if the transformation could not be applied
15738     * @hide
15739     */
15740    public boolean toGlobalMotionEvent(MotionEvent ev) {
15741        final AttachInfo info = mAttachInfo;
15742        if (info == null) {
15743            return false;
15744        }
15745
15746        transformMotionEventToGlobal(ev);
15747        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
15748        return true;
15749    }
15750
15751    /**
15752     * Transforms a motion event from on-screen coordinates to view-local
15753     * coordinates.
15754     *
15755     * @param ev the on-screen motion event
15756     * @return false if the transformation could not be applied
15757     * @hide
15758     */
15759    public boolean toLocalMotionEvent(MotionEvent ev) {
15760        final AttachInfo info = mAttachInfo;
15761        if (info == null) {
15762            return false;
15763        }
15764
15765        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
15766        transformMotionEventToLocal(ev);
15767        return true;
15768    }
15769
15770    /**
15771     * Recursive helper method that applies transformations in post-order.
15772     *
15773     * @param ev the on-screen motion event
15774     */
15775    private void transformMotionEventToLocal(MotionEvent ev) {
15776        final ViewParent parent = mParent;
15777        if (parent instanceof View) {
15778            final View vp = (View) parent;
15779            vp.transformMotionEventToLocal(ev);
15780            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
15781        } else if (parent instanceof ViewRootImpl) {
15782            final ViewRootImpl vr = (ViewRootImpl) parent;
15783            ev.offsetLocation(0, vr.mCurScrollY);
15784        }
15785
15786        ev.offsetLocation(-mLeft, -mTop);
15787
15788        if (!hasIdentityMatrix()) {
15789            ev.transform(getInverseMatrix());
15790        }
15791    }
15792
15793    /**
15794     * Recursive helper method that applies transformations in pre-order.
15795     *
15796     * @param ev the on-screen motion event
15797     */
15798    private void transformMotionEventToGlobal(MotionEvent ev) {
15799        if (!hasIdentityMatrix()) {
15800            ev.transform(getMatrix());
15801        }
15802
15803        ev.offsetLocation(mLeft, mTop);
15804
15805        final ViewParent parent = mParent;
15806        if (parent instanceof View) {
15807            final View vp = (View) parent;
15808            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
15809            vp.transformMotionEventToGlobal(ev);
15810        } else if (parent instanceof ViewRootImpl) {
15811            final ViewRootImpl vr = (ViewRootImpl) parent;
15812            ev.offsetLocation(0, -vr.mCurScrollY);
15813        }
15814    }
15815
15816    /**
15817     * <p>Computes the coordinates of this view on the screen. The argument
15818     * must be an array of two integers. After the method returns, the array
15819     * contains the x and y location in that order.</p>
15820     *
15821     * @param location an array of two integers in which to hold the coordinates
15822     */
15823    public void getLocationOnScreen(int[] location) {
15824        getLocationInWindow(location);
15825
15826        final AttachInfo info = mAttachInfo;
15827        if (info != null) {
15828            location[0] += info.mWindowLeft;
15829            location[1] += info.mWindowTop;
15830        }
15831    }
15832
15833    /**
15834     * <p>Computes the coordinates of this view in its window. The argument
15835     * must be an array of two integers. After the method returns, the array
15836     * contains the x and y location in that order.</p>
15837     *
15838     * @param location an array of two integers in which to hold the coordinates
15839     */
15840    public void getLocationInWindow(int[] location) {
15841        if (location == null || location.length < 2) {
15842            throw new IllegalArgumentException("location must be an array of two integers");
15843        }
15844
15845        if (mAttachInfo == null) {
15846            // When the view is not attached to a window, this method does not make sense
15847            location[0] = location[1] = 0;
15848            return;
15849        }
15850
15851        float[] position = mAttachInfo.mTmpTransformLocation;
15852        position[0] = position[1] = 0.0f;
15853
15854        if (!hasIdentityMatrix()) {
15855            getMatrix().mapPoints(position);
15856        }
15857
15858        position[0] += mLeft;
15859        position[1] += mTop;
15860
15861        ViewParent viewParent = mParent;
15862        while (viewParent instanceof View) {
15863            final View view = (View) viewParent;
15864
15865            position[0] -= view.mScrollX;
15866            position[1] -= view.mScrollY;
15867
15868            if (!view.hasIdentityMatrix()) {
15869                view.getMatrix().mapPoints(position);
15870            }
15871
15872            position[0] += view.mLeft;
15873            position[1] += view.mTop;
15874
15875            viewParent = view.mParent;
15876         }
15877
15878        if (viewParent instanceof ViewRootImpl) {
15879            // *cough*
15880            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15881            position[1] -= vr.mCurScrollY;
15882        }
15883
15884        location[0] = (int) (position[0] + 0.5f);
15885        location[1] = (int) (position[1] + 0.5f);
15886    }
15887
15888    /**
15889     * {@hide}
15890     * @param id the id of the view to be found
15891     * @return the view of the specified id, null if cannot be found
15892     */
15893    protected View findViewTraversal(int id) {
15894        if (id == mID) {
15895            return this;
15896        }
15897        return null;
15898    }
15899
15900    /**
15901     * {@hide}
15902     * @param tag the tag of the view to be found
15903     * @return the view of specified tag, null if cannot be found
15904     */
15905    protected View findViewWithTagTraversal(Object tag) {
15906        if (tag != null && tag.equals(mTag)) {
15907            return this;
15908        }
15909        return null;
15910    }
15911
15912    /**
15913     * {@hide}
15914     * @param predicate The predicate to evaluate.
15915     * @param childToSkip If not null, ignores this child during the recursive traversal.
15916     * @return The first view that matches the predicate or null.
15917     */
15918    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15919        if (predicate.apply(this)) {
15920            return this;
15921        }
15922        return null;
15923    }
15924
15925    /**
15926     * Look for a child view with the given id.  If this view has the given
15927     * id, return this view.
15928     *
15929     * @param id The id to search for.
15930     * @return The view that has the given id in the hierarchy or null
15931     */
15932    public final View findViewById(int id) {
15933        if (id < 0) {
15934            return null;
15935        }
15936        return findViewTraversal(id);
15937    }
15938
15939    /**
15940     * Finds a view by its unuque and stable accessibility id.
15941     *
15942     * @param accessibilityId The searched accessibility id.
15943     * @return The found view.
15944     */
15945    final View findViewByAccessibilityId(int accessibilityId) {
15946        if (accessibilityId < 0) {
15947            return null;
15948        }
15949        return findViewByAccessibilityIdTraversal(accessibilityId);
15950    }
15951
15952    /**
15953     * Performs the traversal to find a view by its unuque and stable accessibility id.
15954     *
15955     * <strong>Note:</strong>This method does not stop at the root namespace
15956     * boundary since the user can touch the screen at an arbitrary location
15957     * potentially crossing the root namespace bounday which will send an
15958     * accessibility event to accessibility services and they should be able
15959     * to obtain the event source. Also accessibility ids are guaranteed to be
15960     * unique in the window.
15961     *
15962     * @param accessibilityId The accessibility id.
15963     * @return The found view.
15964     *
15965     * @hide
15966     */
15967    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15968        if (getAccessibilityViewId() == accessibilityId) {
15969            return this;
15970        }
15971        return null;
15972    }
15973
15974    /**
15975     * Look for a child view with the given tag.  If this view has the given
15976     * tag, return this view.
15977     *
15978     * @param tag The tag to search for, using "tag.equals(getTag())".
15979     * @return The View that has the given tag in the hierarchy or null
15980     */
15981    public final View findViewWithTag(Object tag) {
15982        if (tag == null) {
15983            return null;
15984        }
15985        return findViewWithTagTraversal(tag);
15986    }
15987
15988    /**
15989     * {@hide}
15990     * Look for a child view that matches the specified predicate.
15991     * If this view matches the predicate, return this view.
15992     *
15993     * @param predicate The predicate to evaluate.
15994     * @return The first view that matches the predicate or null.
15995     */
15996    public final View findViewByPredicate(Predicate<View> predicate) {
15997        return findViewByPredicateTraversal(predicate, null);
15998    }
15999
16000    /**
16001     * {@hide}
16002     * Look for a child view that matches the specified predicate,
16003     * starting with the specified view and its descendents and then
16004     * recusively searching the ancestors and siblings of that view
16005     * until this view is reached.
16006     *
16007     * This method is useful in cases where the predicate does not match
16008     * a single unique view (perhaps multiple views use the same id)
16009     * and we are trying to find the view that is "closest" in scope to the
16010     * starting view.
16011     *
16012     * @param start The view to start from.
16013     * @param predicate The predicate to evaluate.
16014     * @return The first view that matches the predicate or null.
16015     */
16016    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16017        View childToSkip = null;
16018        for (;;) {
16019            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16020            if (view != null || start == this) {
16021                return view;
16022            }
16023
16024            ViewParent parent = start.getParent();
16025            if (parent == null || !(parent instanceof View)) {
16026                return null;
16027            }
16028
16029            childToSkip = start;
16030            start = (View) parent;
16031        }
16032    }
16033
16034    /**
16035     * Sets the identifier for this view. The identifier does not have to be
16036     * unique in this view's hierarchy. The identifier should be a positive
16037     * number.
16038     *
16039     * @see #NO_ID
16040     * @see #getId()
16041     * @see #findViewById(int)
16042     *
16043     * @param id a number used to identify the view
16044     *
16045     * @attr ref android.R.styleable#View_id
16046     */
16047    public void setId(int id) {
16048        mID = id;
16049        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16050            mID = generateViewId();
16051        }
16052    }
16053
16054    /**
16055     * {@hide}
16056     *
16057     * @param isRoot true if the view belongs to the root namespace, false
16058     *        otherwise
16059     */
16060    public void setIsRootNamespace(boolean isRoot) {
16061        if (isRoot) {
16062            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16063        } else {
16064            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16065        }
16066    }
16067
16068    /**
16069     * {@hide}
16070     *
16071     * @return true if the view belongs to the root namespace, false otherwise
16072     */
16073    public boolean isRootNamespace() {
16074        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16075    }
16076
16077    /**
16078     * Returns this view's identifier.
16079     *
16080     * @return a positive integer used to identify the view or {@link #NO_ID}
16081     *         if the view has no ID
16082     *
16083     * @see #setId(int)
16084     * @see #findViewById(int)
16085     * @attr ref android.R.styleable#View_id
16086     */
16087    @ViewDebug.CapturedViewProperty
16088    public int getId() {
16089        return mID;
16090    }
16091
16092    /**
16093     * Returns this view's tag.
16094     *
16095     * @return the Object stored in this view as a tag
16096     *
16097     * @see #setTag(Object)
16098     * @see #getTag(int)
16099     */
16100    @ViewDebug.ExportedProperty
16101    public Object getTag() {
16102        return mTag;
16103    }
16104
16105    /**
16106     * Sets the tag associated with this view. A tag can be used to mark
16107     * a view in its hierarchy and does not have to be unique within the
16108     * hierarchy. Tags can also be used to store data within a view without
16109     * resorting to another data structure.
16110     *
16111     * @param tag an Object to tag the view with
16112     *
16113     * @see #getTag()
16114     * @see #setTag(int, Object)
16115     */
16116    public void setTag(final Object tag) {
16117        mTag = tag;
16118    }
16119
16120    /**
16121     * Returns the tag associated with this view and the specified key.
16122     *
16123     * @param key The key identifying the tag
16124     *
16125     * @return the Object stored in this view as a tag
16126     *
16127     * @see #setTag(int, Object)
16128     * @see #getTag()
16129     */
16130    public Object getTag(int key) {
16131        if (mKeyedTags != null) return mKeyedTags.get(key);
16132        return null;
16133    }
16134
16135    /**
16136     * Sets a tag associated with this view and a key. A tag can be used
16137     * to mark a view in its hierarchy and does not have to be unique within
16138     * the hierarchy. Tags can also be used to store data within a view
16139     * without resorting to another data structure.
16140     *
16141     * The specified key should be an id declared in the resources of the
16142     * application to ensure it is unique (see the <a
16143     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16144     * Keys identified as belonging to
16145     * the Android framework or not associated with any package will cause
16146     * an {@link IllegalArgumentException} to be thrown.
16147     *
16148     * @param key The key identifying the tag
16149     * @param tag An Object to tag the view with
16150     *
16151     * @throws IllegalArgumentException If they specified key is not valid
16152     *
16153     * @see #setTag(Object)
16154     * @see #getTag(int)
16155     */
16156    public void setTag(int key, final Object tag) {
16157        // If the package id is 0x00 or 0x01, it's either an undefined package
16158        // or a framework id
16159        if ((key >>> 24) < 2) {
16160            throw new IllegalArgumentException("The key must be an application-specific "
16161                    + "resource id.");
16162        }
16163
16164        setKeyedTag(key, tag);
16165    }
16166
16167    /**
16168     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16169     * framework id.
16170     *
16171     * @hide
16172     */
16173    public void setTagInternal(int key, Object tag) {
16174        if ((key >>> 24) != 0x1) {
16175            throw new IllegalArgumentException("The key must be a framework-specific "
16176                    + "resource id.");
16177        }
16178
16179        setKeyedTag(key, tag);
16180    }
16181
16182    private void setKeyedTag(int key, Object tag) {
16183        if (mKeyedTags == null) {
16184            mKeyedTags = new SparseArray<Object>(2);
16185        }
16186
16187        mKeyedTags.put(key, tag);
16188    }
16189
16190    /**
16191     * Prints information about this view in the log output, with the tag
16192     * {@link #VIEW_LOG_TAG}.
16193     *
16194     * @hide
16195     */
16196    public void debug() {
16197        debug(0);
16198    }
16199
16200    /**
16201     * Prints information about this view in the log output, with the tag
16202     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16203     * indentation defined by the <code>depth</code>.
16204     *
16205     * @param depth the indentation level
16206     *
16207     * @hide
16208     */
16209    protected void debug(int depth) {
16210        String output = debugIndent(depth - 1);
16211
16212        output += "+ " + this;
16213        int id = getId();
16214        if (id != -1) {
16215            output += " (id=" + id + ")";
16216        }
16217        Object tag = getTag();
16218        if (tag != null) {
16219            output += " (tag=" + tag + ")";
16220        }
16221        Log.d(VIEW_LOG_TAG, output);
16222
16223        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16224            output = debugIndent(depth) + " FOCUSED";
16225            Log.d(VIEW_LOG_TAG, output);
16226        }
16227
16228        output = debugIndent(depth);
16229        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16230                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16231                + "} ";
16232        Log.d(VIEW_LOG_TAG, output);
16233
16234        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16235                || mPaddingBottom != 0) {
16236            output = debugIndent(depth);
16237            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16238                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16239            Log.d(VIEW_LOG_TAG, output);
16240        }
16241
16242        output = debugIndent(depth);
16243        output += "mMeasureWidth=" + mMeasuredWidth +
16244                " mMeasureHeight=" + mMeasuredHeight;
16245        Log.d(VIEW_LOG_TAG, output);
16246
16247        output = debugIndent(depth);
16248        if (mLayoutParams == null) {
16249            output += "BAD! no layout params";
16250        } else {
16251            output = mLayoutParams.debug(output);
16252        }
16253        Log.d(VIEW_LOG_TAG, output);
16254
16255        output = debugIndent(depth);
16256        output += "flags={";
16257        output += View.printFlags(mViewFlags);
16258        output += "}";
16259        Log.d(VIEW_LOG_TAG, output);
16260
16261        output = debugIndent(depth);
16262        output += "privateFlags={";
16263        output += View.printPrivateFlags(mPrivateFlags);
16264        output += "}";
16265        Log.d(VIEW_LOG_TAG, output);
16266    }
16267
16268    /**
16269     * Creates a string of whitespaces used for indentation.
16270     *
16271     * @param depth the indentation level
16272     * @return a String containing (depth * 2 + 3) * 2 white spaces
16273     *
16274     * @hide
16275     */
16276    protected static String debugIndent(int depth) {
16277        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16278        for (int i = 0; i < (depth * 2) + 3; i++) {
16279            spaces.append(' ').append(' ');
16280        }
16281        return spaces.toString();
16282    }
16283
16284    /**
16285     * <p>Return the offset of the widget's text baseline from the widget's top
16286     * boundary. If this widget does not support baseline alignment, this
16287     * method returns -1. </p>
16288     *
16289     * @return the offset of the baseline within the widget's bounds or -1
16290     *         if baseline alignment is not supported
16291     */
16292    @ViewDebug.ExportedProperty(category = "layout")
16293    public int getBaseline() {
16294        return -1;
16295    }
16296
16297    /**
16298     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16299     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16300     * a layout pass.
16301     *
16302     * @return whether the view hierarchy is currently undergoing a layout pass
16303     */
16304    public boolean isInLayout() {
16305        ViewRootImpl viewRoot = getViewRootImpl();
16306        return (viewRoot != null && viewRoot.isInLayout());
16307    }
16308
16309    /**
16310     * Call this when something has changed which has invalidated the
16311     * layout of this view. This will schedule a layout pass of the view
16312     * tree. This should not be called while the view hierarchy is currently in a layout
16313     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16314     * end of the current layout pass (and then layout will run again) or after the current
16315     * frame is drawn and the next layout occurs.
16316     *
16317     * <p>Subclasses which override this method should call the superclass method to
16318     * handle possible request-during-layout errors correctly.</p>
16319     */
16320    public void requestLayout() {
16321        if (mMeasureCache != null) mMeasureCache.clear();
16322
16323        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16324            // Only trigger request-during-layout logic if this is the view requesting it,
16325            // not the views in its parent hierarchy
16326            ViewRootImpl viewRoot = getViewRootImpl();
16327            if (viewRoot != null && viewRoot.isInLayout()) {
16328                if (!viewRoot.requestLayoutDuringLayout(this)) {
16329                    return;
16330                }
16331            }
16332            mAttachInfo.mViewRequestingLayout = this;
16333        }
16334
16335        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16336        mPrivateFlags |= PFLAG_INVALIDATED;
16337
16338        if (mParent != null && !mParent.isLayoutRequested()) {
16339            mParent.requestLayout();
16340        }
16341        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16342            mAttachInfo.mViewRequestingLayout = null;
16343        }
16344    }
16345
16346    /**
16347     * Forces this view to be laid out during the next layout pass.
16348     * This method does not call requestLayout() or forceLayout()
16349     * on the parent.
16350     */
16351    public void forceLayout() {
16352        if (mMeasureCache != null) mMeasureCache.clear();
16353
16354        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16355        mPrivateFlags |= PFLAG_INVALIDATED;
16356    }
16357
16358    /**
16359     * <p>
16360     * This is called to find out how big a view should be. The parent
16361     * supplies constraint information in the width and height parameters.
16362     * </p>
16363     *
16364     * <p>
16365     * The actual measurement work of a view is performed in
16366     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16367     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16368     * </p>
16369     *
16370     *
16371     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16372     *        parent
16373     * @param heightMeasureSpec Vertical space requirements as imposed by the
16374     *        parent
16375     *
16376     * @see #onMeasure(int, int)
16377     */
16378    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16379        boolean optical = isLayoutModeOptical(this);
16380        if (optical != isLayoutModeOptical(mParent)) {
16381            Insets insets = getOpticalInsets();
16382            int oWidth  = insets.left + insets.right;
16383            int oHeight = insets.top  + insets.bottom;
16384            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16385            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16386        }
16387
16388        // Suppress sign extension for the low bytes
16389        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16390        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16391
16392        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16393                widthMeasureSpec != mOldWidthMeasureSpec ||
16394                heightMeasureSpec != mOldHeightMeasureSpec) {
16395
16396            // first clears the measured dimension flag
16397            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16398
16399            resolveRtlPropertiesIfNeeded();
16400
16401            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16402                    mMeasureCache.indexOfKey(key);
16403            if (cacheIndex < 0) {
16404                // measure ourselves, this should set the measured dimension flag back
16405                onMeasure(widthMeasureSpec, heightMeasureSpec);
16406                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16407            } else {
16408                long value = mMeasureCache.valueAt(cacheIndex);
16409                // Casting a long to int drops the high 32 bits, no mask needed
16410                setMeasuredDimension((int) (value >> 32), (int) value);
16411                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16412            }
16413
16414            // flag not set, setMeasuredDimension() was not invoked, we raise
16415            // an exception to warn the developer
16416            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16417                throw new IllegalStateException("onMeasure() did not set the"
16418                        + " measured dimension by calling"
16419                        + " setMeasuredDimension()");
16420            }
16421
16422            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16423        }
16424
16425        mOldWidthMeasureSpec = widthMeasureSpec;
16426        mOldHeightMeasureSpec = heightMeasureSpec;
16427
16428        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16429                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16430    }
16431
16432    /**
16433     * <p>
16434     * Measure the view and its content to determine the measured width and the
16435     * measured height. This method is invoked by {@link #measure(int, int)} and
16436     * should be overriden by subclasses to provide accurate and efficient
16437     * measurement of their contents.
16438     * </p>
16439     *
16440     * <p>
16441     * <strong>CONTRACT:</strong> When overriding this method, you
16442     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16443     * measured width and height of this view. Failure to do so will trigger an
16444     * <code>IllegalStateException</code>, thrown by
16445     * {@link #measure(int, int)}. Calling the superclass'
16446     * {@link #onMeasure(int, int)} is a valid use.
16447     * </p>
16448     *
16449     * <p>
16450     * The base class implementation of measure defaults to the background size,
16451     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16452     * override {@link #onMeasure(int, int)} to provide better measurements of
16453     * their content.
16454     * </p>
16455     *
16456     * <p>
16457     * If this method is overridden, it is the subclass's responsibility to make
16458     * sure the measured height and width are at least the view's minimum height
16459     * and width ({@link #getSuggestedMinimumHeight()} and
16460     * {@link #getSuggestedMinimumWidth()}).
16461     * </p>
16462     *
16463     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16464     *                         The requirements are encoded with
16465     *                         {@link android.view.View.MeasureSpec}.
16466     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16467     *                         The requirements are encoded with
16468     *                         {@link android.view.View.MeasureSpec}.
16469     *
16470     * @see #getMeasuredWidth()
16471     * @see #getMeasuredHeight()
16472     * @see #setMeasuredDimension(int, int)
16473     * @see #getSuggestedMinimumHeight()
16474     * @see #getSuggestedMinimumWidth()
16475     * @see android.view.View.MeasureSpec#getMode(int)
16476     * @see android.view.View.MeasureSpec#getSize(int)
16477     */
16478    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16479        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16480                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16481    }
16482
16483    /**
16484     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16485     * measured width and measured height. Failing to do so will trigger an
16486     * exception at measurement time.</p>
16487     *
16488     * @param measuredWidth The measured width of this view.  May be a complex
16489     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16490     * {@link #MEASURED_STATE_TOO_SMALL}.
16491     * @param measuredHeight The measured height of this view.  May be a complex
16492     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16493     * {@link #MEASURED_STATE_TOO_SMALL}.
16494     */
16495    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16496        boolean optical = isLayoutModeOptical(this);
16497        if (optical != isLayoutModeOptical(mParent)) {
16498            Insets insets = getOpticalInsets();
16499            int opticalWidth  = insets.left + insets.right;
16500            int opticalHeight = insets.top  + insets.bottom;
16501
16502            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16503            measuredHeight += optical ? opticalHeight : -opticalHeight;
16504        }
16505        mMeasuredWidth = measuredWidth;
16506        mMeasuredHeight = measuredHeight;
16507
16508        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16509    }
16510
16511    /**
16512     * Merge two states as returned by {@link #getMeasuredState()}.
16513     * @param curState The current state as returned from a view or the result
16514     * of combining multiple views.
16515     * @param newState The new view state to combine.
16516     * @return Returns a new integer reflecting the combination of the two
16517     * states.
16518     */
16519    public static int combineMeasuredStates(int curState, int newState) {
16520        return curState | newState;
16521    }
16522
16523    /**
16524     * Version of {@link #resolveSizeAndState(int, int, int)}
16525     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16526     */
16527    public static int resolveSize(int size, int measureSpec) {
16528        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16529    }
16530
16531    /**
16532     * Utility to reconcile a desired size and state, with constraints imposed
16533     * by a MeasureSpec.  Will take the desired size, unless a different size
16534     * is imposed by the constraints.  The returned value is a compound integer,
16535     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16536     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16537     * size is smaller than the size the view wants to be.
16538     *
16539     * @param size How big the view wants to be
16540     * @param measureSpec Constraints imposed by the parent
16541     * @return Size information bit mask as defined by
16542     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16543     */
16544    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16545        int result = size;
16546        int specMode = MeasureSpec.getMode(measureSpec);
16547        int specSize =  MeasureSpec.getSize(measureSpec);
16548        switch (specMode) {
16549        case MeasureSpec.UNSPECIFIED:
16550            result = size;
16551            break;
16552        case MeasureSpec.AT_MOST:
16553            if (specSize < size) {
16554                result = specSize | MEASURED_STATE_TOO_SMALL;
16555            } else {
16556                result = size;
16557            }
16558            break;
16559        case MeasureSpec.EXACTLY:
16560            result = specSize;
16561            break;
16562        }
16563        return result | (childMeasuredState&MEASURED_STATE_MASK);
16564    }
16565
16566    /**
16567     * Utility to return a default size. Uses the supplied size if the
16568     * MeasureSpec imposed no constraints. Will get larger if allowed
16569     * by the MeasureSpec.
16570     *
16571     * @param size Default size for this view
16572     * @param measureSpec Constraints imposed by the parent
16573     * @return The size this view should be.
16574     */
16575    public static int getDefaultSize(int size, int measureSpec) {
16576        int result = size;
16577        int specMode = MeasureSpec.getMode(measureSpec);
16578        int specSize = MeasureSpec.getSize(measureSpec);
16579
16580        switch (specMode) {
16581        case MeasureSpec.UNSPECIFIED:
16582            result = size;
16583            break;
16584        case MeasureSpec.AT_MOST:
16585        case MeasureSpec.EXACTLY:
16586            result = specSize;
16587            break;
16588        }
16589        return result;
16590    }
16591
16592    /**
16593     * Returns the suggested minimum height that the view should use. This
16594     * returns the maximum of the view's minimum height
16595     * and the background's minimum height
16596     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16597     * <p>
16598     * When being used in {@link #onMeasure(int, int)}, the caller should still
16599     * ensure the returned height is within the requirements of the parent.
16600     *
16601     * @return The suggested minimum height of the view.
16602     */
16603    protected int getSuggestedMinimumHeight() {
16604        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16605
16606    }
16607
16608    /**
16609     * Returns the suggested minimum width that the view should use. This
16610     * returns the maximum of the view's minimum width)
16611     * and the background's minimum width
16612     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16613     * <p>
16614     * When being used in {@link #onMeasure(int, int)}, the caller should still
16615     * ensure the returned width is within the requirements of the parent.
16616     *
16617     * @return The suggested minimum width of the view.
16618     */
16619    protected int getSuggestedMinimumWidth() {
16620        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16621    }
16622
16623    /**
16624     * Returns the minimum height of the view.
16625     *
16626     * @return the minimum height the view will try to be.
16627     *
16628     * @see #setMinimumHeight(int)
16629     *
16630     * @attr ref android.R.styleable#View_minHeight
16631     */
16632    public int getMinimumHeight() {
16633        return mMinHeight;
16634    }
16635
16636    /**
16637     * Sets the minimum height of the view. It is not guaranteed the view will
16638     * be able to achieve this minimum height (for example, if its parent layout
16639     * constrains it with less available height).
16640     *
16641     * @param minHeight The minimum height the view will try to be.
16642     *
16643     * @see #getMinimumHeight()
16644     *
16645     * @attr ref android.R.styleable#View_minHeight
16646     */
16647    public void setMinimumHeight(int minHeight) {
16648        mMinHeight = minHeight;
16649        requestLayout();
16650    }
16651
16652    /**
16653     * Returns the minimum width of the view.
16654     *
16655     * @return the minimum width the view will try to be.
16656     *
16657     * @see #setMinimumWidth(int)
16658     *
16659     * @attr ref android.R.styleable#View_minWidth
16660     */
16661    public int getMinimumWidth() {
16662        return mMinWidth;
16663    }
16664
16665    /**
16666     * Sets the minimum width of the view. It is not guaranteed the view will
16667     * be able to achieve this minimum width (for example, if its parent layout
16668     * constrains it with less available width).
16669     *
16670     * @param minWidth The minimum width the view will try to be.
16671     *
16672     * @see #getMinimumWidth()
16673     *
16674     * @attr ref android.R.styleable#View_minWidth
16675     */
16676    public void setMinimumWidth(int minWidth) {
16677        mMinWidth = minWidth;
16678        requestLayout();
16679
16680    }
16681
16682    /**
16683     * Get the animation currently associated with this view.
16684     *
16685     * @return The animation that is currently playing or
16686     *         scheduled to play for this view.
16687     */
16688    public Animation getAnimation() {
16689        return mCurrentAnimation;
16690    }
16691
16692    /**
16693     * Start the specified animation now.
16694     *
16695     * @param animation the animation to start now
16696     */
16697    public void startAnimation(Animation animation) {
16698        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16699        setAnimation(animation);
16700        invalidateParentCaches();
16701        invalidate(true);
16702    }
16703
16704    /**
16705     * Cancels any animations for this view.
16706     */
16707    public void clearAnimation() {
16708        if (mCurrentAnimation != null) {
16709            mCurrentAnimation.detach();
16710        }
16711        mCurrentAnimation = null;
16712        invalidateParentIfNeeded();
16713    }
16714
16715    /**
16716     * Sets the next animation to play for this view.
16717     * If you want the animation to play immediately, use
16718     * {@link #startAnimation(android.view.animation.Animation)} instead.
16719     * This method provides allows fine-grained
16720     * control over the start time and invalidation, but you
16721     * must make sure that 1) the animation has a start time set, and
16722     * 2) the view's parent (which controls animations on its children)
16723     * will be invalidated when the animation is supposed to
16724     * start.
16725     *
16726     * @param animation The next animation, or null.
16727     */
16728    public void setAnimation(Animation animation) {
16729        mCurrentAnimation = animation;
16730
16731        if (animation != null) {
16732            // If the screen is off assume the animation start time is now instead of
16733            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16734            // would cause the animation to start when the screen turns back on
16735            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16736                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16737                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16738            }
16739            animation.reset();
16740        }
16741    }
16742
16743    /**
16744     * Invoked by a parent ViewGroup to notify the start of the animation
16745     * currently associated with this view. If you override this method,
16746     * always call super.onAnimationStart();
16747     *
16748     * @see #setAnimation(android.view.animation.Animation)
16749     * @see #getAnimation()
16750     */
16751    protected void onAnimationStart() {
16752        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16753    }
16754
16755    /**
16756     * Invoked by a parent ViewGroup to notify the end of the animation
16757     * currently associated with this view. If you override this method,
16758     * always call super.onAnimationEnd();
16759     *
16760     * @see #setAnimation(android.view.animation.Animation)
16761     * @see #getAnimation()
16762     */
16763    protected void onAnimationEnd() {
16764        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16765    }
16766
16767    /**
16768     * Invoked if there is a Transform that involves alpha. Subclass that can
16769     * draw themselves with the specified alpha should return true, and then
16770     * respect that alpha when their onDraw() is called. If this returns false
16771     * then the view may be redirected to draw into an offscreen buffer to
16772     * fulfill the request, which will look fine, but may be slower than if the
16773     * subclass handles it internally. The default implementation returns false.
16774     *
16775     * @param alpha The alpha (0..255) to apply to the view's drawing
16776     * @return true if the view can draw with the specified alpha.
16777     */
16778    protected boolean onSetAlpha(int alpha) {
16779        return false;
16780    }
16781
16782    /**
16783     * This is used by the RootView to perform an optimization when
16784     * the view hierarchy contains one or several SurfaceView.
16785     * SurfaceView is always considered transparent, but its children are not,
16786     * therefore all View objects remove themselves from the global transparent
16787     * region (passed as a parameter to this function).
16788     *
16789     * @param region The transparent region for this ViewAncestor (window).
16790     *
16791     * @return Returns true if the effective visibility of the view at this
16792     * point is opaque, regardless of the transparent region; returns false
16793     * if it is possible for underlying windows to be seen behind the view.
16794     *
16795     * {@hide}
16796     */
16797    public boolean gatherTransparentRegion(Region region) {
16798        final AttachInfo attachInfo = mAttachInfo;
16799        if (region != null && attachInfo != null) {
16800            final int pflags = mPrivateFlags;
16801            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16802                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16803                // remove it from the transparent region.
16804                final int[] location = attachInfo.mTransparentLocation;
16805                getLocationInWindow(location);
16806                region.op(location[0], location[1], location[0] + mRight - mLeft,
16807                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16808            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16809                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16810                // exists, so we remove the background drawable's non-transparent
16811                // parts from this transparent region.
16812                applyDrawableToTransparentRegion(mBackground, region);
16813            }
16814        }
16815        return true;
16816    }
16817
16818    /**
16819     * Play a sound effect for this view.
16820     *
16821     * <p>The framework will play sound effects for some built in actions, such as
16822     * clicking, but you may wish to play these effects in your widget,
16823     * for instance, for internal navigation.
16824     *
16825     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16826     * {@link #isSoundEffectsEnabled()} is true.
16827     *
16828     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16829     */
16830    public void playSoundEffect(int soundConstant) {
16831        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16832            return;
16833        }
16834        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16835    }
16836
16837    /**
16838     * BZZZTT!!1!
16839     *
16840     * <p>Provide haptic feedback to the user for this view.
16841     *
16842     * <p>The framework will provide haptic feedback for some built in actions,
16843     * such as long presses, but you may wish to provide feedback for your
16844     * own widget.
16845     *
16846     * <p>The feedback will only be performed if
16847     * {@link #isHapticFeedbackEnabled()} is true.
16848     *
16849     * @param feedbackConstant One of the constants defined in
16850     * {@link HapticFeedbackConstants}
16851     */
16852    public boolean performHapticFeedback(int feedbackConstant) {
16853        return performHapticFeedback(feedbackConstant, 0);
16854    }
16855
16856    /**
16857     * BZZZTT!!1!
16858     *
16859     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16860     *
16861     * @param feedbackConstant One of the constants defined in
16862     * {@link HapticFeedbackConstants}
16863     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16864     */
16865    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16866        if (mAttachInfo == null) {
16867            return false;
16868        }
16869        //noinspection SimplifiableIfStatement
16870        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16871                && !isHapticFeedbackEnabled()) {
16872            return false;
16873        }
16874        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16875                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16876    }
16877
16878    /**
16879     * Request that the visibility of the status bar or other screen/window
16880     * decorations be changed.
16881     *
16882     * <p>This method is used to put the over device UI into temporary modes
16883     * where the user's attention is focused more on the application content,
16884     * by dimming or hiding surrounding system affordances.  This is typically
16885     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16886     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16887     * to be placed behind the action bar (and with these flags other system
16888     * affordances) so that smooth transitions between hiding and showing them
16889     * can be done.
16890     *
16891     * <p>Two representative examples of the use of system UI visibility is
16892     * implementing a content browsing application (like a magazine reader)
16893     * and a video playing application.
16894     *
16895     * <p>The first code shows a typical implementation of a View in a content
16896     * browsing application.  In this implementation, the application goes
16897     * into a content-oriented mode by hiding the status bar and action bar,
16898     * and putting the navigation elements into lights out mode.  The user can
16899     * then interact with content while in this mode.  Such an application should
16900     * provide an easy way for the user to toggle out of the mode (such as to
16901     * check information in the status bar or access notifications).  In the
16902     * implementation here, this is done simply by tapping on the content.
16903     *
16904     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16905     *      content}
16906     *
16907     * <p>This second code sample shows a typical implementation of a View
16908     * in a video playing application.  In this situation, while the video is
16909     * playing the application would like to go into a complete full-screen mode,
16910     * to use as much of the display as possible for the video.  When in this state
16911     * the user can not interact with the application; the system intercepts
16912     * touching on the screen to pop the UI out of full screen mode.  See
16913     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16914     *
16915     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16916     *      content}
16917     *
16918     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16919     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16920     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16921     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
16922     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16923     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16924     */
16925    public void setSystemUiVisibility(int visibility) {
16926        if (visibility != mSystemUiVisibility) {
16927            mSystemUiVisibility = visibility;
16928            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16929                mParent.recomputeViewAttributes(this);
16930            }
16931        }
16932    }
16933
16934    /**
16935     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
16936     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16937     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16938     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16939     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
16940     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
16941     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
16942     */
16943    public int getSystemUiVisibility() {
16944        return mSystemUiVisibility;
16945    }
16946
16947    /**
16948     * Returns the current system UI visibility that is currently set for
16949     * the entire window.  This is the combination of the
16950     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16951     * views in the window.
16952     */
16953    public int getWindowSystemUiVisibility() {
16954        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16955    }
16956
16957    /**
16958     * Override to find out when the window's requested system UI visibility
16959     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16960     * This is different from the callbacks received through
16961     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16962     * in that this is only telling you about the local request of the window,
16963     * not the actual values applied by the system.
16964     */
16965    public void onWindowSystemUiVisibilityChanged(int visible) {
16966    }
16967
16968    /**
16969     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16970     * the view hierarchy.
16971     */
16972    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16973        onWindowSystemUiVisibilityChanged(visible);
16974    }
16975
16976    /**
16977     * Set a listener to receive callbacks when the visibility of the system bar changes.
16978     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16979     */
16980    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16981        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16982        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16983            mParent.recomputeViewAttributes(this);
16984        }
16985    }
16986
16987    /**
16988     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16989     * the view hierarchy.
16990     */
16991    public void dispatchSystemUiVisibilityChanged(int visibility) {
16992        ListenerInfo li = mListenerInfo;
16993        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16994            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16995                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16996        }
16997    }
16998
16999    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17000        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17001        if (val != mSystemUiVisibility) {
17002            setSystemUiVisibility(val);
17003            return true;
17004        }
17005        return false;
17006    }
17007
17008    /** @hide */
17009    public void setDisabledSystemUiVisibility(int flags) {
17010        if (mAttachInfo != null) {
17011            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17012                mAttachInfo.mDisabledSystemUiVisibility = flags;
17013                if (mParent != null) {
17014                    mParent.recomputeViewAttributes(this);
17015                }
17016            }
17017        }
17018    }
17019
17020    /**
17021     * Creates an image that the system displays during the drag and drop
17022     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17023     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17024     * appearance as the given View. The default also positions the center of the drag shadow
17025     * directly under the touch point. If no View is provided (the constructor with no parameters
17026     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17027     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17028     * default is an invisible drag shadow.
17029     * <p>
17030     * You are not required to use the View you provide to the constructor as the basis of the
17031     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17032     * anything you want as the drag shadow.
17033     * </p>
17034     * <p>
17035     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17036     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17037     *  size and position of the drag shadow. It uses this data to construct a
17038     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17039     *  so that your application can draw the shadow image in the Canvas.
17040     * </p>
17041     *
17042     * <div class="special reference">
17043     * <h3>Developer Guides</h3>
17044     * <p>For a guide to implementing drag and drop features, read the
17045     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17046     * </div>
17047     */
17048    public static class DragShadowBuilder {
17049        private final WeakReference<View> mView;
17050
17051        /**
17052         * Constructs a shadow image builder based on a View. By default, the resulting drag
17053         * shadow will have the same appearance and dimensions as the View, with the touch point
17054         * over the center of the View.
17055         * @param view A View. Any View in scope can be used.
17056         */
17057        public DragShadowBuilder(View view) {
17058            mView = new WeakReference<View>(view);
17059        }
17060
17061        /**
17062         * Construct a shadow builder object with no associated View.  This
17063         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17064         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17065         * to supply the drag shadow's dimensions and appearance without
17066         * reference to any View object. If they are not overridden, then the result is an
17067         * invisible drag shadow.
17068         */
17069        public DragShadowBuilder() {
17070            mView = new WeakReference<View>(null);
17071        }
17072
17073        /**
17074         * Returns the View object that had been passed to the
17075         * {@link #View.DragShadowBuilder(View)}
17076         * constructor.  If that View parameter was {@code null} or if the
17077         * {@link #View.DragShadowBuilder()}
17078         * constructor was used to instantiate the builder object, this method will return
17079         * null.
17080         *
17081         * @return The View object associate with this builder object.
17082         */
17083        @SuppressWarnings({"JavadocReference"})
17084        final public View getView() {
17085            return mView.get();
17086        }
17087
17088        /**
17089         * Provides the metrics for the shadow image. These include the dimensions of
17090         * the shadow image, and the point within that shadow that should
17091         * be centered under the touch location while dragging.
17092         * <p>
17093         * The default implementation sets the dimensions of the shadow to be the
17094         * same as the dimensions of the View itself and centers the shadow under
17095         * the touch point.
17096         * </p>
17097         *
17098         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17099         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17100         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17101         * image.
17102         *
17103         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17104         * shadow image that should be underneath the touch point during the drag and drop
17105         * operation. Your application must set {@link android.graphics.Point#x} to the
17106         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17107         */
17108        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17109            final View view = mView.get();
17110            if (view != null) {
17111                shadowSize.set(view.getWidth(), view.getHeight());
17112                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17113            } else {
17114                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17115            }
17116        }
17117
17118        /**
17119         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17120         * based on the dimensions it received from the
17121         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17122         *
17123         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17124         */
17125        public void onDrawShadow(Canvas canvas) {
17126            final View view = mView.get();
17127            if (view != null) {
17128                view.draw(canvas);
17129            } else {
17130                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17131            }
17132        }
17133    }
17134
17135    /**
17136     * Starts a drag and drop operation. When your application calls this method, it passes a
17137     * {@link android.view.View.DragShadowBuilder} object to the system. The
17138     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17139     * to get metrics for the drag shadow, and then calls the object's
17140     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17141     * <p>
17142     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17143     *  drag events to all the View objects in your application that are currently visible. It does
17144     *  this either by calling the View object's drag listener (an implementation of
17145     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17146     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17147     *  Both are passed a {@link android.view.DragEvent} object that has a
17148     *  {@link android.view.DragEvent#getAction()} value of
17149     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17150     * </p>
17151     * <p>
17152     * Your application can invoke startDrag() on any attached View object. The View object does not
17153     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17154     * be related to the View the user selected for dragging.
17155     * </p>
17156     * @param data A {@link android.content.ClipData} object pointing to the data to be
17157     * transferred by the drag and drop operation.
17158     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17159     * drag shadow.
17160     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17161     * drop operation. This Object is put into every DragEvent object sent by the system during the
17162     * current drag.
17163     * <p>
17164     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17165     * to the target Views. For example, it can contain flags that differentiate between a
17166     * a copy operation and a move operation.
17167     * </p>
17168     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17169     * so the parameter should be set to 0.
17170     * @return {@code true} if the method completes successfully, or
17171     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17172     * do a drag, and so no drag operation is in progress.
17173     */
17174    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17175            Object myLocalState, int flags) {
17176        if (ViewDebug.DEBUG_DRAG) {
17177            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17178        }
17179        boolean okay = false;
17180
17181        Point shadowSize = new Point();
17182        Point shadowTouchPoint = new Point();
17183        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17184
17185        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17186                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17187            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17188        }
17189
17190        if (ViewDebug.DEBUG_DRAG) {
17191            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17192                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17193        }
17194        Surface surface = new Surface();
17195        try {
17196            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17197                    flags, shadowSize.x, shadowSize.y, surface);
17198            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17199                    + " surface=" + surface);
17200            if (token != null) {
17201                Canvas canvas = surface.lockCanvas(null);
17202                try {
17203                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17204                    shadowBuilder.onDrawShadow(canvas);
17205                } finally {
17206                    surface.unlockCanvasAndPost(canvas);
17207                }
17208
17209                final ViewRootImpl root = getViewRootImpl();
17210
17211                // Cache the local state object for delivery with DragEvents
17212                root.setLocalDragState(myLocalState);
17213
17214                // repurpose 'shadowSize' for the last touch point
17215                root.getLastTouchPoint(shadowSize);
17216
17217                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17218                        shadowSize.x, shadowSize.y,
17219                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17220                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17221
17222                // Off and running!  Release our local surface instance; the drag
17223                // shadow surface is now managed by the system process.
17224                surface.release();
17225            }
17226        } catch (Exception e) {
17227            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17228            surface.destroy();
17229        }
17230
17231        return okay;
17232    }
17233
17234    /**
17235     * Handles drag events sent by the system following a call to
17236     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17237     *<p>
17238     * When the system calls this method, it passes a
17239     * {@link android.view.DragEvent} object. A call to
17240     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17241     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17242     * operation.
17243     * @param event The {@link android.view.DragEvent} sent by the system.
17244     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17245     * in DragEvent, indicating the type of drag event represented by this object.
17246     * @return {@code true} if the method was successful, otherwise {@code false}.
17247     * <p>
17248     *  The method should return {@code true} in response to an action type of
17249     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17250     *  operation.
17251     * </p>
17252     * <p>
17253     *  The method should also return {@code true} in response to an action type of
17254     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17255     *  {@code false} if it didn't.
17256     * </p>
17257     */
17258    public boolean onDragEvent(DragEvent event) {
17259        return false;
17260    }
17261
17262    /**
17263     * Detects if this View is enabled and has a drag event listener.
17264     * If both are true, then it calls the drag event listener with the
17265     * {@link android.view.DragEvent} it received. If the drag event listener returns
17266     * {@code true}, then dispatchDragEvent() returns {@code true}.
17267     * <p>
17268     * For all other cases, the method calls the
17269     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17270     * method and returns its result.
17271     * </p>
17272     * <p>
17273     * This ensures that a drag event is always consumed, even if the View does not have a drag
17274     * event listener. However, if the View has a listener and the listener returns true, then
17275     * onDragEvent() is not called.
17276     * </p>
17277     */
17278    public boolean dispatchDragEvent(DragEvent event) {
17279        ListenerInfo li = mListenerInfo;
17280        //noinspection SimplifiableIfStatement
17281        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17282                && li.mOnDragListener.onDrag(this, event)) {
17283            return true;
17284        }
17285        return onDragEvent(event);
17286    }
17287
17288    boolean canAcceptDrag() {
17289        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17290    }
17291
17292    /**
17293     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17294     * it is ever exposed at all.
17295     * @hide
17296     */
17297    public void onCloseSystemDialogs(String reason) {
17298    }
17299
17300    /**
17301     * Given a Drawable whose bounds have been set to draw into this view,
17302     * update a Region being computed for
17303     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17304     * that any non-transparent parts of the Drawable are removed from the
17305     * given transparent region.
17306     *
17307     * @param dr The Drawable whose transparency is to be applied to the region.
17308     * @param region A Region holding the current transparency information,
17309     * where any parts of the region that are set are considered to be
17310     * transparent.  On return, this region will be modified to have the
17311     * transparency information reduced by the corresponding parts of the
17312     * Drawable that are not transparent.
17313     * {@hide}
17314     */
17315    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17316        if (DBG) {
17317            Log.i("View", "Getting transparent region for: " + this);
17318        }
17319        final Region r = dr.getTransparentRegion();
17320        final Rect db = dr.getBounds();
17321        final AttachInfo attachInfo = mAttachInfo;
17322        if (r != null && attachInfo != null) {
17323            final int w = getRight()-getLeft();
17324            final int h = getBottom()-getTop();
17325            if (db.left > 0) {
17326                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17327                r.op(0, 0, db.left, h, Region.Op.UNION);
17328            }
17329            if (db.right < w) {
17330                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17331                r.op(db.right, 0, w, h, Region.Op.UNION);
17332            }
17333            if (db.top > 0) {
17334                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17335                r.op(0, 0, w, db.top, Region.Op.UNION);
17336            }
17337            if (db.bottom < h) {
17338                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17339                r.op(0, db.bottom, w, h, Region.Op.UNION);
17340            }
17341            final int[] location = attachInfo.mTransparentLocation;
17342            getLocationInWindow(location);
17343            r.translate(location[0], location[1]);
17344            region.op(r, Region.Op.INTERSECT);
17345        } else {
17346            region.op(db, Region.Op.DIFFERENCE);
17347        }
17348    }
17349
17350    private void checkForLongClick(int delayOffset) {
17351        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17352            mHasPerformedLongPress = false;
17353
17354            if (mPendingCheckForLongPress == null) {
17355                mPendingCheckForLongPress = new CheckForLongPress();
17356            }
17357            mPendingCheckForLongPress.rememberWindowAttachCount();
17358            postDelayed(mPendingCheckForLongPress,
17359                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17360        }
17361    }
17362
17363    /**
17364     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17365     * LayoutInflater} class, which provides a full range of options for view inflation.
17366     *
17367     * @param context The Context object for your activity or application.
17368     * @param resource The resource ID to inflate
17369     * @param root A view group that will be the parent.  Used to properly inflate the
17370     * layout_* parameters.
17371     * @see LayoutInflater
17372     */
17373    public static View inflate(Context context, int resource, ViewGroup root) {
17374        LayoutInflater factory = LayoutInflater.from(context);
17375        return factory.inflate(resource, root);
17376    }
17377
17378    /**
17379     * Scroll the view with standard behavior for scrolling beyond the normal
17380     * content boundaries. Views that call this method should override
17381     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17382     * results of an over-scroll operation.
17383     *
17384     * Views can use this method to handle any touch or fling-based scrolling.
17385     *
17386     * @param deltaX Change in X in pixels
17387     * @param deltaY Change in Y in pixels
17388     * @param scrollX Current X scroll value in pixels before applying deltaX
17389     * @param scrollY Current Y scroll value in pixels before applying deltaY
17390     * @param scrollRangeX Maximum content scroll range along the X axis
17391     * @param scrollRangeY Maximum content scroll range along the Y axis
17392     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17393     *          along the X axis.
17394     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17395     *          along the Y axis.
17396     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17397     * @return true if scrolling was clamped to an over-scroll boundary along either
17398     *          axis, false otherwise.
17399     */
17400    @SuppressWarnings({"UnusedParameters"})
17401    protected boolean overScrollBy(int deltaX, int deltaY,
17402            int scrollX, int scrollY,
17403            int scrollRangeX, int scrollRangeY,
17404            int maxOverScrollX, int maxOverScrollY,
17405            boolean isTouchEvent) {
17406        final int overScrollMode = mOverScrollMode;
17407        final boolean canScrollHorizontal =
17408                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17409        final boolean canScrollVertical =
17410                computeVerticalScrollRange() > computeVerticalScrollExtent();
17411        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17412                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17413        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17414                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17415
17416        int newScrollX = scrollX + deltaX;
17417        if (!overScrollHorizontal) {
17418            maxOverScrollX = 0;
17419        }
17420
17421        int newScrollY = scrollY + deltaY;
17422        if (!overScrollVertical) {
17423            maxOverScrollY = 0;
17424        }
17425
17426        // Clamp values if at the limits and record
17427        final int left = -maxOverScrollX;
17428        final int right = maxOverScrollX + scrollRangeX;
17429        final int top = -maxOverScrollY;
17430        final int bottom = maxOverScrollY + scrollRangeY;
17431
17432        boolean clampedX = false;
17433        if (newScrollX > right) {
17434            newScrollX = right;
17435            clampedX = true;
17436        } else if (newScrollX < left) {
17437            newScrollX = left;
17438            clampedX = true;
17439        }
17440
17441        boolean clampedY = false;
17442        if (newScrollY > bottom) {
17443            newScrollY = bottom;
17444            clampedY = true;
17445        } else if (newScrollY < top) {
17446            newScrollY = top;
17447            clampedY = true;
17448        }
17449
17450        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17451
17452        return clampedX || clampedY;
17453    }
17454
17455    /**
17456     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17457     * respond to the results of an over-scroll operation.
17458     *
17459     * @param scrollX New X scroll value in pixels
17460     * @param scrollY New Y scroll value in pixels
17461     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17462     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17463     */
17464    protected void onOverScrolled(int scrollX, int scrollY,
17465            boolean clampedX, boolean clampedY) {
17466        // Intentionally empty.
17467    }
17468
17469    /**
17470     * Returns the over-scroll mode for this view. The result will be
17471     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17472     * (allow over-scrolling only if the view content is larger than the container),
17473     * or {@link #OVER_SCROLL_NEVER}.
17474     *
17475     * @return This view's over-scroll mode.
17476     */
17477    public int getOverScrollMode() {
17478        return mOverScrollMode;
17479    }
17480
17481    /**
17482     * Set the over-scroll mode for this view. Valid over-scroll modes are
17483     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17484     * (allow over-scrolling only if the view content is larger than the container),
17485     * or {@link #OVER_SCROLL_NEVER}.
17486     *
17487     * Setting the over-scroll mode of a view will have an effect only if the
17488     * view is capable of scrolling.
17489     *
17490     * @param overScrollMode The new over-scroll mode for this view.
17491     */
17492    public void setOverScrollMode(int overScrollMode) {
17493        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17494                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17495                overScrollMode != OVER_SCROLL_NEVER) {
17496            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17497        }
17498        mOverScrollMode = overScrollMode;
17499    }
17500
17501    /**
17502     * Gets a scale factor that determines the distance the view should scroll
17503     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17504     * @return The vertical scroll scale factor.
17505     * @hide
17506     */
17507    protected float getVerticalScrollFactor() {
17508        if (mVerticalScrollFactor == 0) {
17509            TypedValue outValue = new TypedValue();
17510            if (!mContext.getTheme().resolveAttribute(
17511                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17512                throw new IllegalStateException(
17513                        "Expected theme to define listPreferredItemHeight.");
17514            }
17515            mVerticalScrollFactor = outValue.getDimension(
17516                    mContext.getResources().getDisplayMetrics());
17517        }
17518        return mVerticalScrollFactor;
17519    }
17520
17521    /**
17522     * Gets a scale factor that determines the distance the view should scroll
17523     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17524     * @return The horizontal scroll scale factor.
17525     * @hide
17526     */
17527    protected float getHorizontalScrollFactor() {
17528        // TODO: Should use something else.
17529        return getVerticalScrollFactor();
17530    }
17531
17532    /**
17533     * Return the value specifying the text direction or policy that was set with
17534     * {@link #setTextDirection(int)}.
17535     *
17536     * @return the defined text direction. It can be one of:
17537     *
17538     * {@link #TEXT_DIRECTION_INHERIT},
17539     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17540     * {@link #TEXT_DIRECTION_ANY_RTL},
17541     * {@link #TEXT_DIRECTION_LTR},
17542     * {@link #TEXT_DIRECTION_RTL},
17543     * {@link #TEXT_DIRECTION_LOCALE}
17544     *
17545     * @attr ref android.R.styleable#View_textDirection
17546     *
17547     * @hide
17548     */
17549    @ViewDebug.ExportedProperty(category = "text", mapping = {
17550            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17551            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17552            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17553            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17554            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17555            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17556    })
17557    public int getRawTextDirection() {
17558        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17559    }
17560
17561    /**
17562     * Set the text direction.
17563     *
17564     * @param textDirection the direction to set. Should be one of:
17565     *
17566     * {@link #TEXT_DIRECTION_INHERIT},
17567     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17568     * {@link #TEXT_DIRECTION_ANY_RTL},
17569     * {@link #TEXT_DIRECTION_LTR},
17570     * {@link #TEXT_DIRECTION_RTL},
17571     * {@link #TEXT_DIRECTION_LOCALE}
17572     *
17573     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17574     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17575     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17576     *
17577     * @attr ref android.R.styleable#View_textDirection
17578     */
17579    public void setTextDirection(int textDirection) {
17580        if (getRawTextDirection() != textDirection) {
17581            // Reset the current text direction and the resolved one
17582            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17583            resetResolvedTextDirection();
17584            // Set the new text direction
17585            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17586            // Do resolution
17587            resolveTextDirection();
17588            // Notify change
17589            onRtlPropertiesChanged(getLayoutDirection());
17590            // Refresh
17591            requestLayout();
17592            invalidate(true);
17593        }
17594    }
17595
17596    /**
17597     * Return the resolved text direction.
17598     *
17599     * @return the resolved text direction. Returns one of:
17600     *
17601     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17602     * {@link #TEXT_DIRECTION_ANY_RTL},
17603     * {@link #TEXT_DIRECTION_LTR},
17604     * {@link #TEXT_DIRECTION_RTL},
17605     * {@link #TEXT_DIRECTION_LOCALE}
17606     *
17607     * @attr ref android.R.styleable#View_textDirection
17608     */
17609    @ViewDebug.ExportedProperty(category = "text", mapping = {
17610            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17611            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17612            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17613            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17614            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17615            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17616    })
17617    public int getTextDirection() {
17618        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17619    }
17620
17621    /**
17622     * Resolve the text direction.
17623     *
17624     * @return true if resolution has been done, false otherwise.
17625     *
17626     * @hide
17627     */
17628    public boolean resolveTextDirection() {
17629        // Reset any previous text direction resolution
17630        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17631
17632        if (hasRtlSupport()) {
17633            // Set resolved text direction flag depending on text direction flag
17634            final int textDirection = getRawTextDirection();
17635            switch(textDirection) {
17636                case TEXT_DIRECTION_INHERIT:
17637                    if (!canResolveTextDirection()) {
17638                        // We cannot do the resolution if there is no parent, so use the default one
17639                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17640                        // Resolution will need to happen again later
17641                        return false;
17642                    }
17643
17644                    // Parent has not yet resolved, so we still return the default
17645                    try {
17646                        if (!mParent.isTextDirectionResolved()) {
17647                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17648                            // Resolution will need to happen again later
17649                            return false;
17650                        }
17651                    } catch (AbstractMethodError e) {
17652                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17653                                " does not fully implement ViewParent", e);
17654                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17655                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17656                        return true;
17657                    }
17658
17659                    // Set current resolved direction to the same value as the parent's one
17660                    int parentResolvedDirection;
17661                    try {
17662                        parentResolvedDirection = mParent.getTextDirection();
17663                    } catch (AbstractMethodError e) {
17664                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17665                                " does not fully implement ViewParent", e);
17666                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17667                    }
17668                    switch (parentResolvedDirection) {
17669                        case TEXT_DIRECTION_FIRST_STRONG:
17670                        case TEXT_DIRECTION_ANY_RTL:
17671                        case TEXT_DIRECTION_LTR:
17672                        case TEXT_DIRECTION_RTL:
17673                        case TEXT_DIRECTION_LOCALE:
17674                            mPrivateFlags2 |=
17675                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17676                            break;
17677                        default:
17678                            // Default resolved direction is "first strong" heuristic
17679                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17680                    }
17681                    break;
17682                case TEXT_DIRECTION_FIRST_STRONG:
17683                case TEXT_DIRECTION_ANY_RTL:
17684                case TEXT_DIRECTION_LTR:
17685                case TEXT_DIRECTION_RTL:
17686                case TEXT_DIRECTION_LOCALE:
17687                    // Resolved direction is the same as text direction
17688                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17689                    break;
17690                default:
17691                    // Default resolved direction is "first strong" heuristic
17692                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17693            }
17694        } else {
17695            // Default resolved direction is "first strong" heuristic
17696            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17697        }
17698
17699        // Set to resolved
17700        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17701        return true;
17702    }
17703
17704    /**
17705     * Check if text direction resolution can be done.
17706     *
17707     * @return true if text direction resolution can be done otherwise return false.
17708     */
17709    public boolean canResolveTextDirection() {
17710        switch (getRawTextDirection()) {
17711            case TEXT_DIRECTION_INHERIT:
17712                if (mParent != null) {
17713                    try {
17714                        return mParent.canResolveTextDirection();
17715                    } catch (AbstractMethodError e) {
17716                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17717                                " does not fully implement ViewParent", e);
17718                    }
17719                }
17720                return false;
17721
17722            default:
17723                return true;
17724        }
17725    }
17726
17727    /**
17728     * Reset resolved text direction. Text direction will be resolved during a call to
17729     * {@link #onMeasure(int, int)}.
17730     *
17731     * @hide
17732     */
17733    public void resetResolvedTextDirection() {
17734        // Reset any previous text direction resolution
17735        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17736        // Set to default value
17737        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17738    }
17739
17740    /**
17741     * @return true if text direction is inherited.
17742     *
17743     * @hide
17744     */
17745    public boolean isTextDirectionInherited() {
17746        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17747    }
17748
17749    /**
17750     * @return true if text direction is resolved.
17751     */
17752    public boolean isTextDirectionResolved() {
17753        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17754    }
17755
17756    /**
17757     * Return the value specifying the text alignment or policy that was set with
17758     * {@link #setTextAlignment(int)}.
17759     *
17760     * @return the defined text alignment. It can be one of:
17761     *
17762     * {@link #TEXT_ALIGNMENT_INHERIT},
17763     * {@link #TEXT_ALIGNMENT_GRAVITY},
17764     * {@link #TEXT_ALIGNMENT_CENTER},
17765     * {@link #TEXT_ALIGNMENT_TEXT_START},
17766     * {@link #TEXT_ALIGNMENT_TEXT_END},
17767     * {@link #TEXT_ALIGNMENT_VIEW_START},
17768     * {@link #TEXT_ALIGNMENT_VIEW_END}
17769     *
17770     * @attr ref android.R.styleable#View_textAlignment
17771     *
17772     * @hide
17773     */
17774    @ViewDebug.ExportedProperty(category = "text", mapping = {
17775            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17776            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17777            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17778            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17779            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17780            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17781            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17782    })
17783    public int getRawTextAlignment() {
17784        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17785    }
17786
17787    /**
17788     * Set the text alignment.
17789     *
17790     * @param textAlignment The text alignment to set. Should be one of
17791     *
17792     * {@link #TEXT_ALIGNMENT_INHERIT},
17793     * {@link #TEXT_ALIGNMENT_GRAVITY},
17794     * {@link #TEXT_ALIGNMENT_CENTER},
17795     * {@link #TEXT_ALIGNMENT_TEXT_START},
17796     * {@link #TEXT_ALIGNMENT_TEXT_END},
17797     * {@link #TEXT_ALIGNMENT_VIEW_START},
17798     * {@link #TEXT_ALIGNMENT_VIEW_END}
17799     *
17800     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17801     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17802     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17803     *
17804     * @attr ref android.R.styleable#View_textAlignment
17805     */
17806    public void setTextAlignment(int textAlignment) {
17807        if (textAlignment != getRawTextAlignment()) {
17808            // Reset the current and resolved text alignment
17809            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17810            resetResolvedTextAlignment();
17811            // Set the new text alignment
17812            mPrivateFlags2 |=
17813                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17814            // Do resolution
17815            resolveTextAlignment();
17816            // Notify change
17817            onRtlPropertiesChanged(getLayoutDirection());
17818            // Refresh
17819            requestLayout();
17820            invalidate(true);
17821        }
17822    }
17823
17824    /**
17825     * Return the resolved text alignment.
17826     *
17827     * @return the resolved text alignment. Returns one of:
17828     *
17829     * {@link #TEXT_ALIGNMENT_GRAVITY},
17830     * {@link #TEXT_ALIGNMENT_CENTER},
17831     * {@link #TEXT_ALIGNMENT_TEXT_START},
17832     * {@link #TEXT_ALIGNMENT_TEXT_END},
17833     * {@link #TEXT_ALIGNMENT_VIEW_START},
17834     * {@link #TEXT_ALIGNMENT_VIEW_END}
17835     *
17836     * @attr ref android.R.styleable#View_textAlignment
17837     */
17838    @ViewDebug.ExportedProperty(category = "text", mapping = {
17839            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17840            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17841            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17842            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17843            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17844            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17845            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17846    })
17847    public int getTextAlignment() {
17848        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17849                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17850    }
17851
17852    /**
17853     * Resolve the text alignment.
17854     *
17855     * @return true if resolution has been done, false otherwise.
17856     *
17857     * @hide
17858     */
17859    public boolean resolveTextAlignment() {
17860        // Reset any previous text alignment resolution
17861        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17862
17863        if (hasRtlSupport()) {
17864            // Set resolved text alignment flag depending on text alignment flag
17865            final int textAlignment = getRawTextAlignment();
17866            switch (textAlignment) {
17867                case TEXT_ALIGNMENT_INHERIT:
17868                    // Check if we can resolve the text alignment
17869                    if (!canResolveTextAlignment()) {
17870                        // We cannot do the resolution if there is no parent so use the default
17871                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17872                        // Resolution will need to happen again later
17873                        return false;
17874                    }
17875
17876                    // Parent has not yet resolved, so we still return the default
17877                    try {
17878                        if (!mParent.isTextAlignmentResolved()) {
17879                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17880                            // Resolution will need to happen again later
17881                            return false;
17882                        }
17883                    } catch (AbstractMethodError e) {
17884                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17885                                " does not fully implement ViewParent", e);
17886                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17887                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17888                        return true;
17889                    }
17890
17891                    int parentResolvedTextAlignment;
17892                    try {
17893                        parentResolvedTextAlignment = mParent.getTextAlignment();
17894                    } catch (AbstractMethodError e) {
17895                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17896                                " does not fully implement ViewParent", e);
17897                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17898                    }
17899                    switch (parentResolvedTextAlignment) {
17900                        case TEXT_ALIGNMENT_GRAVITY:
17901                        case TEXT_ALIGNMENT_TEXT_START:
17902                        case TEXT_ALIGNMENT_TEXT_END:
17903                        case TEXT_ALIGNMENT_CENTER:
17904                        case TEXT_ALIGNMENT_VIEW_START:
17905                        case TEXT_ALIGNMENT_VIEW_END:
17906                            // Resolved text alignment is the same as the parent resolved
17907                            // text alignment
17908                            mPrivateFlags2 |=
17909                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17910                            break;
17911                        default:
17912                            // Use default resolved text alignment
17913                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17914                    }
17915                    break;
17916                case TEXT_ALIGNMENT_GRAVITY:
17917                case TEXT_ALIGNMENT_TEXT_START:
17918                case TEXT_ALIGNMENT_TEXT_END:
17919                case TEXT_ALIGNMENT_CENTER:
17920                case TEXT_ALIGNMENT_VIEW_START:
17921                case TEXT_ALIGNMENT_VIEW_END:
17922                    // Resolved text alignment is the same as text alignment
17923                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17924                    break;
17925                default:
17926                    // Use default resolved text alignment
17927                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17928            }
17929        } else {
17930            // Use default resolved text alignment
17931            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17932        }
17933
17934        // Set the resolved
17935        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17936        return true;
17937    }
17938
17939    /**
17940     * Check if text alignment resolution can be done.
17941     *
17942     * @return true if text alignment resolution can be done otherwise return false.
17943     */
17944    public boolean canResolveTextAlignment() {
17945        switch (getRawTextAlignment()) {
17946            case TEXT_DIRECTION_INHERIT:
17947                if (mParent != null) {
17948                    try {
17949                        return mParent.canResolveTextAlignment();
17950                    } catch (AbstractMethodError e) {
17951                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17952                                " does not fully implement ViewParent", e);
17953                    }
17954                }
17955                return false;
17956
17957            default:
17958                return true;
17959        }
17960    }
17961
17962    /**
17963     * Reset resolved text alignment. Text alignment will be resolved during a call to
17964     * {@link #onMeasure(int, int)}.
17965     *
17966     * @hide
17967     */
17968    public void resetResolvedTextAlignment() {
17969        // Reset any previous text alignment resolution
17970        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17971        // Set to default
17972        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17973    }
17974
17975    /**
17976     * @return true if text alignment is inherited.
17977     *
17978     * @hide
17979     */
17980    public boolean isTextAlignmentInherited() {
17981        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17982    }
17983
17984    /**
17985     * @return true if text alignment is resolved.
17986     */
17987    public boolean isTextAlignmentResolved() {
17988        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17989    }
17990
17991    /**
17992     * Generate a value suitable for use in {@link #setId(int)}.
17993     * This value will not collide with ID values generated at build time by aapt for R.id.
17994     *
17995     * @return a generated ID value
17996     */
17997    public static int generateViewId() {
17998        for (;;) {
17999            final int result = sNextGeneratedId.get();
18000            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18001            int newValue = result + 1;
18002            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18003            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18004                return result;
18005            }
18006        }
18007    }
18008
18009    //
18010    // Properties
18011    //
18012    /**
18013     * A Property wrapper around the <code>alpha</code> functionality handled by the
18014     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18015     */
18016    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18017        @Override
18018        public void setValue(View object, float value) {
18019            object.setAlpha(value);
18020        }
18021
18022        @Override
18023        public Float get(View object) {
18024            return object.getAlpha();
18025        }
18026    };
18027
18028    /**
18029     * A Property wrapper around the <code>translationX</code> functionality handled by the
18030     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18031     */
18032    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18033        @Override
18034        public void setValue(View object, float value) {
18035            object.setTranslationX(value);
18036        }
18037
18038                @Override
18039        public Float get(View object) {
18040            return object.getTranslationX();
18041        }
18042    };
18043
18044    /**
18045     * A Property wrapper around the <code>translationY</code> functionality handled by the
18046     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18047     */
18048    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18049        @Override
18050        public void setValue(View object, float value) {
18051            object.setTranslationY(value);
18052        }
18053
18054        @Override
18055        public Float get(View object) {
18056            return object.getTranslationY();
18057        }
18058    };
18059
18060    /**
18061     * A Property wrapper around the <code>x</code> functionality handled by the
18062     * {@link View#setX(float)} and {@link View#getX()} methods.
18063     */
18064    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18065        @Override
18066        public void setValue(View object, float value) {
18067            object.setX(value);
18068        }
18069
18070        @Override
18071        public Float get(View object) {
18072            return object.getX();
18073        }
18074    };
18075
18076    /**
18077     * A Property wrapper around the <code>y</code> functionality handled by the
18078     * {@link View#setY(float)} and {@link View#getY()} methods.
18079     */
18080    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18081        @Override
18082        public void setValue(View object, float value) {
18083            object.setY(value);
18084        }
18085
18086        @Override
18087        public Float get(View object) {
18088            return object.getY();
18089        }
18090    };
18091
18092    /**
18093     * A Property wrapper around the <code>rotation</code> functionality handled by the
18094     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18095     */
18096    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18097        @Override
18098        public void setValue(View object, float value) {
18099            object.setRotation(value);
18100        }
18101
18102        @Override
18103        public Float get(View object) {
18104            return object.getRotation();
18105        }
18106    };
18107
18108    /**
18109     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18110     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18111     */
18112    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18113        @Override
18114        public void setValue(View object, float value) {
18115            object.setRotationX(value);
18116        }
18117
18118        @Override
18119        public Float get(View object) {
18120            return object.getRotationX();
18121        }
18122    };
18123
18124    /**
18125     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18126     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18127     */
18128    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18129        @Override
18130        public void setValue(View object, float value) {
18131            object.setRotationY(value);
18132        }
18133
18134        @Override
18135        public Float get(View object) {
18136            return object.getRotationY();
18137        }
18138    };
18139
18140    /**
18141     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18142     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18143     */
18144    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18145        @Override
18146        public void setValue(View object, float value) {
18147            object.setScaleX(value);
18148        }
18149
18150        @Override
18151        public Float get(View object) {
18152            return object.getScaleX();
18153        }
18154    };
18155
18156    /**
18157     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18158     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18159     */
18160    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18161        @Override
18162        public void setValue(View object, float value) {
18163            object.setScaleY(value);
18164        }
18165
18166        @Override
18167        public Float get(View object) {
18168            return object.getScaleY();
18169        }
18170    };
18171
18172    /**
18173     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18174     * Each MeasureSpec represents a requirement for either the width or the height.
18175     * A MeasureSpec is comprised of a size and a mode. There are three possible
18176     * modes:
18177     * <dl>
18178     * <dt>UNSPECIFIED</dt>
18179     * <dd>
18180     * The parent has not imposed any constraint on the child. It can be whatever size
18181     * it wants.
18182     * </dd>
18183     *
18184     * <dt>EXACTLY</dt>
18185     * <dd>
18186     * The parent has determined an exact size for the child. The child is going to be
18187     * given those bounds regardless of how big it wants to be.
18188     * </dd>
18189     *
18190     * <dt>AT_MOST</dt>
18191     * <dd>
18192     * The child can be as large as it wants up to the specified size.
18193     * </dd>
18194     * </dl>
18195     *
18196     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18197     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18198     */
18199    public static class MeasureSpec {
18200        private static final int MODE_SHIFT = 30;
18201        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18202
18203        /**
18204         * Measure specification mode: The parent has not imposed any constraint
18205         * on the child. It can be whatever size it wants.
18206         */
18207        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18208
18209        /**
18210         * Measure specification mode: The parent has determined an exact size
18211         * for the child. The child is going to be given those bounds regardless
18212         * of how big it wants to be.
18213         */
18214        public static final int EXACTLY     = 1 << MODE_SHIFT;
18215
18216        /**
18217         * Measure specification mode: The child can be as large as it wants up
18218         * to the specified size.
18219         */
18220        public static final int AT_MOST     = 2 << MODE_SHIFT;
18221
18222        /**
18223         * Creates a measure specification based on the supplied size and mode.
18224         *
18225         * The mode must always be one of the following:
18226         * <ul>
18227         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18228         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18229         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18230         * </ul>
18231         *
18232         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
18233         * implementation was such that the order of arguments did not matter
18234         * and overflow in either value could impact the resulting MeasureSpec.
18235         * {@link android.widget.RelativeLayout} was affected by this bug.
18236         * Apps targeting API levels greater than 17 will get the fixed, more strict
18237         * behavior.</p>
18238         *
18239         * @param size the size of the measure specification
18240         * @param mode the mode of the measure specification
18241         * @return the measure specification based on size and mode
18242         */
18243        public static int makeMeasureSpec(int size, int mode) {
18244            if (sUseBrokenMakeMeasureSpec) {
18245                return size + mode;
18246            } else {
18247                return (size & ~MODE_MASK) | (mode & MODE_MASK);
18248            }
18249        }
18250
18251        /**
18252         * Extracts the mode from the supplied measure specification.
18253         *
18254         * @param measureSpec the measure specification to extract the mode from
18255         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
18256         *         {@link android.view.View.MeasureSpec#AT_MOST} or
18257         *         {@link android.view.View.MeasureSpec#EXACTLY}
18258         */
18259        public static int getMode(int measureSpec) {
18260            return (measureSpec & MODE_MASK);
18261        }
18262
18263        /**
18264         * Extracts the size from the supplied measure specification.
18265         *
18266         * @param measureSpec the measure specification to extract the size from
18267         * @return the size in pixels defined in the supplied measure specification
18268         */
18269        public static int getSize(int measureSpec) {
18270            return (measureSpec & ~MODE_MASK);
18271        }
18272
18273        static int adjust(int measureSpec, int delta) {
18274            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18275        }
18276
18277        /**
18278         * Returns a String representation of the specified measure
18279         * specification.
18280         *
18281         * @param measureSpec the measure specification to convert to a String
18282         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18283         */
18284        public static String toString(int measureSpec) {
18285            int mode = getMode(measureSpec);
18286            int size = getSize(measureSpec);
18287
18288            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18289
18290            if (mode == UNSPECIFIED)
18291                sb.append("UNSPECIFIED ");
18292            else if (mode == EXACTLY)
18293                sb.append("EXACTLY ");
18294            else if (mode == AT_MOST)
18295                sb.append("AT_MOST ");
18296            else
18297                sb.append(mode).append(" ");
18298
18299            sb.append(size);
18300            return sb.toString();
18301        }
18302    }
18303
18304    class CheckForLongPress implements Runnable {
18305
18306        private int mOriginalWindowAttachCount;
18307
18308        public void run() {
18309            if (isPressed() && (mParent != null)
18310                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18311                if (performLongClick()) {
18312                    mHasPerformedLongPress = true;
18313                }
18314            }
18315        }
18316
18317        public void rememberWindowAttachCount() {
18318            mOriginalWindowAttachCount = mWindowAttachCount;
18319        }
18320    }
18321
18322    private final class CheckForTap implements Runnable {
18323        public void run() {
18324            mPrivateFlags &= ~PFLAG_PREPRESSED;
18325            setPressed(true);
18326            checkForLongClick(ViewConfiguration.getTapTimeout());
18327        }
18328    }
18329
18330    private final class PerformClick implements Runnable {
18331        public void run() {
18332            performClick();
18333        }
18334    }
18335
18336    /** @hide */
18337    public void hackTurnOffWindowResizeAnim(boolean off) {
18338        mAttachInfo.mTurnOffWindowResizeAnim = off;
18339    }
18340
18341    /**
18342     * This method returns a ViewPropertyAnimator object, which can be used to animate
18343     * specific properties on this View.
18344     *
18345     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18346     */
18347    public ViewPropertyAnimator animate() {
18348        if (mAnimator == null) {
18349            mAnimator = new ViewPropertyAnimator(this);
18350        }
18351        return mAnimator;
18352    }
18353
18354    /**
18355     * Interface definition for a callback to be invoked when a hardware key event is
18356     * dispatched to this view. The callback will be invoked before the key event is
18357     * given to the view. This is only useful for hardware keyboards; a software input
18358     * method has no obligation to trigger this listener.
18359     */
18360    public interface OnKeyListener {
18361        /**
18362         * Called when a hardware key is dispatched to a view. This allows listeners to
18363         * get a chance to respond before the target view.
18364         * <p>Key presses in software keyboards will generally NOT trigger this method,
18365         * although some may elect to do so in some situations. Do not assume a
18366         * software input method has to be key-based; even if it is, it may use key presses
18367         * in a different way than you expect, so there is no way to reliably catch soft
18368         * input key presses.
18369         *
18370         * @param v The view the key has been dispatched to.
18371         * @param keyCode The code for the physical key that was pressed
18372         * @param event The KeyEvent object containing full information about
18373         *        the event.
18374         * @return True if the listener has consumed the event, false otherwise.
18375         */
18376        boolean onKey(View v, int keyCode, KeyEvent event);
18377    }
18378
18379    /**
18380     * Interface definition for a callback to be invoked when a touch event is
18381     * dispatched to this view. The callback will be invoked before the touch
18382     * event is given to the view.
18383     */
18384    public interface OnTouchListener {
18385        /**
18386         * Called when a touch event is dispatched to a view. This allows listeners to
18387         * get a chance to respond before the target view.
18388         *
18389         * @param v The view the touch event has been dispatched to.
18390         * @param event The MotionEvent object containing full information about
18391         *        the event.
18392         * @return True if the listener has consumed the event, false otherwise.
18393         */
18394        boolean onTouch(View v, MotionEvent event);
18395    }
18396
18397    /**
18398     * Interface definition for a callback to be invoked when a hover event is
18399     * dispatched to this view. The callback will be invoked before the hover
18400     * event is given to the view.
18401     */
18402    public interface OnHoverListener {
18403        /**
18404         * Called when a hover event is dispatched to a view. This allows listeners to
18405         * get a chance to respond before the target view.
18406         *
18407         * @param v The view the hover event has been dispatched to.
18408         * @param event The MotionEvent object containing full information about
18409         *        the event.
18410         * @return True if the listener has consumed the event, false otherwise.
18411         */
18412        boolean onHover(View v, MotionEvent event);
18413    }
18414
18415    /**
18416     * Interface definition for a callback to be invoked when a generic motion event is
18417     * dispatched to this view. The callback will be invoked before the generic motion
18418     * event is given to the view.
18419     */
18420    public interface OnGenericMotionListener {
18421        /**
18422         * Called when a generic motion event is dispatched to a view. This allows listeners to
18423         * get a chance to respond before the target view.
18424         *
18425         * @param v The view the generic motion event has been dispatched to.
18426         * @param event The MotionEvent object containing full information about
18427         *        the event.
18428         * @return True if the listener has consumed the event, false otherwise.
18429         */
18430        boolean onGenericMotion(View v, MotionEvent event);
18431    }
18432
18433    /**
18434     * Interface definition for a callback to be invoked when a view has been clicked and held.
18435     */
18436    public interface OnLongClickListener {
18437        /**
18438         * Called when a view has been clicked and held.
18439         *
18440         * @param v The view that was clicked and held.
18441         *
18442         * @return true if the callback consumed the long click, false otherwise.
18443         */
18444        boolean onLongClick(View v);
18445    }
18446
18447    /**
18448     * Interface definition for a callback to be invoked when a drag is being dispatched
18449     * to this view.  The callback will be invoked before the hosting view's own
18450     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18451     * onDrag(event) behavior, it should return 'false' from this callback.
18452     *
18453     * <div class="special reference">
18454     * <h3>Developer Guides</h3>
18455     * <p>For a guide to implementing drag and drop features, read the
18456     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18457     * </div>
18458     */
18459    public interface OnDragListener {
18460        /**
18461         * Called when a drag event is dispatched to a view. This allows listeners
18462         * to get a chance to override base View behavior.
18463         *
18464         * @param v The View that received the drag event.
18465         * @param event The {@link android.view.DragEvent} object for the drag event.
18466         * @return {@code true} if the drag event was handled successfully, or {@code false}
18467         * if the drag event was not handled. Note that {@code false} will trigger the View
18468         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18469         */
18470        boolean onDrag(View v, DragEvent event);
18471    }
18472
18473    /**
18474     * Interface definition for a callback to be invoked when the focus state of
18475     * a view changed.
18476     */
18477    public interface OnFocusChangeListener {
18478        /**
18479         * Called when the focus state of a view has changed.
18480         *
18481         * @param v The view whose state has changed.
18482         * @param hasFocus The new focus state of v.
18483         */
18484        void onFocusChange(View v, boolean hasFocus);
18485    }
18486
18487    /**
18488     * Interface definition for a callback to be invoked when a view is clicked.
18489     */
18490    public interface OnClickListener {
18491        /**
18492         * Called when a view has been clicked.
18493         *
18494         * @param v The view that was clicked.
18495         */
18496        void onClick(View v);
18497    }
18498
18499    /**
18500     * Interface definition for a callback to be invoked when the context menu
18501     * for this view is being built.
18502     */
18503    public interface OnCreateContextMenuListener {
18504        /**
18505         * Called when the context menu for this view is being built. It is not
18506         * safe to hold onto the menu after this method returns.
18507         *
18508         * @param menu The context menu that is being built
18509         * @param v The view for which the context menu is being built
18510         * @param menuInfo Extra information about the item for which the
18511         *            context menu should be shown. This information will vary
18512         *            depending on the class of v.
18513         */
18514        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18515    }
18516
18517    /**
18518     * Interface definition for a callback to be invoked when the status bar changes
18519     * visibility.  This reports <strong>global</strong> changes to the system UI
18520     * state, not what the application is requesting.
18521     *
18522     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18523     */
18524    public interface OnSystemUiVisibilityChangeListener {
18525        /**
18526         * Called when the status bar changes visibility because of a call to
18527         * {@link View#setSystemUiVisibility(int)}.
18528         *
18529         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18530         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18531         * This tells you the <strong>global</strong> state of these UI visibility
18532         * flags, not what your app is currently applying.
18533         */
18534        public void onSystemUiVisibilityChange(int visibility);
18535    }
18536
18537    /**
18538     * Interface definition for a callback to be invoked when this view is attached
18539     * or detached from its window.
18540     */
18541    public interface OnAttachStateChangeListener {
18542        /**
18543         * Called when the view is attached to a window.
18544         * @param v The view that was attached
18545         */
18546        public void onViewAttachedToWindow(View v);
18547        /**
18548         * Called when the view is detached from a window.
18549         * @param v The view that was detached
18550         */
18551        public void onViewDetachedFromWindow(View v);
18552    }
18553
18554    private final class UnsetPressedState implements Runnable {
18555        public void run() {
18556            setPressed(false);
18557        }
18558    }
18559
18560    /**
18561     * Base class for derived classes that want to save and restore their own
18562     * state in {@link android.view.View#onSaveInstanceState()}.
18563     */
18564    public static class BaseSavedState extends AbsSavedState {
18565        /**
18566         * Constructor used when reading from a parcel. Reads the state of the superclass.
18567         *
18568         * @param source
18569         */
18570        public BaseSavedState(Parcel source) {
18571            super(source);
18572        }
18573
18574        /**
18575         * Constructor called by derived classes when creating their SavedState objects
18576         *
18577         * @param superState The state of the superclass of this view
18578         */
18579        public BaseSavedState(Parcelable superState) {
18580            super(superState);
18581        }
18582
18583        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18584                new Parcelable.Creator<BaseSavedState>() {
18585            public BaseSavedState createFromParcel(Parcel in) {
18586                return new BaseSavedState(in);
18587            }
18588
18589            public BaseSavedState[] newArray(int size) {
18590                return new BaseSavedState[size];
18591            }
18592        };
18593    }
18594
18595    /**
18596     * A set of information given to a view when it is attached to its parent
18597     * window.
18598     */
18599    static class AttachInfo {
18600        interface Callbacks {
18601            void playSoundEffect(int effectId);
18602            boolean performHapticFeedback(int effectId, boolean always);
18603        }
18604
18605        /**
18606         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18607         * to a Handler. This class contains the target (View) to invalidate and
18608         * the coordinates of the dirty rectangle.
18609         *
18610         * For performance purposes, this class also implements a pool of up to
18611         * POOL_LIMIT objects that get reused. This reduces memory allocations
18612         * whenever possible.
18613         */
18614        static class InvalidateInfo {
18615            private static final int POOL_LIMIT = 10;
18616
18617            private static final SynchronizedPool<InvalidateInfo> sPool =
18618                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18619
18620            View target;
18621
18622            int left;
18623            int top;
18624            int right;
18625            int bottom;
18626
18627            public static InvalidateInfo obtain() {
18628                InvalidateInfo instance = sPool.acquire();
18629                return (instance != null) ? instance : new InvalidateInfo();
18630            }
18631
18632            public void recycle() {
18633                target = null;
18634                sPool.release(this);
18635            }
18636        }
18637
18638        final IWindowSession mSession;
18639
18640        final IWindow mWindow;
18641
18642        final IBinder mWindowToken;
18643
18644        final Display mDisplay;
18645
18646        final Callbacks mRootCallbacks;
18647
18648        HardwareCanvas mHardwareCanvas;
18649
18650        IWindowId mIWindowId;
18651        WindowId mWindowId;
18652
18653        /**
18654         * The top view of the hierarchy.
18655         */
18656        View mRootView;
18657
18658        IBinder mPanelParentWindowToken;
18659        Surface mSurface;
18660
18661        boolean mHardwareAccelerated;
18662        boolean mHardwareAccelerationRequested;
18663        HardwareRenderer mHardwareRenderer;
18664
18665        boolean mScreenOn;
18666
18667        /**
18668         * Scale factor used by the compatibility mode
18669         */
18670        float mApplicationScale;
18671
18672        /**
18673         * Indicates whether the application is in compatibility mode
18674         */
18675        boolean mScalingRequired;
18676
18677        /**
18678         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18679         */
18680        boolean mTurnOffWindowResizeAnim;
18681
18682        /**
18683         * Left position of this view's window
18684         */
18685        int mWindowLeft;
18686
18687        /**
18688         * Top position of this view's window
18689         */
18690        int mWindowTop;
18691
18692        /**
18693         * Indicates whether views need to use 32-bit drawing caches
18694         */
18695        boolean mUse32BitDrawingCache;
18696
18697        /**
18698         * For windows that are full-screen but using insets to layout inside
18699         * of the screen areas, these are the current insets to appear inside
18700         * the overscan area of the display.
18701         */
18702        final Rect mOverscanInsets = new Rect();
18703
18704        /**
18705         * For windows that are full-screen but using insets to layout inside
18706         * of the screen decorations, these are the current insets for the
18707         * content of the window.
18708         */
18709        final Rect mContentInsets = new Rect();
18710
18711        /**
18712         * For windows that are full-screen but using insets to layout inside
18713         * of the screen decorations, these are the current insets for the
18714         * actual visible parts of the window.
18715         */
18716        final Rect mVisibleInsets = new Rect();
18717
18718        /**
18719         * The internal insets given by this window.  This value is
18720         * supplied by the client (through
18721         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18722         * be given to the window manager when changed to be used in laying
18723         * out windows behind it.
18724         */
18725        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18726                = new ViewTreeObserver.InternalInsetsInfo();
18727
18728        /**
18729         * Set to true when mGivenInternalInsets is non-empty.
18730         */
18731        boolean mHasNonEmptyGivenInternalInsets;
18732
18733        /**
18734         * All views in the window's hierarchy that serve as scroll containers,
18735         * used to determine if the window can be resized or must be panned
18736         * to adjust for a soft input area.
18737         */
18738        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18739
18740        final KeyEvent.DispatcherState mKeyDispatchState
18741                = new KeyEvent.DispatcherState();
18742
18743        /**
18744         * Indicates whether the view's window currently has the focus.
18745         */
18746        boolean mHasWindowFocus;
18747
18748        /**
18749         * The current visibility of the window.
18750         */
18751        int mWindowVisibility;
18752
18753        /**
18754         * Indicates the time at which drawing started to occur.
18755         */
18756        long mDrawingTime;
18757
18758        /**
18759         * Indicates whether or not ignoring the DIRTY_MASK flags.
18760         */
18761        boolean mIgnoreDirtyState;
18762
18763        /**
18764         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18765         * to avoid clearing that flag prematurely.
18766         */
18767        boolean mSetIgnoreDirtyState = false;
18768
18769        /**
18770         * Indicates whether the view's window is currently in touch mode.
18771         */
18772        boolean mInTouchMode;
18773
18774        /**
18775         * Indicates that ViewAncestor should trigger a global layout change
18776         * the next time it performs a traversal
18777         */
18778        boolean mRecomputeGlobalAttributes;
18779
18780        /**
18781         * Always report new attributes at next traversal.
18782         */
18783        boolean mForceReportNewAttributes;
18784
18785        /**
18786         * Set during a traveral if any views want to keep the screen on.
18787         */
18788        boolean mKeepScreenOn;
18789
18790        /**
18791         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18792         */
18793        int mSystemUiVisibility;
18794
18795        /**
18796         * Hack to force certain system UI visibility flags to be cleared.
18797         */
18798        int mDisabledSystemUiVisibility;
18799
18800        /**
18801         * Last global system UI visibility reported by the window manager.
18802         */
18803        int mGlobalSystemUiVisibility;
18804
18805        /**
18806         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18807         * attached.
18808         */
18809        boolean mHasSystemUiListeners;
18810
18811        /**
18812         * Set if the window has requested to extend into the overscan region
18813         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18814         */
18815        boolean mOverscanRequested;
18816
18817        /**
18818         * Set if the visibility of any views has changed.
18819         */
18820        boolean mViewVisibilityChanged;
18821
18822        /**
18823         * Set to true if a view has been scrolled.
18824         */
18825        boolean mViewScrollChanged;
18826
18827        /**
18828         * Global to the view hierarchy used as a temporary for dealing with
18829         * x/y points in the transparent region computations.
18830         */
18831        final int[] mTransparentLocation = new int[2];
18832
18833        /**
18834         * Global to the view hierarchy used as a temporary for dealing with
18835         * x/y points in the ViewGroup.invalidateChild implementation.
18836         */
18837        final int[] mInvalidateChildLocation = new int[2];
18838
18839
18840        /**
18841         * Global to the view hierarchy used as a temporary for dealing with
18842         * x/y location when view is transformed.
18843         */
18844        final float[] mTmpTransformLocation = new float[2];
18845
18846        /**
18847         * The view tree observer used to dispatch global events like
18848         * layout, pre-draw, touch mode change, etc.
18849         */
18850        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18851
18852        /**
18853         * A Canvas used by the view hierarchy to perform bitmap caching.
18854         */
18855        Canvas mCanvas;
18856
18857        /**
18858         * The view root impl.
18859         */
18860        final ViewRootImpl mViewRootImpl;
18861
18862        /**
18863         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18864         * handler can be used to pump events in the UI events queue.
18865         */
18866        final Handler mHandler;
18867
18868        /**
18869         * Temporary for use in computing invalidate rectangles while
18870         * calling up the hierarchy.
18871         */
18872        final Rect mTmpInvalRect = new Rect();
18873
18874        /**
18875         * Temporary for use in computing hit areas with transformed views
18876         */
18877        final RectF mTmpTransformRect = new RectF();
18878
18879        /**
18880         * Temporary for use in transforming invalidation rect
18881         */
18882        final Matrix mTmpMatrix = new Matrix();
18883
18884        /**
18885         * Temporary for use in transforming invalidation rect
18886         */
18887        final Transformation mTmpTransformation = new Transformation();
18888
18889        /**
18890         * Temporary list for use in collecting focusable descendents of a view.
18891         */
18892        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18893
18894        /**
18895         * The id of the window for accessibility purposes.
18896         */
18897        int mAccessibilityWindowId = View.NO_ID;
18898
18899        /**
18900         * Flags related to accessibility processing.
18901         *
18902         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18903         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18904         */
18905        int mAccessibilityFetchFlags;
18906
18907        /**
18908         * The drawable for highlighting accessibility focus.
18909         */
18910        Drawable mAccessibilityFocusDrawable;
18911
18912        /**
18913         * Show where the margins, bounds and layout bounds are for each view.
18914         */
18915        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18916
18917        /**
18918         * Point used to compute visible regions.
18919         */
18920        final Point mPoint = new Point();
18921
18922        /**
18923         * Used to track which View originated a requestLayout() call, used when
18924         * requestLayout() is called during layout.
18925         */
18926        View mViewRequestingLayout;
18927
18928        /**
18929         * Creates a new set of attachment information with the specified
18930         * events handler and thread.
18931         *
18932         * @param handler the events handler the view must use
18933         */
18934        AttachInfo(IWindowSession session, IWindow window, Display display,
18935                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18936            mSession = session;
18937            mWindow = window;
18938            mWindowToken = window.asBinder();
18939            mDisplay = display;
18940            mViewRootImpl = viewRootImpl;
18941            mHandler = handler;
18942            mRootCallbacks = effectPlayer;
18943        }
18944    }
18945
18946    /**
18947     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18948     * is supported. This avoids keeping too many unused fields in most
18949     * instances of View.</p>
18950     */
18951    private static class ScrollabilityCache implements Runnable {
18952
18953        /**
18954         * Scrollbars are not visible
18955         */
18956        public static final int OFF = 0;
18957
18958        /**
18959         * Scrollbars are visible
18960         */
18961        public static final int ON = 1;
18962
18963        /**
18964         * Scrollbars are fading away
18965         */
18966        public static final int FADING = 2;
18967
18968        public boolean fadeScrollBars;
18969
18970        public int fadingEdgeLength;
18971        public int scrollBarDefaultDelayBeforeFade;
18972        public int scrollBarFadeDuration;
18973
18974        public int scrollBarSize;
18975        public ScrollBarDrawable scrollBar;
18976        public float[] interpolatorValues;
18977        public View host;
18978
18979        public final Paint paint;
18980        public final Matrix matrix;
18981        public Shader shader;
18982
18983        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18984
18985        private static final float[] OPAQUE = { 255 };
18986        private static final float[] TRANSPARENT = { 0.0f };
18987
18988        /**
18989         * When fading should start. This time moves into the future every time
18990         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18991         */
18992        public long fadeStartTime;
18993
18994
18995        /**
18996         * The current state of the scrollbars: ON, OFF, or FADING
18997         */
18998        public int state = OFF;
18999
19000        private int mLastColor;
19001
19002        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19003            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19004            scrollBarSize = configuration.getScaledScrollBarSize();
19005            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19006            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19007
19008            paint = new Paint();
19009            matrix = new Matrix();
19010            // use use a height of 1, and then wack the matrix each time we
19011            // actually use it.
19012            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19013            paint.setShader(shader);
19014            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19015
19016            this.host = host;
19017        }
19018
19019        public void setFadeColor(int color) {
19020            if (color != mLastColor) {
19021                mLastColor = color;
19022
19023                if (color != 0) {
19024                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19025                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19026                    paint.setShader(shader);
19027                    // Restore the default transfer mode (src_over)
19028                    paint.setXfermode(null);
19029                } else {
19030                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19031                    paint.setShader(shader);
19032                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19033                }
19034            }
19035        }
19036
19037        public void run() {
19038            long now = AnimationUtils.currentAnimationTimeMillis();
19039            if (now >= fadeStartTime) {
19040
19041                // the animation fades the scrollbars out by changing
19042                // the opacity (alpha) from fully opaque to fully
19043                // transparent
19044                int nextFrame = (int) now;
19045                int framesCount = 0;
19046
19047                Interpolator interpolator = scrollBarInterpolator;
19048
19049                // Start opaque
19050                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19051
19052                // End transparent
19053                nextFrame += scrollBarFadeDuration;
19054                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19055
19056                state = FADING;
19057
19058                // Kick off the fade animation
19059                host.invalidate(true);
19060            }
19061        }
19062    }
19063
19064    /**
19065     * Resuable callback for sending
19066     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19067     */
19068    private class SendViewScrolledAccessibilityEvent implements Runnable {
19069        public volatile boolean mIsPending;
19070
19071        public void run() {
19072            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19073            mIsPending = false;
19074        }
19075    }
19076
19077    /**
19078     * <p>
19079     * This class represents a delegate that can be registered in a {@link View}
19080     * to enhance accessibility support via composition rather via inheritance.
19081     * It is specifically targeted to widget developers that extend basic View
19082     * classes i.e. classes in package android.view, that would like their
19083     * applications to be backwards compatible.
19084     * </p>
19085     * <div class="special reference">
19086     * <h3>Developer Guides</h3>
19087     * <p>For more information about making applications accessible, read the
19088     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19089     * developer guide.</p>
19090     * </div>
19091     * <p>
19092     * A scenario in which a developer would like to use an accessibility delegate
19093     * is overriding a method introduced in a later API version then the minimal API
19094     * version supported by the application. For example, the method
19095     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19096     * in API version 4 when the accessibility APIs were first introduced. If a
19097     * developer would like his application to run on API version 4 devices (assuming
19098     * all other APIs used by the application are version 4 or lower) and take advantage
19099     * of this method, instead of overriding the method which would break the application's
19100     * backwards compatibility, he can override the corresponding method in this
19101     * delegate and register the delegate in the target View if the API version of
19102     * the system is high enough i.e. the API version is same or higher to the API
19103     * version that introduced
19104     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19105     * </p>
19106     * <p>
19107     * Here is an example implementation:
19108     * </p>
19109     * <code><pre><p>
19110     * if (Build.VERSION.SDK_INT >= 14) {
19111     *     // If the API version is equal of higher than the version in
19112     *     // which onInitializeAccessibilityNodeInfo was introduced we
19113     *     // register a delegate with a customized implementation.
19114     *     View view = findViewById(R.id.view_id);
19115     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19116     *         public void onInitializeAccessibilityNodeInfo(View host,
19117     *                 AccessibilityNodeInfo info) {
19118     *             // Let the default implementation populate the info.
19119     *             super.onInitializeAccessibilityNodeInfo(host, info);
19120     *             // Set some other information.
19121     *             info.setEnabled(host.isEnabled());
19122     *         }
19123     *     });
19124     * }
19125     * </code></pre></p>
19126     * <p>
19127     * This delegate contains methods that correspond to the accessibility methods
19128     * in View. If a delegate has been specified the implementation in View hands
19129     * off handling to the corresponding method in this delegate. The default
19130     * implementation the delegate methods behaves exactly as the corresponding
19131     * method in View for the case of no accessibility delegate been set. Hence,
19132     * to customize the behavior of a View method, clients can override only the
19133     * corresponding delegate method without altering the behavior of the rest
19134     * accessibility related methods of the host view.
19135     * </p>
19136     */
19137    public static class AccessibilityDelegate {
19138
19139        /**
19140         * Sends an accessibility event of the given type. If accessibility is not
19141         * enabled this method has no effect.
19142         * <p>
19143         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19144         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19145         * been set.
19146         * </p>
19147         *
19148         * @param host The View hosting the delegate.
19149         * @param eventType The type of the event to send.
19150         *
19151         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
19152         */
19153        public void sendAccessibilityEvent(View host, int eventType) {
19154            host.sendAccessibilityEventInternal(eventType);
19155        }
19156
19157        /**
19158         * Performs the specified accessibility action on the view. For
19159         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
19160         * <p>
19161         * The default implementation behaves as
19162         * {@link View#performAccessibilityAction(int, Bundle)
19163         *  View#performAccessibilityAction(int, Bundle)} for the case of
19164         *  no accessibility delegate been set.
19165         * </p>
19166         *
19167         * @param action The action to perform.
19168         * @return Whether the action was performed.
19169         *
19170         * @see View#performAccessibilityAction(int, Bundle)
19171         *      View#performAccessibilityAction(int, Bundle)
19172         */
19173        public boolean performAccessibilityAction(View host, int action, Bundle args) {
19174            return host.performAccessibilityActionInternal(action, args);
19175        }
19176
19177        /**
19178         * Sends an accessibility event. This method behaves exactly as
19179         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
19180         * empty {@link AccessibilityEvent} and does not perform a check whether
19181         * accessibility is enabled.
19182         * <p>
19183         * The default implementation behaves as
19184         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19185         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
19186         * the case of no accessibility delegate been set.
19187         * </p>
19188         *
19189         * @param host The View hosting the delegate.
19190         * @param event The event to send.
19191         *
19192         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19193         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19194         */
19195        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
19196            host.sendAccessibilityEventUncheckedInternal(event);
19197        }
19198
19199        /**
19200         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
19201         * to its children for adding their text content to the event.
19202         * <p>
19203         * The default implementation behaves as
19204         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19205         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
19206         * the case of no accessibility delegate been set.
19207         * </p>
19208         *
19209         * @param host The View hosting the delegate.
19210         * @param event The event.
19211         * @return True if the event population was completed.
19212         *
19213         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19214         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19215         */
19216        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19217            return host.dispatchPopulateAccessibilityEventInternal(event);
19218        }
19219
19220        /**
19221         * Gives a chance to the host View to populate the accessibility event with its
19222         * text content.
19223         * <p>
19224         * The default implementation behaves as
19225         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
19226         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
19227         * the case of no accessibility delegate been set.
19228         * </p>
19229         *
19230         * @param host The View hosting the delegate.
19231         * @param event The accessibility event which to populate.
19232         *
19233         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
19234         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
19235         */
19236        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19237            host.onPopulateAccessibilityEventInternal(event);
19238        }
19239
19240        /**
19241         * Initializes an {@link AccessibilityEvent} with information about the
19242         * the host View which is the event source.
19243         * <p>
19244         * The default implementation behaves as
19245         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19246         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19247         * the case of no accessibility delegate been set.
19248         * </p>
19249         *
19250         * @param host The View hosting the delegate.
19251         * @param event The event to initialize.
19252         *
19253         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19254         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19255         */
19256        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19257            host.onInitializeAccessibilityEventInternal(event);
19258        }
19259
19260        /**
19261         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19262         * <p>
19263         * The default implementation behaves as
19264         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19265         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19266         * the case of no accessibility delegate been set.
19267         * </p>
19268         *
19269         * @param host The View hosting the delegate.
19270         * @param info The instance to initialize.
19271         *
19272         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19273         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19274         */
19275        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19276            host.onInitializeAccessibilityNodeInfoInternal(info);
19277        }
19278
19279        /**
19280         * Called when a child of the host View has requested sending an
19281         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19282         * to augment the event.
19283         * <p>
19284         * The default implementation behaves as
19285         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19286         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19287         * the case of no accessibility delegate been set.
19288         * </p>
19289         *
19290         * @param host The View hosting the delegate.
19291         * @param child The child which requests sending the event.
19292         * @param event The event to be sent.
19293         * @return True if the event should be sent
19294         *
19295         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19296         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19297         */
19298        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19299                AccessibilityEvent event) {
19300            return host.onRequestSendAccessibilityEventInternal(child, event);
19301        }
19302
19303        /**
19304         * Gets the provider for managing a virtual view hierarchy rooted at this View
19305         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19306         * that explore the window content.
19307         * <p>
19308         * The default implementation behaves as
19309         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19310         * the case of no accessibility delegate been set.
19311         * </p>
19312         *
19313         * @return The provider.
19314         *
19315         * @see AccessibilityNodeProvider
19316         */
19317        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19318            return null;
19319        }
19320
19321        /**
19322         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19323         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19324         * This method is responsible for obtaining an accessibility node info from a
19325         * pool of reusable instances and calling
19326         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19327         * view to initialize the former.
19328         * <p>
19329         * <strong>Note:</strong> The client is responsible for recycling the obtained
19330         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19331         * creation.
19332         * </p>
19333         * <p>
19334         * The default implementation behaves as
19335         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19336         * the case of no accessibility delegate been set.
19337         * </p>
19338         * @return A populated {@link AccessibilityNodeInfo}.
19339         *
19340         * @see AccessibilityNodeInfo
19341         *
19342         * @hide
19343         */
19344        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19345            return host.createAccessibilityNodeInfoInternal();
19346        }
19347    }
19348
19349    private class MatchIdPredicate implements Predicate<View> {
19350        public int mId;
19351
19352        @Override
19353        public boolean apply(View view) {
19354            return (view.mID == mId);
19355        }
19356    }
19357
19358    private class MatchLabelForPredicate implements Predicate<View> {
19359        private int mLabeledId;
19360
19361        @Override
19362        public boolean apply(View view) {
19363            return (view.mLabelForId == mLabeledId);
19364        }
19365    }
19366
19367    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19368        private int mChangeTypes = 0;
19369        private boolean mPosted;
19370        private boolean mPostedWithDelay;
19371        private long mLastEventTimeMillis;
19372
19373        @Override
19374        public void run() {
19375            mPosted = false;
19376            mPostedWithDelay = false;
19377            mLastEventTimeMillis = SystemClock.uptimeMillis();
19378            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19379                final AccessibilityEvent event = AccessibilityEvent.obtain();
19380                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19381                event.setContentChangeTypes(mChangeTypes);
19382                sendAccessibilityEventUnchecked(event);
19383            }
19384            mChangeTypes = 0;
19385        }
19386
19387        public void runOrPost(int changeType) {
19388            mChangeTypes |= changeType;
19389
19390            // If this is a live region or the child of a live region, collect
19391            // all events from this frame and send them on the next frame.
19392            if (inLiveRegion()) {
19393                // If we're already posted with a delay, remove that.
19394                if (mPostedWithDelay) {
19395                    removeCallbacks(this);
19396                    mPostedWithDelay = false;
19397                }
19398                // Only post if we're not already posted.
19399                if (!mPosted) {
19400                    post(this);
19401                    mPosted = true;
19402                }
19403                return;
19404            }
19405
19406            if (mPosted) {
19407                return;
19408            }
19409            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19410            final long minEventIntevalMillis =
19411                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19412            if (timeSinceLastMillis >= minEventIntevalMillis) {
19413                removeCallbacks(this);
19414                run();
19415            } else {
19416                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19417                mPosted = true;
19418                mPostedWithDelay = true;
19419            }
19420        }
19421    }
19422
19423    private boolean inLiveRegion() {
19424        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19425            return true;
19426        }
19427
19428        ViewParent parent = getParent();
19429        while (parent instanceof View) {
19430            if (((View) parent).getAccessibilityLiveRegion()
19431                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19432                return true;
19433            }
19434            parent = parent.getParent();
19435        }
19436
19437        return false;
19438    }
19439
19440    /**
19441     * Dump all private flags in readable format, useful for documentation and
19442     * sanity checking.
19443     */
19444    private static void dumpFlags() {
19445        final HashMap<String, String> found = Maps.newHashMap();
19446        try {
19447            for (Field field : View.class.getDeclaredFields()) {
19448                final int modifiers = field.getModifiers();
19449                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19450                    if (field.getType().equals(int.class)) {
19451                        final int value = field.getInt(null);
19452                        dumpFlag(found, field.getName(), value);
19453                    } else if (field.getType().equals(int[].class)) {
19454                        final int[] values = (int[]) field.get(null);
19455                        for (int i = 0; i < values.length; i++) {
19456                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19457                        }
19458                    }
19459                }
19460            }
19461        } catch (IllegalAccessException e) {
19462            throw new RuntimeException(e);
19463        }
19464
19465        final ArrayList<String> keys = Lists.newArrayList();
19466        keys.addAll(found.keySet());
19467        Collections.sort(keys);
19468        for (String key : keys) {
19469            Log.d(VIEW_LOG_TAG, found.get(key));
19470        }
19471    }
19472
19473    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19474        // Sort flags by prefix, then by bits, always keeping unique keys
19475        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19476        final int prefix = name.indexOf('_');
19477        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19478        final String output = bits + " " + name;
19479        found.put(key, output);
19480    }
19481}
19482