View.java revision 425f126a0f2284423f4ccea0b00fbd5ea670a6c9
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.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.util.AttributeSet;
51import android.util.FloatProperty;
52import android.util.LocaleUtil;
53import android.util.Log;
54import android.util.Pool;
55import android.util.Poolable;
56import android.util.PoolableManager;
57import android.util.Pools;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.widget.ScrollBarDrawable;
78
79import static android.os.Build.VERSION_CODES.*;
80import static java.lang.Math.max;
81
82import com.android.internal.R;
83import com.android.internal.util.Predicate;
84import com.android.internal.view.menu.MenuBuilder;
85
86import java.lang.ref.WeakReference;
87import java.lang.reflect.InvocationTargetException;
88import java.lang.reflect.Method;
89import java.util.ArrayList;
90import java.util.Arrays;
91import java.util.Locale;
92import java.util.concurrent.CopyOnWriteArrayList;
93
94/**
95 * <p>
96 * This class represents the basic building block for user interface components. A View
97 * occupies a rectangular area on the screen and is responsible for drawing and
98 * event handling. View is the base class for <em>widgets</em>, which are
99 * used to create interactive UI components (buttons, text fields, etc.). The
100 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
101 * are invisible containers that hold other Views (or other ViewGroups) and define
102 * their layout properties.
103 * </p>
104 *
105 * <div class="special reference">
106 * <h3>Developer Guides</h3>
107 * <p>For information about using this class to develop your application's user interface,
108 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
347 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
349 * {@link #getPaddingEnd()}.
350 * </p>
351 *
352 * <p>
353 * Even though a view can define a padding, it does not provide any support for
354 * margins. However, view groups provide such a support. Refer to
355 * {@link android.view.ViewGroup} and
356 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
357 * </p>
358 *
359 * <a name="Layout"></a>
360 * <h3>Layout</h3>
361 * <p>
362 * Layout is a two pass process: a measure pass and a layout pass. The measuring
363 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
364 * of the view tree. Each view pushes dimension specifications down the tree
365 * during the recursion. At the end of the measure pass, every view has stored
366 * its measurements. The second pass happens in
367 * {@link #layout(int,int,int,int)} and is also top-down. During
368 * this pass each parent is responsible for positioning all of its children
369 * using the sizes computed in the measure pass.
370 * </p>
371 *
372 * <p>
373 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
374 * {@link #getMeasuredHeight()} values must be set, along with those for all of
375 * that view's descendants. A view's measured width and measured height values
376 * must respect the constraints imposed by the view's parents. This guarantees
377 * that at the end of the measure pass, all parents accept all of their
378 * children's measurements. A parent view may call measure() more than once on
379 * its children. For example, the parent may measure each child once with
380 * unspecified dimensions to find out how big they want to be, then call
381 * measure() on them again with actual numbers if the sum of all the children's
382 * unconstrained sizes is too big or too small.
383 * </p>
384 *
385 * <p>
386 * The measure pass uses two classes to communicate dimensions. The
387 * {@link MeasureSpec} class is used by views to tell their parents how they
388 * want to be measured and positioned. The base LayoutParams class just
389 * describes how big the view wants to be for both width and height. For each
390 * dimension, it can specify one of:
391 * <ul>
392 * <li> an exact number
393 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
394 * (minus padding)
395 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
396 * enclose its content (plus padding).
397 * </ul>
398 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
399 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
400 * an X and Y value.
401 * </p>
402 *
403 * <p>
404 * MeasureSpecs are used to push requirements down the tree from parent to
405 * child. A MeasureSpec can be in one of three modes:
406 * <ul>
407 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
408 * of a child view. For example, a LinearLayout may call measure() on its child
409 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
410 * tall the child view wants to be given a width of 240 pixels.
411 * <li>EXACTLY: This is used by the parent to impose an exact size on the
412 * child. The child must use this size, and guarantee that all of its
413 * descendants will fit within this size.
414 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
415 * child. The child must gurantee that it and all of its descendants will fit
416 * within this size.
417 * </ul>
418 * </p>
419 *
420 * <p>
421 * To intiate a layout, call {@link #requestLayout}. This method is typically
422 * called by a view on itself when it believes that is can no longer fit within
423 * its current bounds.
424 * </p>
425 *
426 * <a name="Drawing"></a>
427 * <h3>Drawing</h3>
428 * <p>
429 * Drawing is handled by walking the tree and rendering each view that
430 * intersects the invalid region. Because the tree is traversed in-order,
431 * this means that parents will draw before (i.e., behind) their children, with
432 * siblings drawn in the order they appear in the tree.
433 * If you set a background drawable for a View, then the View will draw it for you
434 * before calling back to its <code>onDraw()</code> method.
435 * </p>
436 *
437 * <p>
438 * Note that the framework will not draw views that are not in the invalid region.
439 * </p>
440 *
441 * <p>
442 * To force a view to draw, call {@link #invalidate()}.
443 * </p>
444 *
445 * <a name="EventHandlingThreading"></a>
446 * <h3>Event Handling and Threading</h3>
447 * <p>
448 * The basic cycle of a view is as follows:
449 * <ol>
450 * <li>An event comes in and is dispatched to the appropriate view. The view
451 * handles the event and notifies any listeners.</li>
452 * <li>If in the course of processing the event, the view's bounds may need
453 * to be changed, the view will call {@link #requestLayout()}.</li>
454 * <li>Similarly, if in the course of processing the event the view's appearance
455 * may need to be changed, the view will call {@link #invalidate()}.</li>
456 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
457 * the framework will take care of measuring, laying out, and drawing the tree
458 * as appropriate.</li>
459 * </ol>
460 * </p>
461 *
462 * <p><em>Note: The entire view tree is single threaded. You must always be on
463 * the UI thread when calling any method on any view.</em>
464 * If you are doing work on other threads and want to update the state of a view
465 * from that thread, you should use a {@link Handler}.
466 * </p>
467 *
468 * <a name="FocusHandling"></a>
469 * <h3>Focus Handling</h3>
470 * <p>
471 * The framework will handle routine focus movement in response to user input.
472 * This includes changing the focus as views are removed or hidden, or as new
473 * views become available. Views indicate their willingness to take focus
474 * through the {@link #isFocusable} method. To change whether a view can take
475 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
476 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
477 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
478 * </p>
479 * <p>
480 * Focus movement is based on an algorithm which finds the nearest neighbor in a
481 * given direction. In rare cases, the default algorithm may not match the
482 * intended behavior of the developer. In these situations, you can provide
483 * explicit overrides by using these XML attributes in the layout file:
484 * <pre>
485 * nextFocusDown
486 * nextFocusLeft
487 * nextFocusRight
488 * nextFocusUp
489 * </pre>
490 * </p>
491 *
492 *
493 * <p>
494 * To get a particular view to take focus, call {@link #requestFocus()}.
495 * </p>
496 *
497 * <a name="TouchMode"></a>
498 * <h3>Touch Mode</h3>
499 * <p>
500 * When a user is navigating a user interface via directional keys such as a D-pad, it is
501 * necessary to give focus to actionable items such as buttons so the user can see
502 * what will take input.  If the device has touch capabilities, however, and the user
503 * begins interacting with the interface by touching it, it is no longer necessary to
504 * always highlight, or give focus to, a particular view.  This motivates a mode
505 * for interaction named 'touch mode'.
506 * </p>
507 * <p>
508 * For a touch capable device, once the user touches the screen, the device
509 * will enter touch mode.  From this point onward, only views for which
510 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
511 * Other views that are touchable, like buttons, will not take focus when touched; they will
512 * only fire the on click listeners.
513 * </p>
514 * <p>
515 * Any time a user hits a directional key, such as a D-pad direction, the view device will
516 * exit touch mode, and find a view to take focus, so that the user may resume interacting
517 * with the user interface without touching the screen again.
518 * </p>
519 * <p>
520 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
521 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
522 * </p>
523 *
524 * <a name="Scrolling"></a>
525 * <h3>Scrolling</h3>
526 * <p>
527 * The framework provides basic support for views that wish to internally
528 * scroll their content. This includes keeping track of the X and Y scroll
529 * offset as well as mechanisms for drawing scrollbars. See
530 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
531 * {@link #awakenScrollBars()} for more details.
532 * </p>
533 *
534 * <a name="Tags"></a>
535 * <h3>Tags</h3>
536 * <p>
537 * Unlike IDs, tags are not used to identify views. Tags are essentially an
538 * extra piece of information that can be associated with a view. They are most
539 * often used as a convenience to store data related to views in the views
540 * themselves rather than by putting them in a separate structure.
541 * </p>
542 *
543 * <a name="Properties"></a>
544 * <h3>Properties</h3>
545 * <p>
546 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
547 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
548 * available both in the {@link Property} form as well as in similarly-named setter/getter
549 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
550 * be used to set persistent state associated with these rendering-related properties on the view.
551 * The properties and methods can also be used in conjunction with
552 * {@link android.animation.Animator Animator}-based animations, described more in the
553 * <a href="#Animation">Animation</a> section.
554 * </p>
555 *
556 * <a name="Animation"></a>
557 * <h3>Animation</h3>
558 * <p>
559 * Starting with Android 3.0, the preferred way of animating views is to use the
560 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
561 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
562 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
563 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
564 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
565 * makes animating these View properties particularly easy and efficient.
566 * </p>
567 * <p>
568 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
569 * You can attach an {@link Animation} object to a view using
570 * {@link #setAnimation(Animation)} or
571 * {@link #startAnimation(Animation)}. The animation can alter the scale,
572 * rotation, translation and alpha of a view over time. If the animation is
573 * attached to a view that has children, the animation will affect the entire
574 * subtree rooted by that node. When an animation is started, the framework will
575 * take care of redrawing the appropriate views until the animation completes.
576 * </p>
577 *
578 * <a name="Security"></a>
579 * <h3>Security</h3>
580 * <p>
581 * Sometimes it is essential that an application be able to verify that an action
582 * is being performed with the full knowledge and consent of the user, such as
583 * granting a permission request, making a purchase or clicking on an advertisement.
584 * Unfortunately, a malicious application could try to spoof the user into
585 * performing these actions, unaware, by concealing the intended purpose of the view.
586 * As a remedy, the framework offers a touch filtering mechanism that can be used to
587 * improve the security of views that provide access to sensitive functionality.
588 * </p><p>
589 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
590 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
591 * will discard touches that are received whenever the view's window is obscured by
592 * another visible window.  As a result, the view will not receive touches whenever a
593 * toast, dialog or other window appears above the view's window.
594 * </p><p>
595 * For more fine-grained control over security, consider overriding the
596 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
597 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
598 * </p>
599 *
600 * @attr ref android.R.styleable#View_alpha
601 * @attr ref android.R.styleable#View_background
602 * @attr ref android.R.styleable#View_clickable
603 * @attr ref android.R.styleable#View_contentDescription
604 * @attr ref android.R.styleable#View_drawingCacheQuality
605 * @attr ref android.R.styleable#View_duplicateParentState
606 * @attr ref android.R.styleable#View_id
607 * @attr ref android.R.styleable#View_requiresFadingEdge
608 * @attr ref android.R.styleable#View_fadeScrollbars
609 * @attr ref android.R.styleable#View_fadingEdgeLength
610 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
611 * @attr ref android.R.styleable#View_fitsSystemWindows
612 * @attr ref android.R.styleable#View_isScrollContainer
613 * @attr ref android.R.styleable#View_focusable
614 * @attr ref android.R.styleable#View_focusableInTouchMode
615 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
616 * @attr ref android.R.styleable#View_keepScreenOn
617 * @attr ref android.R.styleable#View_layerType
618 * @attr ref android.R.styleable#View_longClickable
619 * @attr ref android.R.styleable#View_minHeight
620 * @attr ref android.R.styleable#View_minWidth
621 * @attr ref android.R.styleable#View_nextFocusDown
622 * @attr ref android.R.styleable#View_nextFocusLeft
623 * @attr ref android.R.styleable#View_nextFocusRight
624 * @attr ref android.R.styleable#View_nextFocusUp
625 * @attr ref android.R.styleable#View_onClick
626 * @attr ref android.R.styleable#View_padding
627 * @attr ref android.R.styleable#View_paddingBottom
628 * @attr ref android.R.styleable#View_paddingLeft
629 * @attr ref android.R.styleable#View_paddingRight
630 * @attr ref android.R.styleable#View_paddingTop
631 * @attr ref android.R.styleable#View_paddingStart
632 * @attr ref android.R.styleable#View_paddingEnd
633 * @attr ref android.R.styleable#View_saveEnabled
634 * @attr ref android.R.styleable#View_rotation
635 * @attr ref android.R.styleable#View_rotationX
636 * @attr ref android.R.styleable#View_rotationY
637 * @attr ref android.R.styleable#View_scaleX
638 * @attr ref android.R.styleable#View_scaleY
639 * @attr ref android.R.styleable#View_scrollX
640 * @attr ref android.R.styleable#View_scrollY
641 * @attr ref android.R.styleable#View_scrollbarSize
642 * @attr ref android.R.styleable#View_scrollbarStyle
643 * @attr ref android.R.styleable#View_scrollbars
644 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
645 * @attr ref android.R.styleable#View_scrollbarFadeDuration
646 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
647 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
648 * @attr ref android.R.styleable#View_scrollbarThumbVertical
649 * @attr ref android.R.styleable#View_scrollbarTrackVertical
650 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
651 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
652 * @attr ref android.R.styleable#View_soundEffectsEnabled
653 * @attr ref android.R.styleable#View_tag
654 * @attr ref android.R.styleable#View_textAlignment
655 * @attr ref android.R.styleable#View_transformPivotX
656 * @attr ref android.R.styleable#View_transformPivotY
657 * @attr ref android.R.styleable#View_translationX
658 * @attr ref android.R.styleable#View_translationY
659 * @attr ref android.R.styleable#View_visibility
660 *
661 * @see android.view.ViewGroup
662 */
663public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
664        AccessibilityEventSource {
665    private static final boolean DBG = false;
666
667    /**
668     * The logging tag used by this class with android.util.Log.
669     */
670    protected static final String VIEW_LOG_TAG = "View";
671
672    /**
673     * When set to true, apps will draw debugging information about their layouts.
674     *
675     * @hide
676     */
677    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
678
679    /**
680     * Used to mark a View that has no ID.
681     */
682    public static final int NO_ID = -1;
683
684    /**
685     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
686     * calling setFlags.
687     */
688    private static final int NOT_FOCUSABLE = 0x00000000;
689
690    /**
691     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
692     * setFlags.
693     */
694    private static final int FOCUSABLE = 0x00000001;
695
696    /**
697     * Mask for use with setFlags indicating bits used for focus.
698     */
699    private static final int FOCUSABLE_MASK = 0x00000001;
700
701    /**
702     * This view will adjust its padding to fit sytem windows (e.g. status bar)
703     */
704    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
705
706    /**
707     * This view is visible.
708     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
709     * android:visibility}.
710     */
711    public static final int VISIBLE = 0x00000000;
712
713    /**
714     * This view is invisible, but it still takes up space for layout purposes.
715     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
716     * android:visibility}.
717     */
718    public static final int INVISIBLE = 0x00000004;
719
720    /**
721     * This view is invisible, and it doesn't take any space for layout
722     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
723     * android:visibility}.
724     */
725    public static final int GONE = 0x00000008;
726
727    /**
728     * Mask for use with setFlags indicating bits used for visibility.
729     * {@hide}
730     */
731    static final int VISIBILITY_MASK = 0x0000000C;
732
733    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
734
735    /**
736     * This view is enabled. Interpretation varies by subclass.
737     * Use with ENABLED_MASK when calling setFlags.
738     * {@hide}
739     */
740    static final int ENABLED = 0x00000000;
741
742    /**
743     * This view is disabled. Interpretation varies by subclass.
744     * Use with ENABLED_MASK when calling setFlags.
745     * {@hide}
746     */
747    static final int DISABLED = 0x00000020;
748
749   /**
750    * Mask for use with setFlags indicating bits used for indicating whether
751    * this view is enabled
752    * {@hide}
753    */
754    static final int ENABLED_MASK = 0x00000020;
755
756    /**
757     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
758     * called and further optimizations will be performed. It is okay to have
759     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
760     * {@hide}
761     */
762    static final int WILL_NOT_DRAW = 0x00000080;
763
764    /**
765     * Mask for use with setFlags indicating bits used for indicating whether
766     * this view is will draw
767     * {@hide}
768     */
769    static final int DRAW_MASK = 0x00000080;
770
771    /**
772     * <p>This view doesn't show scrollbars.</p>
773     * {@hide}
774     */
775    static final int SCROLLBARS_NONE = 0x00000000;
776
777    /**
778     * <p>This view shows horizontal scrollbars.</p>
779     * {@hide}
780     */
781    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
782
783    /**
784     * <p>This view shows vertical scrollbars.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_VERTICAL = 0x00000200;
788
789    /**
790     * <p>Mask for use with setFlags indicating bits used for indicating which
791     * scrollbars are enabled.</p>
792     * {@hide}
793     */
794    static final int SCROLLBARS_MASK = 0x00000300;
795
796    /**
797     * Indicates that the view should filter touches when its window is obscured.
798     * Refer to the class comments for more information about this security feature.
799     * {@hide}
800     */
801    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
802
803    /**
804     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
805     * that they are optional and should be skipped if the window has
806     * requested system UI flags that ignore those insets for layout.
807     */
808    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
809
810    /**
811     * <p>This view doesn't show fading edges.</p>
812     * {@hide}
813     */
814    static final int FADING_EDGE_NONE = 0x00000000;
815
816    /**
817     * <p>This view shows horizontal fading edges.</p>
818     * {@hide}
819     */
820    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
821
822    /**
823     * <p>This view shows vertical fading edges.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_VERTICAL = 0x00002000;
827
828    /**
829     * <p>Mask for use with setFlags indicating bits used for indicating which
830     * fading edges are enabled.</p>
831     * {@hide}
832     */
833    static final int FADING_EDGE_MASK = 0x00003000;
834
835    /**
836     * <p>Indicates this view can be clicked. When clickable, a View reacts
837     * to clicks by notifying the OnClickListener.<p>
838     * {@hide}
839     */
840    static final int CLICKABLE = 0x00004000;
841
842    /**
843     * <p>Indicates this view is caching its drawing into a bitmap.</p>
844     * {@hide}
845     */
846    static final int DRAWING_CACHE_ENABLED = 0x00008000;
847
848    /**
849     * <p>Indicates that no icicle should be saved for this view.<p>
850     * {@hide}
851     */
852    static final int SAVE_DISABLED = 0x000010000;
853
854    /**
855     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
856     * property.</p>
857     * {@hide}
858     */
859    static final int SAVE_DISABLED_MASK = 0x000010000;
860
861    /**
862     * <p>Indicates that no drawing cache should ever be created for this view.<p>
863     * {@hide}
864     */
865    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
866
867    /**
868     * <p>Indicates this view can take / keep focus when int touch mode.</p>
869     * {@hide}
870     */
871    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
872
873    /**
874     * <p>Enables low quality mode for the drawing cache.</p>
875     */
876    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
877
878    /**
879     * <p>Enables high quality mode for the drawing cache.</p>
880     */
881    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
882
883    /**
884     * <p>Enables automatic quality mode for the drawing cache.</p>
885     */
886    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
887
888    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
889            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
890    };
891
892    /**
893     * <p>Mask for use with setFlags indicating bits used for the cache
894     * quality property.</p>
895     * {@hide}
896     */
897    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
898
899    /**
900     * <p>
901     * Indicates this view can be long clicked. When long clickable, a View
902     * reacts to long clicks by notifying the OnLongClickListener or showing a
903     * context menu.
904     * </p>
905     * {@hide}
906     */
907    static final int LONG_CLICKABLE = 0x00200000;
908
909    /**
910     * <p>Indicates that this view gets its drawable states from its direct parent
911     * and ignores its original internal states.</p>
912     *
913     * @hide
914     */
915    static final int DUPLICATE_PARENT_STATE = 0x00400000;
916
917    /**
918     * The scrollbar style to display the scrollbars inside the content area,
919     * without increasing the padding. The scrollbars will be overlaid with
920     * translucency on the view's content.
921     */
922    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
923
924    /**
925     * The scrollbar style to display the scrollbars inside the padded area,
926     * increasing the padding of the view. The scrollbars will not overlap the
927     * content area of the view.
928     */
929    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
930
931    /**
932     * The scrollbar style to display the scrollbars at the edge of the view,
933     * without increasing the padding. The scrollbars will be overlaid with
934     * translucency.
935     */
936    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
937
938    /**
939     * The scrollbar style to display the scrollbars at the edge of the view,
940     * increasing the padding of the view. The scrollbars will only overlap the
941     * background, if any.
942     */
943    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
944
945    /**
946     * Mask to check if the scrollbar style is overlay or inset.
947     * {@hide}
948     */
949    static final int SCROLLBARS_INSET_MASK = 0x01000000;
950
951    /**
952     * Mask to check if the scrollbar style is inside or outside.
953     * {@hide}
954     */
955    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
956
957    /**
958     * Mask for scrollbar style.
959     * {@hide}
960     */
961    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
962
963    /**
964     * View flag indicating that the screen should remain on while the
965     * window containing this view is visible to the user.  This effectively
966     * takes care of automatically setting the WindowManager's
967     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
968     */
969    public static final int KEEP_SCREEN_ON = 0x04000000;
970
971    /**
972     * View flag indicating whether this view should have sound effects enabled
973     * for events such as clicking and touching.
974     */
975    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
976
977    /**
978     * View flag indicating whether this view should have haptic feedback
979     * enabled for events such as long presses.
980     */
981    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
982
983    /**
984     * <p>Indicates that the view hierarchy should stop saving state when
985     * it reaches this view.  If state saving is initiated immediately at
986     * the view, it will be allowed.
987     * {@hide}
988     */
989    static final int PARENT_SAVE_DISABLED = 0x20000000;
990
991    /**
992     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
993     * {@hide}
994     */
995    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
996
997    /**
998     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
999     * should add all focusable Views regardless if they are focusable in touch mode.
1000     */
1001    public static final int FOCUSABLES_ALL = 0x00000000;
1002
1003    /**
1004     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1005     * should add only Views focusable in touch mode.
1006     */
1007    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add only accessibility focusable Views.
1012     *
1013     * @hide
1014     */
1015    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1016
1017    /**
1018     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1019     * item.
1020     */
1021    public static final int FOCUS_BACKWARD = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1025     * item.
1026     */
1027    public static final int FOCUS_FORWARD = 0x00000002;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the left.
1031     */
1032    public static final int FOCUS_LEFT = 0x00000011;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus up.
1036     */
1037    public static final int FOCUS_UP = 0x00000021;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus to the right.
1041     */
1042    public static final int FOCUS_RIGHT = 0x00000042;
1043
1044    /**
1045     * Use with {@link #focusSearch(int)}. Move focus down.
1046     */
1047    public static final int FOCUS_DOWN = 0x00000082;
1048
1049    // Accessibility focus directions.
1050
1051    /**
1052     * The accessibility focus which is the current user position when
1053     * interacting with the accessibility framework.
1054     */
1055    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1056
1057    /**
1058     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1059     */
1060    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1061
1062    /**
1063     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1064     */
1065    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1066
1067    /**
1068     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1069     */
1070    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1071
1072    /**
1073     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1074     */
1075    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1076
1077    /**
1078     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1079     */
1080    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1081
1082    /**
1083     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1084     */
1085    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1086
1087    /**
1088     * Bits of {@link #getMeasuredWidthAndState()} and
1089     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1090     */
1091    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1092
1093    /**
1094     * Bits of {@link #getMeasuredWidthAndState()} and
1095     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1096     */
1097    public static final int MEASURED_STATE_MASK = 0xff000000;
1098
1099    /**
1100     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1101     * for functions that combine both width and height into a single int,
1102     * such as {@link #getMeasuredState()} and the childState argument of
1103     * {@link #resolveSizeAndState(int, int, int)}.
1104     */
1105    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1106
1107    /**
1108     * Bit of {@link #getMeasuredWidthAndState()} and
1109     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1110     * is smaller that the space the view would like to have.
1111     */
1112    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1113
1114    /**
1115     * Base View state sets
1116     */
1117    // Singles
1118    /**
1119     * Indicates the view has no states set. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     */
1126    protected static final int[] EMPTY_STATE_SET;
1127    /**
1128     * Indicates the view is enabled. States are used with
1129     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1130     * view depending on its state.
1131     *
1132     * @see android.graphics.drawable.Drawable
1133     * @see #getDrawableState()
1134     */
1135    protected static final int[] ENABLED_STATE_SET;
1136    /**
1137     * Indicates the view is focused. States are used with
1138     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1139     * view depending on its state.
1140     *
1141     * @see android.graphics.drawable.Drawable
1142     * @see #getDrawableState()
1143     */
1144    protected static final int[] FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is selected. States are used with
1147     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1148     * view depending on its state.
1149     *
1150     * @see android.graphics.drawable.Drawable
1151     * @see #getDrawableState()
1152     */
1153    protected static final int[] SELECTED_STATE_SET;
1154    /**
1155     * Indicates the view is pressed. States are used with
1156     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1157     * view depending on its state.
1158     *
1159     * @see android.graphics.drawable.Drawable
1160     * @see #getDrawableState()
1161     * @hide
1162     */
1163    protected static final int[] PRESSED_STATE_SET;
1164    /**
1165     * Indicates the view's window has focus. States are used with
1166     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1167     * view depending on its state.
1168     *
1169     * @see android.graphics.drawable.Drawable
1170     * @see #getDrawableState()
1171     */
1172    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1173    // Doubles
1174    /**
1175     * Indicates the view is enabled and has the focus.
1176     *
1177     * @see #ENABLED_STATE_SET
1178     * @see #FOCUSED_STATE_SET
1179     */
1180    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1181    /**
1182     * Indicates the view is enabled and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #SELECTED_STATE_SET
1186     */
1187    protected static final int[] ENABLED_SELECTED_STATE_SET;
1188    /**
1189     * Indicates the view is enabled and that its window has focus.
1190     *
1191     * @see #ENABLED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is focused and selected.
1197     *
1198     * @see #FOCUSED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     */
1201    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1202    /**
1203     * Indicates the view has the focus and that its window has the focus.
1204     *
1205     * @see #FOCUSED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is selected and that its window has the focus.
1211     *
1212     * @see #SELECTED_STATE_SET
1213     * @see #WINDOW_FOCUSED_STATE_SET
1214     */
1215    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1216    // Triples
1217    /**
1218     * Indicates the view is enabled, focused and selected.
1219     *
1220     * @see #ENABLED_STATE_SET
1221     * @see #FOCUSED_STATE_SET
1222     * @see #SELECTED_STATE_SET
1223     */
1224    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1225    /**
1226     * Indicates the view is enabled, focused and its window has the focus.
1227     *
1228     * @see #ENABLED_STATE_SET
1229     * @see #FOCUSED_STATE_SET
1230     * @see #WINDOW_FOCUSED_STATE_SET
1231     */
1232    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1233    /**
1234     * Indicates the view is enabled, selected and its window has the focus.
1235     *
1236     * @see #ENABLED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is focused, selected and its window has the focus.
1243     *
1244     * @see #FOCUSED_STATE_SET
1245     * @see #SELECTED_STATE_SET
1246     * @see #WINDOW_FOCUSED_STATE_SET
1247     */
1248    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1249    /**
1250     * Indicates the view is enabled, focused, selected and its window
1251     * has the focus.
1252     *
1253     * @see #ENABLED_STATE_SET
1254     * @see #FOCUSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed and its window has the focus.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #WINDOW_FOCUSED_STATE_SET
1264     */
1265    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1266    /**
1267     * Indicates the view is pressed and selected.
1268     *
1269     * @see #PRESSED_STATE_SET
1270     * @see #SELECTED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_SELECTED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed, selected and its window has the focus.
1275     *
1276     * @see #PRESSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is pressed and focused.
1283     *
1284     * @see #PRESSED_STATE_SET
1285     * @see #FOCUSED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, focused and its window has the focus.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #FOCUSED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, focused and selected.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, focused, selected and its window has the focus.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #FOCUSED_STATE_SET
1309     * @see #SELECTED_STATE_SET
1310     * @see #WINDOW_FOCUSED_STATE_SET
1311     */
1312    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1313    /**
1314     * Indicates the view is pressed and enabled.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #ENABLED_STATE_SET
1318     */
1319    protected static final int[] PRESSED_ENABLED_STATE_SET;
1320    /**
1321     * Indicates the view is pressed, enabled and its window has the focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     */
1335    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1336    /**
1337     * Indicates the view is pressed, enabled, selected and its window has the
1338     * focus.
1339     *
1340     * @see #PRESSED_STATE_SET
1341     * @see #ENABLED_STATE_SET
1342     * @see #SELECTED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed, enabled and focused.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #ENABLED_STATE_SET
1351     * @see #FOCUSED_STATE_SET
1352     */
1353    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1354    /**
1355     * Indicates the view is pressed, enabled, focused and its window has the
1356     * focus.
1357     *
1358     * @see #PRESSED_STATE_SET
1359     * @see #ENABLED_STATE_SET
1360     * @see #FOCUSED_STATE_SET
1361     * @see #WINDOW_FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled, focused and selected.
1366     *
1367     * @see #PRESSED_STATE_SET
1368     * @see #ENABLED_STATE_SET
1369     * @see #SELECTED_STATE_SET
1370     * @see #FOCUSED_STATE_SET
1371     */
1372    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1373    /**
1374     * Indicates the view is pressed, enabled, focused, selected and its window
1375     * has the focus.
1376     *
1377     * @see #PRESSED_STATE_SET
1378     * @see #ENABLED_STATE_SET
1379     * @see #SELECTED_STATE_SET
1380     * @see #FOCUSED_STATE_SET
1381     * @see #WINDOW_FOCUSED_STATE_SET
1382     */
1383    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1384
1385    /**
1386     * The order here is very important to {@link #getDrawableState()}
1387     */
1388    private static final int[][] VIEW_STATE_SETS;
1389
1390    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1391    static final int VIEW_STATE_SELECTED = 1 << 1;
1392    static final int VIEW_STATE_FOCUSED = 1 << 2;
1393    static final int VIEW_STATE_ENABLED = 1 << 3;
1394    static final int VIEW_STATE_PRESSED = 1 << 4;
1395    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1396    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1397    static final int VIEW_STATE_HOVERED = 1 << 7;
1398    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1399    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1400
1401    static final int[] VIEW_STATE_IDS = new int[] {
1402        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1403        R.attr.state_selected,          VIEW_STATE_SELECTED,
1404        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1405        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1406        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1407        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1408        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1409        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1410        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1411        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1412    };
1413
1414    static {
1415        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1416            throw new IllegalStateException(
1417                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1418        }
1419        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1420        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1421            int viewState = R.styleable.ViewDrawableStates[i];
1422            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1423                if (VIEW_STATE_IDS[j] == viewState) {
1424                    orderedIds[i * 2] = viewState;
1425                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1426                }
1427            }
1428        }
1429        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1430        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1431        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1432            int numBits = Integer.bitCount(i);
1433            int[] set = new int[numBits];
1434            int pos = 0;
1435            for (int j = 0; j < orderedIds.length; j += 2) {
1436                if ((i & orderedIds[j+1]) != 0) {
1437                    set[pos++] = orderedIds[j];
1438                }
1439            }
1440            VIEW_STATE_SETS[i] = set;
1441        }
1442
1443        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1444        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1445        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1446        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1448        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1449        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1451        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1453        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1455                | VIEW_STATE_FOCUSED];
1456        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1457        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1459        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1461        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1463                | VIEW_STATE_ENABLED];
1464        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1466        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED];
1469        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED];
1472        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1475
1476        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1477        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1479        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1481        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1483                | VIEW_STATE_PRESSED];
1484        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1485                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1486        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1488                | VIEW_STATE_PRESSED];
1489        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1491                | VIEW_STATE_PRESSED];
1492        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1494                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1495        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1497        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1499                | VIEW_STATE_PRESSED];
1500        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1502                | VIEW_STATE_PRESSED];
1503        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1505                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1506        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1508                | VIEW_STATE_PRESSED];
1509        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1511                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1512        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1514                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1515        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1516                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1517                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1518                | VIEW_STATE_PRESSED];
1519    }
1520
1521    /**
1522     * Accessibility event types that are dispatched for text population.
1523     */
1524    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1525            AccessibilityEvent.TYPE_VIEW_CLICKED
1526            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1527            | AccessibilityEvent.TYPE_VIEW_SELECTED
1528            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1529            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1531            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1532            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1533            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1534            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1535            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1536
1537    /**
1538     * Temporary Rect currently for use in setBackground().  This will probably
1539     * be extended in the future to hold our own class with more than just
1540     * a Rect. :)
1541     */
1542    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1543
1544    /**
1545     * Map used to store views' tags.
1546     */
1547    private SparseArray<Object> mKeyedTags;
1548
1549    /**
1550     * The next available accessiiblity id.
1551     */
1552    private static int sNextAccessibilityViewId;
1553
1554    /**
1555     * The animation currently associated with this view.
1556     * @hide
1557     */
1558    protected Animation mCurrentAnimation = null;
1559
1560    /**
1561     * Width as measured during measure pass.
1562     * {@hide}
1563     */
1564    @ViewDebug.ExportedProperty(category = "measurement")
1565    int mMeasuredWidth;
1566
1567    /**
1568     * Height as measured during measure pass.
1569     * {@hide}
1570     */
1571    @ViewDebug.ExportedProperty(category = "measurement")
1572    int mMeasuredHeight;
1573
1574    /**
1575     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1576     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1577     * its display list. This flag, used only when hw accelerated, allows us to clear the
1578     * flag while retaining this information until it's needed (at getDisplayList() time and
1579     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1580     *
1581     * {@hide}
1582     */
1583    boolean mRecreateDisplayList = false;
1584
1585    /**
1586     * The view's identifier.
1587     * {@hide}
1588     *
1589     * @see #setId(int)
1590     * @see #getId()
1591     */
1592    @ViewDebug.ExportedProperty(resolveId = true)
1593    int mID = NO_ID;
1594
1595    /**
1596     * The stable ID of this view for accessibility purposes.
1597     */
1598    int mAccessibilityViewId = NO_ID;
1599
1600    /**
1601     * @hide
1602     */
1603    private int mAccessibilityCursorPosition = -1;
1604
1605    /**
1606     * The view's tag.
1607     * {@hide}
1608     *
1609     * @see #setTag(Object)
1610     * @see #getTag()
1611     */
1612    protected Object mTag;
1613
1614    // for mPrivateFlags:
1615    /** {@hide} */
1616    static final int WANTS_FOCUS                    = 0x00000001;
1617    /** {@hide} */
1618    static final int FOCUSED                        = 0x00000002;
1619    /** {@hide} */
1620    static final int SELECTED                       = 0x00000004;
1621    /** {@hide} */
1622    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1623    /** {@hide} */
1624    static final int HAS_BOUNDS                     = 0x00000010;
1625    /** {@hide} */
1626    static final int DRAWN                          = 0x00000020;
1627    /**
1628     * When this flag is set, this view is running an animation on behalf of its
1629     * children and should therefore not cancel invalidate requests, even if they
1630     * lie outside of this view's bounds.
1631     *
1632     * {@hide}
1633     */
1634    static final int DRAW_ANIMATION                 = 0x00000040;
1635    /** {@hide} */
1636    static final int SKIP_DRAW                      = 0x00000080;
1637    /** {@hide} */
1638    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1639    /** {@hide} */
1640    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1641    /** {@hide} */
1642    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1643    /** {@hide} */
1644    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1645    /** {@hide} */
1646    static final int FORCE_LAYOUT                   = 0x00001000;
1647    /** {@hide} */
1648    static final int LAYOUT_REQUIRED                = 0x00002000;
1649
1650    private static final int PRESSED                = 0x00004000;
1651
1652    /** {@hide} */
1653    static final int DRAWING_CACHE_VALID            = 0x00008000;
1654    /**
1655     * Flag used to indicate that this view should be drawn once more (and only once
1656     * more) after its animation has completed.
1657     * {@hide}
1658     */
1659    static final int ANIMATION_STARTED              = 0x00010000;
1660
1661    private static final int SAVE_STATE_CALLED      = 0x00020000;
1662
1663    /**
1664     * Indicates that the View returned true when onSetAlpha() was called and that
1665     * the alpha must be restored.
1666     * {@hide}
1667     */
1668    static final int ALPHA_SET                      = 0x00040000;
1669
1670    /**
1671     * Set by {@link #setScrollContainer(boolean)}.
1672     */
1673    static final int SCROLL_CONTAINER               = 0x00080000;
1674
1675    /**
1676     * Set by {@link #setScrollContainer(boolean)}.
1677     */
1678    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1679
1680    /**
1681     * View flag indicating whether this view was invalidated (fully or partially.)
1682     *
1683     * @hide
1684     */
1685    static final int DIRTY                          = 0x00200000;
1686
1687    /**
1688     * View flag indicating whether this view was invalidated by an opaque
1689     * invalidate request.
1690     *
1691     * @hide
1692     */
1693    static final int DIRTY_OPAQUE                   = 0x00400000;
1694
1695    /**
1696     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1697     *
1698     * @hide
1699     */
1700    static final int DIRTY_MASK                     = 0x00600000;
1701
1702    /**
1703     * Indicates whether the background is opaque.
1704     *
1705     * @hide
1706     */
1707    static final int OPAQUE_BACKGROUND              = 0x00800000;
1708
1709    /**
1710     * Indicates whether the scrollbars are opaque.
1711     *
1712     * @hide
1713     */
1714    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1715
1716    /**
1717     * Indicates whether the view is opaque.
1718     *
1719     * @hide
1720     */
1721    static final int OPAQUE_MASK                    = 0x01800000;
1722
1723    /**
1724     * Indicates a prepressed state;
1725     * the short time between ACTION_DOWN and recognizing
1726     * a 'real' press. Prepressed is used to recognize quick taps
1727     * even when they are shorter than ViewConfiguration.getTapTimeout().
1728     *
1729     * @hide
1730     */
1731    private static final int PREPRESSED             = 0x02000000;
1732
1733    /**
1734     * Indicates whether the view is temporarily detached.
1735     *
1736     * @hide
1737     */
1738    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1739
1740    /**
1741     * Indicates that we should awaken scroll bars once attached
1742     *
1743     * @hide
1744     */
1745    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1746
1747    /**
1748     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1749     * @hide
1750     */
1751    private static final int HOVERED              = 0x10000000;
1752
1753    /**
1754     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1755     * for transform operations
1756     *
1757     * @hide
1758     */
1759    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1760
1761    /** {@hide} */
1762    static final int ACTIVATED                    = 0x40000000;
1763
1764    /**
1765     * Indicates that this view was specifically invalidated, not just dirtied because some
1766     * child view was invalidated. The flag is used to determine when we need to recreate
1767     * a view's display list (as opposed to just returning a reference to its existing
1768     * display list).
1769     *
1770     * @hide
1771     */
1772    static final int INVALIDATED                  = 0x80000000;
1773
1774    /* Masks for mPrivateFlags2 */
1775
1776    /**
1777     * Indicates that this view has reported that it can accept the current drag's content.
1778     * Cleared when the drag operation concludes.
1779     * @hide
1780     */
1781    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1782
1783    /**
1784     * Indicates that this view is currently directly under the drag location in a
1785     * drag-and-drop operation involving content that it can accept.  Cleared when
1786     * the drag exits the view, or when the drag operation concludes.
1787     * @hide
1788     */
1789    static final int DRAG_HOVERED                 = 0x00000002;
1790
1791    /**
1792     * Horizontal layout direction of this view is from Left to Right.
1793     * Use with {@link #setLayoutDirection}.
1794     */
1795    public static final int LAYOUT_DIRECTION_LTR = 0;
1796
1797    /**
1798     * Horizontal layout direction of this view is from Right to Left.
1799     * Use with {@link #setLayoutDirection}.
1800     */
1801    public static final int LAYOUT_DIRECTION_RTL = 1;
1802
1803    /**
1804     * Horizontal layout direction of this view is inherited from its parent.
1805     * Use with {@link #setLayoutDirection}.
1806     */
1807    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1808
1809    /**
1810     * Horizontal layout direction of this view is from deduced from the default language
1811     * script for the locale. Use with {@link #setLayoutDirection}.
1812     */
1813    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1814
1815    /**
1816     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1817     * @hide
1818     */
1819    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1820
1821    /**
1822     * Mask for use with private flags indicating bits used for horizontal layout direction.
1823     * @hide
1824     */
1825    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1826
1827    /**
1828     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1829     * right-to-left direction.
1830     * @hide
1831     */
1832    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1833
1834    /**
1835     * Indicates whether the view horizontal layout direction has been resolved.
1836     * @hide
1837     */
1838    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1842     * @hide
1843     */
1844    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /*
1847     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1848     * flag value.
1849     * @hide
1850     */
1851    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1852            LAYOUT_DIRECTION_LTR,
1853            LAYOUT_DIRECTION_RTL,
1854            LAYOUT_DIRECTION_INHERIT,
1855            LAYOUT_DIRECTION_LOCALE
1856    };
1857
1858    /**
1859     * Default horizontal layout direction.
1860     * @hide
1861     */
1862    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1863
1864    /**
1865     * Indicates that the view is tracking some sort of transient state
1866     * that the app should not need to be aware of, but that the framework
1867     * should take special care to preserve.
1868     *
1869     * @hide
1870     */
1871    static final int HAS_TRANSIENT_STATE = 0x00000100;
1872
1873
1874    /**
1875     * Text direction is inherited thru {@link ViewGroup}
1876     */
1877    public static final int TEXT_DIRECTION_INHERIT = 0;
1878
1879    /**
1880     * Text direction is using "first strong algorithm". The first strong directional character
1881     * determines the paragraph direction. If there is no strong directional character, the
1882     * paragraph direction is the view's resolved layout direction.
1883     */
1884    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1885
1886    /**
1887     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1888     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1889     * If there are neither, the paragraph direction is the view's resolved layout direction.
1890     */
1891    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1892
1893    /**
1894     * Text direction is forced to LTR.
1895     */
1896    public static final int TEXT_DIRECTION_LTR = 3;
1897
1898    /**
1899     * Text direction is forced to RTL.
1900     */
1901    public static final int TEXT_DIRECTION_RTL = 4;
1902
1903    /**
1904     * Text direction is coming from the system Locale.
1905     */
1906    public static final int TEXT_DIRECTION_LOCALE = 5;
1907
1908    /**
1909     * Default text direction is inherited
1910     */
1911    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1912
1913    /**
1914     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1915     * @hide
1916     */
1917    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1918
1919    /**
1920     * Mask for use with private flags indicating bits used for text direction.
1921     * @hide
1922     */
1923    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1924
1925    /**
1926     * Array of text direction flags for mapping attribute "textDirection" to correct
1927     * flag value.
1928     * @hide
1929     */
1930    private static final int[] TEXT_DIRECTION_FLAGS = {
1931            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1932            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1933            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1934            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1935            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1936            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1937    };
1938
1939    /**
1940     * Indicates whether the view text direction has been resolved.
1941     * @hide
1942     */
1943    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1944
1945    /**
1946     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1947     * @hide
1948     */
1949    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1950
1951    /**
1952     * Mask for use with private flags indicating bits used for resolved text direction.
1953     * @hide
1954     */
1955    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1956
1957    /**
1958     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1959     * @hide
1960     */
1961    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1962            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1963
1964    /*
1965     * Default text alignment. The text alignment of this View is inherited from its parent.
1966     * Use with {@link #setTextAlignment(int)}
1967     */
1968    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1969
1970    /**
1971     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1972     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1973     *
1974     * Use with {@link #setTextAlignment(int)}
1975     */
1976    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1977
1978    /**
1979     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1980     *
1981     * Use with {@link #setTextAlignment(int)}
1982     */
1983    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1984
1985    /**
1986     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1987     *
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1991
1992    /**
1993     * Center the paragraph, e.g. ALIGN_CENTER.
1994     *
1995     * Use with {@link #setTextAlignment(int)}
1996     */
1997    public static final int TEXT_ALIGNMENT_CENTER = 4;
1998
1999    /**
2000     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2001     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2006
2007    /**
2008     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2009     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2010     *
2011     * Use with {@link #setTextAlignment(int)}
2012     */
2013    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2014
2015    /**
2016     * Default text alignment is inherited
2017     */
2018    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2019
2020    /**
2021      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2022      * @hide
2023      */
2024    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2025
2026    /**
2027      * Mask for use with private flags indicating bits used for text alignment.
2028      * @hide
2029      */
2030    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2031
2032    /**
2033     * Array of text direction flags for mapping attribute "textAlignment" to correct
2034     * flag value.
2035     * @hide
2036     */
2037    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2038            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2039            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2040            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2041            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2042            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2043            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2044            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2045    };
2046
2047    /**
2048     * Indicates whether the view text alignment has been resolved.
2049     * @hide
2050     */
2051    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2052
2053    /**
2054     * Bit shift to get the resolved text alignment.
2055     * @hide
2056     */
2057    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2058
2059    /**
2060     * Mask for use with private flags indicating bits used for text alignment.
2061     * @hide
2062     */
2063    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2064
2065    /**
2066     * Indicates whether if the view text alignment has been resolved to gravity
2067     */
2068    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2069            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2070
2071    // Accessiblity constants for mPrivateFlags2
2072
2073    /**
2074     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2075     */
2076    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2077
2078    /**
2079     * Automatically determine whether a view is important for accessibility.
2080     */
2081    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2082
2083    /**
2084     * The view is important for accessibility.
2085     */
2086    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2087
2088    /**
2089     * The view is not important for accessibility.
2090     */
2091    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2092
2093    /**
2094     * The default whether the view is important for accessiblity.
2095     */
2096    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2097
2098    /**
2099     * Mask for obtainig the bits which specify how to determine
2100     * whether a view is important for accessibility.
2101     */
2102    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2103        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2104        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2105
2106    /**
2107     * Flag indicating whether a view has accessibility focus.
2108     */
2109    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2110
2111    /**
2112     * Flag indicating whether a view state for accessibility has changed.
2113     */
2114    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2115
2116    /**
2117     * Flag indicating that view has an animation set on it. This is used to track whether an
2118     * animation is cleared between successive frames, in order to tell the associated
2119     * DisplayList to clear its animation matrix.
2120     */
2121    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x10000000;
2122
2123    /**
2124     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2125     * is used to check whether later changes to the view's transform should invalidate the
2126     * view to force the quickReject test to run again.
2127     */
2128    static final int VIEW_QUICK_REJECTED = 0x20000000;
2129
2130    /* End of masks for mPrivateFlags2 */
2131
2132    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2133
2134    /**
2135     * Always allow a user to over-scroll this view, provided it is a
2136     * view that can scroll.
2137     *
2138     * @see #getOverScrollMode()
2139     * @see #setOverScrollMode(int)
2140     */
2141    public static final int OVER_SCROLL_ALWAYS = 0;
2142
2143    /**
2144     * Allow a user to over-scroll this view only if the content is large
2145     * enough to meaningfully scroll, provided it is a view that can scroll.
2146     *
2147     * @see #getOverScrollMode()
2148     * @see #setOverScrollMode(int)
2149     */
2150    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2151
2152    /**
2153     * Never allow a user to over-scroll this view.
2154     *
2155     * @see #getOverScrollMode()
2156     * @see #setOverScrollMode(int)
2157     */
2158    public static final int OVER_SCROLL_NEVER = 2;
2159
2160    /**
2161     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2162     * requested the system UI (status bar) to be visible (the default).
2163     *
2164     * @see #setSystemUiVisibility(int)
2165     */
2166    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2167
2168    /**
2169     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2170     * system UI to enter an unobtrusive "low profile" mode.
2171     *
2172     * <p>This is for use in games, book readers, video players, or any other
2173     * "immersive" application where the usual system chrome is deemed too distracting.
2174     *
2175     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2176     *
2177     * @see #setSystemUiVisibility(int)
2178     */
2179    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2180
2181    /**
2182     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2183     * system navigation be temporarily hidden.
2184     *
2185     * <p>This is an even less obtrusive state than that called for by
2186     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2187     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2188     * those to disappear. This is useful (in conjunction with the
2189     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2190     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2191     * window flags) for displaying content using every last pixel on the display.
2192     *
2193     * <p>There is a limitation: because navigation controls are so important, the least user
2194     * interaction will cause them to reappear immediately.  When this happens, both
2195     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2196     * so that both elements reappear at the same time.
2197     *
2198     * @see #setSystemUiVisibility(int)
2199     */
2200    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2201
2202    /**
2203     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2204     * into the normal fullscreen mode so that its content can take over the screen
2205     * while still allowing the user to interact with the application.
2206     *
2207     * <p>This has the same visual effect as
2208     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2209     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2210     * meaning that non-critical screen decorations (such as the status bar) will be
2211     * hidden while the user is in the View's window, focusing the experience on
2212     * that content.  Unlike the window flag, if you are using ActionBar in
2213     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2214     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2215     * hide the action bar.
2216     *
2217     * <p>This approach to going fullscreen is best used over the window flag when
2218     * it is a transient state -- that is, the application does this at certain
2219     * points in its user interaction where it wants to allow the user to focus
2220     * on content, but not as a continuous state.  For situations where the application
2221     * would like to simply stay full screen the entire time (such as a game that
2222     * wants to take over the screen), the
2223     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2224     * is usually a better approach.  The state set here will be removed by the system
2225     * in various situations (such as the user moving to another application) like
2226     * the other system UI states.
2227     *
2228     * <p>When using this flag, the application should provide some easy facility
2229     * for the user to go out of it.  A common example would be in an e-book
2230     * reader, where tapping on the screen brings back whatever screen and UI
2231     * decorations that had been hidden while the user was immersed in reading
2232     * the book.
2233     *
2234     * @see #setSystemUiVisibility(int)
2235     */
2236    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2237
2238    /**
2239     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2240     * flags, we would like a stable view of the content insets given to
2241     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2242     * will always represent the worst case that the application can expect
2243     * as a continuous state.  In the stock Android UI this is the space for
2244     * the system bar, nav bar, and status bar, but not more transient elements
2245     * such as an input method.
2246     *
2247     * The stable layout your UI sees is based on the system UI modes you can
2248     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2249     * then you will get a stable layout for changes of the
2250     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2251     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2252     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2253     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2254     * with a stable layout.  (Note that you should avoid using
2255     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2256     *
2257     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2258     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2259     * then a hidden status bar will be considered a "stable" state for purposes
2260     * here.  This allows your UI to continually hide the status bar, while still
2261     * using the system UI flags to hide the action bar while still retaining
2262     * a stable layout.  Note that changing the window fullscreen flag will never
2263     * provide a stable layout for a clean transition.
2264     *
2265     * <p>If you are using ActionBar in
2266     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2267     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2268     * insets it adds to those given to the application.
2269     */
2270    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2271
2272    /**
2273     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2274     * to be layed out as if it has requested
2275     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2276     * allows it to avoid artifacts when switching in and out of that mode, at
2277     * the expense that some of its user interface may be covered by screen
2278     * decorations when they are shown.  You can perform layout of your inner
2279     * UI elements to account for the navagation system UI through the
2280     * {@link #fitSystemWindows(Rect)} method.
2281     */
2282    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2283
2284    /**
2285     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2286     * to be layed out as if it has requested
2287     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2288     * allows it to avoid artifacts when switching in and out of that mode, at
2289     * the expense that some of its user interface may be covered by screen
2290     * decorations when they are shown.  You can perform layout of your inner
2291     * UI elements to account for non-fullscreen system UI through the
2292     * {@link #fitSystemWindows(Rect)} method.
2293     */
2294    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2295
2296    /**
2297     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2298     */
2299    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2300
2301    /**
2302     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2303     */
2304    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2305
2306    /**
2307     * @hide
2308     *
2309     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2310     * out of the public fields to keep the undefined bits out of the developer's way.
2311     *
2312     * Flag to make the status bar not expandable.  Unless you also
2313     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2314     */
2315    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2316
2317    /**
2318     * @hide
2319     *
2320     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2321     * out of the public fields to keep the undefined bits out of the developer's way.
2322     *
2323     * Flag to hide notification icons and scrolling ticker text.
2324     */
2325    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2326
2327    /**
2328     * @hide
2329     *
2330     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2331     * out of the public fields to keep the undefined bits out of the developer's way.
2332     *
2333     * Flag to disable incoming notification alerts.  This will not block
2334     * icons, but it will block sound, vibrating and other visual or aural notifications.
2335     */
2336    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2337
2338    /**
2339     * @hide
2340     *
2341     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2342     * out of the public fields to keep the undefined bits out of the developer's way.
2343     *
2344     * Flag to hide only the scrolling ticker.  Note that
2345     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2346     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2347     */
2348    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2349
2350    /**
2351     * @hide
2352     *
2353     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2354     * out of the public fields to keep the undefined bits out of the developer's way.
2355     *
2356     * Flag to hide the center system info area.
2357     */
2358    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2359
2360    /**
2361     * @hide
2362     *
2363     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2364     * out of the public fields to keep the undefined bits out of the developer's way.
2365     *
2366     * Flag to hide only the home button.  Don't use this
2367     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2368     */
2369    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2370
2371    /**
2372     * @hide
2373     *
2374     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2375     * out of the public fields to keep the undefined bits out of the developer's way.
2376     *
2377     * Flag to hide only the back button. Don't use this
2378     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2379     */
2380    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2381
2382    /**
2383     * @hide
2384     *
2385     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2386     * out of the public fields to keep the undefined bits out of the developer's way.
2387     *
2388     * Flag to hide only the clock.  You might use this if your activity has
2389     * its own clock making the status bar's clock redundant.
2390     */
2391    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2392
2393    /**
2394     * @hide
2395     *
2396     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2397     * out of the public fields to keep the undefined bits out of the developer's way.
2398     *
2399     * Flag to hide only the recent apps button. Don't use this
2400     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2401     */
2402    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2403
2404    /**
2405     * @hide
2406     */
2407    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2408
2409    /**
2410     * These are the system UI flags that can be cleared by events outside
2411     * of an application.  Currently this is just the ability to tap on the
2412     * screen while hiding the navigation bar to have it return.
2413     * @hide
2414     */
2415    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2416            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2417            | SYSTEM_UI_FLAG_FULLSCREEN;
2418
2419    /**
2420     * Flags that can impact the layout in relation to system UI.
2421     */
2422    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2423            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2424            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2425
2426    /**
2427     * Find views that render the specified text.
2428     *
2429     * @see #findViewsWithText(ArrayList, CharSequence, int)
2430     */
2431    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2432
2433    /**
2434     * Find find views that contain the specified content description.
2435     *
2436     * @see #findViewsWithText(ArrayList, CharSequence, int)
2437     */
2438    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2439
2440    /**
2441     * Find views that contain {@link AccessibilityNodeProvider}. Such
2442     * a View is a root of virtual view hierarchy and may contain the searched
2443     * text. If this flag is set Views with providers are automatically
2444     * added and it is a responsibility of the client to call the APIs of
2445     * the provider to determine whether the virtual tree rooted at this View
2446     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2447     * represeting the virtual views with this text.
2448     *
2449     * @see #findViewsWithText(ArrayList, CharSequence, int)
2450     *
2451     * @hide
2452     */
2453    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2454
2455    /**
2456     * Indicates that the screen has changed state and is now off.
2457     *
2458     * @see #onScreenStateChanged(int)
2459     */
2460    public static final int SCREEN_STATE_OFF = 0x0;
2461
2462    /**
2463     * Indicates that the screen has changed state and is now on.
2464     *
2465     * @see #onScreenStateChanged(int)
2466     */
2467    public static final int SCREEN_STATE_ON = 0x1;
2468
2469    /**
2470     * Controls the over-scroll mode for this view.
2471     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2472     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2473     * and {@link #OVER_SCROLL_NEVER}.
2474     */
2475    private int mOverScrollMode;
2476
2477    /**
2478     * The parent this view is attached to.
2479     * {@hide}
2480     *
2481     * @see #getParent()
2482     */
2483    protected ViewParent mParent;
2484
2485    /**
2486     * {@hide}
2487     */
2488    AttachInfo mAttachInfo;
2489
2490    /**
2491     * {@hide}
2492     */
2493    @ViewDebug.ExportedProperty(flagMapping = {
2494        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2495                name = "FORCE_LAYOUT"),
2496        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2497                name = "LAYOUT_REQUIRED"),
2498        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2499            name = "DRAWING_CACHE_INVALID", outputIf = false),
2500        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2501        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2502        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2503        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2504    })
2505    int mPrivateFlags;
2506    int mPrivateFlags2;
2507
2508    /**
2509     * This view's request for the visibility of the status bar.
2510     * @hide
2511     */
2512    @ViewDebug.ExportedProperty(flagMapping = {
2513        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2514                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2515                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2516        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2517                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2518                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2519        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2520                                equals = SYSTEM_UI_FLAG_VISIBLE,
2521                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2522    })
2523    int mSystemUiVisibility;
2524
2525    /**
2526     * Reference count for transient state.
2527     * @see #setHasTransientState(boolean)
2528     */
2529    int mTransientStateCount = 0;
2530
2531    /**
2532     * Count of how many windows this view has been attached to.
2533     */
2534    int mWindowAttachCount;
2535
2536    /**
2537     * The layout parameters associated with this view and used by the parent
2538     * {@link android.view.ViewGroup} to determine how this view should be
2539     * laid out.
2540     * {@hide}
2541     */
2542    protected ViewGroup.LayoutParams mLayoutParams;
2543
2544    /**
2545     * The view flags hold various views states.
2546     * {@hide}
2547     */
2548    @ViewDebug.ExportedProperty
2549    int mViewFlags;
2550
2551    static class TransformationInfo {
2552        /**
2553         * The transform matrix for the View. This transform is calculated internally
2554         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2555         * is used by default. Do *not* use this variable directly; instead call
2556         * getMatrix(), which will automatically recalculate the matrix if necessary
2557         * to get the correct matrix based on the latest rotation and scale properties.
2558         */
2559        private final Matrix mMatrix = new Matrix();
2560
2561        /**
2562         * The transform matrix for the View. This transform is calculated internally
2563         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2564         * is used by default. Do *not* use this variable directly; instead call
2565         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2566         * to get the correct matrix based on the latest rotation and scale properties.
2567         */
2568        private Matrix mInverseMatrix;
2569
2570        /**
2571         * An internal variable that tracks whether we need to recalculate the
2572         * transform matrix, based on whether the rotation or scaleX/Y properties
2573         * have changed since the matrix was last calculated.
2574         */
2575        boolean mMatrixDirty = false;
2576
2577        /**
2578         * An internal variable that tracks whether we need to recalculate the
2579         * transform matrix, based on whether the rotation or scaleX/Y properties
2580         * have changed since the matrix was last calculated.
2581         */
2582        private boolean mInverseMatrixDirty = true;
2583
2584        /**
2585         * A variable that tracks whether we need to recalculate the
2586         * transform matrix, based on whether the rotation or scaleX/Y properties
2587         * have changed since the matrix was last calculated. This variable
2588         * is only valid after a call to updateMatrix() or to a function that
2589         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2590         */
2591        private boolean mMatrixIsIdentity = true;
2592
2593        /**
2594         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2595         */
2596        private Camera mCamera = null;
2597
2598        /**
2599         * This matrix is used when computing the matrix for 3D rotations.
2600         */
2601        private Matrix matrix3D = null;
2602
2603        /**
2604         * These prev values are used to recalculate a centered pivot point when necessary. The
2605         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2606         * set), so thes values are only used then as well.
2607         */
2608        private int mPrevWidth = -1;
2609        private int mPrevHeight = -1;
2610
2611        /**
2612         * The degrees rotation around the vertical axis through the pivot point.
2613         */
2614        @ViewDebug.ExportedProperty
2615        float mRotationY = 0f;
2616
2617        /**
2618         * The degrees rotation around the horizontal axis through the pivot point.
2619         */
2620        @ViewDebug.ExportedProperty
2621        float mRotationX = 0f;
2622
2623        /**
2624         * The degrees rotation around the pivot point.
2625         */
2626        @ViewDebug.ExportedProperty
2627        float mRotation = 0f;
2628
2629        /**
2630         * The amount of translation of the object away from its left property (post-layout).
2631         */
2632        @ViewDebug.ExportedProperty
2633        float mTranslationX = 0f;
2634
2635        /**
2636         * The amount of translation of the object away from its top property (post-layout).
2637         */
2638        @ViewDebug.ExportedProperty
2639        float mTranslationY = 0f;
2640
2641        /**
2642         * The amount of scale in the x direction around the pivot point. A
2643         * value of 1 means no scaling is applied.
2644         */
2645        @ViewDebug.ExportedProperty
2646        float mScaleX = 1f;
2647
2648        /**
2649         * The amount of scale in the y direction around the pivot point. A
2650         * value of 1 means no scaling is applied.
2651         */
2652        @ViewDebug.ExportedProperty
2653        float mScaleY = 1f;
2654
2655        /**
2656         * The x location of the point around which the view is rotated and scaled.
2657         */
2658        @ViewDebug.ExportedProperty
2659        float mPivotX = 0f;
2660
2661        /**
2662         * The y location of the point around which the view is rotated and scaled.
2663         */
2664        @ViewDebug.ExportedProperty
2665        float mPivotY = 0f;
2666
2667        /**
2668         * The opacity of the View. This is a value from 0 to 1, where 0 means
2669         * completely transparent and 1 means completely opaque.
2670         */
2671        @ViewDebug.ExportedProperty
2672        float mAlpha = 1f;
2673    }
2674
2675    TransformationInfo mTransformationInfo;
2676
2677    private boolean mLastIsOpaque;
2678
2679    /**
2680     * Convenience value to check for float values that are close enough to zero to be considered
2681     * zero.
2682     */
2683    private static final float NONZERO_EPSILON = .001f;
2684
2685    /**
2686     * The distance in pixels from the left edge of this view's parent
2687     * to the left edge of this view.
2688     * {@hide}
2689     */
2690    @ViewDebug.ExportedProperty(category = "layout")
2691    protected int mLeft;
2692    /**
2693     * The distance in pixels from the left edge of this view's parent
2694     * to the right edge of this view.
2695     * {@hide}
2696     */
2697    @ViewDebug.ExportedProperty(category = "layout")
2698    protected int mRight;
2699    /**
2700     * The distance in pixels from the top edge of this view's parent
2701     * to the top edge of this view.
2702     * {@hide}
2703     */
2704    @ViewDebug.ExportedProperty(category = "layout")
2705    protected int mTop;
2706    /**
2707     * The distance in pixels from the top edge of this view's parent
2708     * to the bottom edge of this view.
2709     * {@hide}
2710     */
2711    @ViewDebug.ExportedProperty(category = "layout")
2712    protected int mBottom;
2713
2714    /**
2715     * The offset, in pixels, by which the content of this view is scrolled
2716     * horizontally.
2717     * {@hide}
2718     */
2719    @ViewDebug.ExportedProperty(category = "scrolling")
2720    protected int mScrollX;
2721    /**
2722     * The offset, in pixels, by which the content of this view is scrolled
2723     * vertically.
2724     * {@hide}
2725     */
2726    @ViewDebug.ExportedProperty(category = "scrolling")
2727    protected int mScrollY;
2728
2729    /**
2730     * The left padding in pixels, that is the distance in pixels between the
2731     * left edge of this view and the left edge of its content.
2732     * {@hide}
2733     */
2734    @ViewDebug.ExportedProperty(category = "padding")
2735    protected int mPaddingLeft;
2736    /**
2737     * The right padding in pixels, that is the distance in pixels between the
2738     * right edge of this view and the right edge of its content.
2739     * {@hide}
2740     */
2741    @ViewDebug.ExportedProperty(category = "padding")
2742    protected int mPaddingRight;
2743    /**
2744     * The top padding in pixels, that is the distance in pixels between the
2745     * top edge of this view and the top edge of its content.
2746     * {@hide}
2747     */
2748    @ViewDebug.ExportedProperty(category = "padding")
2749    protected int mPaddingTop;
2750    /**
2751     * The bottom padding in pixels, that is the distance in pixels between the
2752     * bottom edge of this view and the bottom edge of its content.
2753     * {@hide}
2754     */
2755    @ViewDebug.ExportedProperty(category = "padding")
2756    protected int mPaddingBottom;
2757
2758    /**
2759     * The layout insets in pixels, that is the distance in pixels between the
2760     * visible edges of this view its bounds.
2761     */
2762    private Insets mLayoutInsets;
2763
2764    /**
2765     * Briefly describes the view and is primarily used for accessibility support.
2766     */
2767    private CharSequence mContentDescription;
2768
2769    /**
2770     * Cache the paddingRight set by the user to append to the scrollbar's size.
2771     *
2772     * @hide
2773     */
2774    @ViewDebug.ExportedProperty(category = "padding")
2775    protected int mUserPaddingRight;
2776
2777    /**
2778     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2779     *
2780     * @hide
2781     */
2782    @ViewDebug.ExportedProperty(category = "padding")
2783    protected int mUserPaddingBottom;
2784
2785    /**
2786     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2787     *
2788     * @hide
2789     */
2790    @ViewDebug.ExportedProperty(category = "padding")
2791    protected int mUserPaddingLeft;
2792
2793    /**
2794     * Cache if the user padding is relative.
2795     *
2796     */
2797    @ViewDebug.ExportedProperty(category = "padding")
2798    boolean mUserPaddingRelative;
2799
2800    /**
2801     * Cache the paddingStart set by the user to append to the scrollbar's size.
2802     *
2803     */
2804    @ViewDebug.ExportedProperty(category = "padding")
2805    int mUserPaddingStart;
2806
2807    /**
2808     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2809     *
2810     */
2811    @ViewDebug.ExportedProperty(category = "padding")
2812    int mUserPaddingEnd;
2813
2814    /**
2815     * @hide
2816     */
2817    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2818    /**
2819     * @hide
2820     */
2821    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2822
2823    private Drawable mBackground;
2824
2825    private int mBackgroundResource;
2826    private boolean mBackgroundSizeChanged;
2827
2828    static class ListenerInfo {
2829        /**
2830         * Listener used to dispatch focus change events.
2831         * This field should be made private, so it is hidden from the SDK.
2832         * {@hide}
2833         */
2834        protected OnFocusChangeListener mOnFocusChangeListener;
2835
2836        /**
2837         * Listeners for layout change events.
2838         */
2839        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2840
2841        /**
2842         * Listeners for attach events.
2843         */
2844        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2845
2846        /**
2847         * Listener used to dispatch click events.
2848         * This field should be made private, so it is hidden from the SDK.
2849         * {@hide}
2850         */
2851        public OnClickListener mOnClickListener;
2852
2853        /**
2854         * Listener used to dispatch long click events.
2855         * This field should be made private, so it is hidden from the SDK.
2856         * {@hide}
2857         */
2858        protected OnLongClickListener mOnLongClickListener;
2859
2860        /**
2861         * Listener used to build the context menu.
2862         * This field should be made private, so it is hidden from the SDK.
2863         * {@hide}
2864         */
2865        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2866
2867        private OnKeyListener mOnKeyListener;
2868
2869        private OnTouchListener mOnTouchListener;
2870
2871        private OnHoverListener mOnHoverListener;
2872
2873        private OnGenericMotionListener mOnGenericMotionListener;
2874
2875        private OnDragListener mOnDragListener;
2876
2877        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2878    }
2879
2880    ListenerInfo mListenerInfo;
2881
2882    /**
2883     * The application environment this view lives in.
2884     * This field should be made private, so it is hidden from the SDK.
2885     * {@hide}
2886     */
2887    protected Context mContext;
2888
2889    private final Resources mResources;
2890
2891    private ScrollabilityCache mScrollCache;
2892
2893    private int[] mDrawableState = null;
2894
2895    /**
2896     * Set to true when drawing cache is enabled and cannot be created.
2897     *
2898     * @hide
2899     */
2900    public boolean mCachingFailed;
2901
2902    private Bitmap mDrawingCache;
2903    private Bitmap mUnscaledDrawingCache;
2904    private HardwareLayer mHardwareLayer;
2905    DisplayList mDisplayList;
2906
2907    /**
2908     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2909     * the user may specify which view to go to next.
2910     */
2911    private int mNextFocusLeftId = View.NO_ID;
2912
2913    /**
2914     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2915     * the user may specify which view to go to next.
2916     */
2917    private int mNextFocusRightId = View.NO_ID;
2918
2919    /**
2920     * When this view has focus and the next focus is {@link #FOCUS_UP},
2921     * the user may specify which view to go to next.
2922     */
2923    private int mNextFocusUpId = View.NO_ID;
2924
2925    /**
2926     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2927     * the user may specify which view to go to next.
2928     */
2929    private int mNextFocusDownId = View.NO_ID;
2930
2931    /**
2932     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2933     * the user may specify which view to go to next.
2934     */
2935    int mNextFocusForwardId = View.NO_ID;
2936
2937    private CheckForLongPress mPendingCheckForLongPress;
2938    private CheckForTap mPendingCheckForTap = null;
2939    private PerformClick mPerformClick;
2940    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2941
2942    private UnsetPressedState mUnsetPressedState;
2943
2944    /**
2945     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2946     * up event while a long press is invoked as soon as the long press duration is reached, so
2947     * a long press could be performed before the tap is checked, in which case the tap's action
2948     * should not be invoked.
2949     */
2950    private boolean mHasPerformedLongPress;
2951
2952    /**
2953     * The minimum height of the view. We'll try our best to have the height
2954     * of this view to at least this amount.
2955     */
2956    @ViewDebug.ExportedProperty(category = "measurement")
2957    private int mMinHeight;
2958
2959    /**
2960     * The minimum width of the view. We'll try our best to have the width
2961     * of this view to at least this amount.
2962     */
2963    @ViewDebug.ExportedProperty(category = "measurement")
2964    private int mMinWidth;
2965
2966    /**
2967     * The delegate to handle touch events that are physically in this view
2968     * but should be handled by another view.
2969     */
2970    private TouchDelegate mTouchDelegate = null;
2971
2972    /**
2973     * Solid color to use as a background when creating the drawing cache. Enables
2974     * the cache to use 16 bit bitmaps instead of 32 bit.
2975     */
2976    private int mDrawingCacheBackgroundColor = 0;
2977
2978    /**
2979     * Special tree observer used when mAttachInfo is null.
2980     */
2981    private ViewTreeObserver mFloatingTreeObserver;
2982
2983    /**
2984     * Cache the touch slop from the context that created the view.
2985     */
2986    private int mTouchSlop;
2987
2988    /**
2989     * Object that handles automatic animation of view properties.
2990     */
2991    private ViewPropertyAnimator mAnimator = null;
2992
2993    /**
2994     * Flag indicating that a drag can cross window boundaries.  When
2995     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2996     * with this flag set, all visible applications will be able to participate
2997     * in the drag operation and receive the dragged content.
2998     *
2999     * @hide
3000     */
3001    public static final int DRAG_FLAG_GLOBAL = 1;
3002
3003    /**
3004     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3005     */
3006    private float mVerticalScrollFactor;
3007
3008    /**
3009     * Position of the vertical scroll bar.
3010     */
3011    private int mVerticalScrollbarPosition;
3012
3013    /**
3014     * Position the scroll bar at the default position as determined by the system.
3015     */
3016    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3017
3018    /**
3019     * Position the scroll bar along the left edge.
3020     */
3021    public static final int SCROLLBAR_POSITION_LEFT = 1;
3022
3023    /**
3024     * Position the scroll bar along the right edge.
3025     */
3026    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3027
3028    /**
3029     * Indicates that the view does not have a layer.
3030     *
3031     * @see #getLayerType()
3032     * @see #setLayerType(int, android.graphics.Paint)
3033     * @see #LAYER_TYPE_SOFTWARE
3034     * @see #LAYER_TYPE_HARDWARE
3035     */
3036    public static final int LAYER_TYPE_NONE = 0;
3037
3038    /**
3039     * <p>Indicates that the view has a software layer. A software layer is backed
3040     * by a bitmap and causes the view to be rendered using Android's software
3041     * rendering pipeline, even if hardware acceleration is enabled.</p>
3042     *
3043     * <p>Software layers have various usages:</p>
3044     * <p>When the application is not using hardware acceleration, a software layer
3045     * is useful to apply a specific color filter and/or blending mode and/or
3046     * translucency to a view and all its children.</p>
3047     * <p>When the application is using hardware acceleration, a software layer
3048     * is useful to render drawing primitives not supported by the hardware
3049     * accelerated pipeline. It can also be used to cache a complex view tree
3050     * into a texture and reduce the complexity of drawing operations. For instance,
3051     * when animating a complex view tree with a translation, a software layer can
3052     * be used to render the view tree only once.</p>
3053     * <p>Software layers should be avoided when the affected view tree updates
3054     * often. Every update will require to re-render the software layer, which can
3055     * potentially be slow (particularly when hardware acceleration is turned on
3056     * since the layer will have to be uploaded into a hardware texture after every
3057     * update.)</p>
3058     *
3059     * @see #getLayerType()
3060     * @see #setLayerType(int, android.graphics.Paint)
3061     * @see #LAYER_TYPE_NONE
3062     * @see #LAYER_TYPE_HARDWARE
3063     */
3064    public static final int LAYER_TYPE_SOFTWARE = 1;
3065
3066    /**
3067     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3068     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3069     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3070     * rendering pipeline, but only if hardware acceleration is turned on for the
3071     * view hierarchy. When hardware acceleration is turned off, hardware layers
3072     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3073     *
3074     * <p>A hardware layer is useful to apply a specific color filter and/or
3075     * blending mode and/or translucency to a view and all its children.</p>
3076     * <p>A hardware layer can be used to cache a complex view tree into a
3077     * texture and reduce the complexity of drawing operations. For instance,
3078     * when animating a complex view tree with a translation, a hardware layer can
3079     * be used to render the view tree only once.</p>
3080     * <p>A hardware layer can also be used to increase the rendering quality when
3081     * rotation transformations are applied on a view. It can also be used to
3082     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3083     *
3084     * @see #getLayerType()
3085     * @see #setLayerType(int, android.graphics.Paint)
3086     * @see #LAYER_TYPE_NONE
3087     * @see #LAYER_TYPE_SOFTWARE
3088     */
3089    public static final int LAYER_TYPE_HARDWARE = 2;
3090
3091    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3092            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3093            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3094            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3095    })
3096    int mLayerType = LAYER_TYPE_NONE;
3097    Paint mLayerPaint;
3098    Rect mLocalDirtyRect;
3099
3100    /**
3101     * Set to true when the view is sending hover accessibility events because it
3102     * is the innermost hovered view.
3103     */
3104    private boolean mSendingHoverAccessibilityEvents;
3105
3106    /**
3107     * Simple constructor to use when creating a view from code.
3108     *
3109     * @param context The Context the view is running in, through which it can
3110     *        access the current theme, resources, etc.
3111     */
3112    public View(Context context) {
3113        mContext = context;
3114        mResources = context != null ? context.getResources() : null;
3115        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3116        // Set layout and text direction defaults
3117        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3118                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3119                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3120                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3121        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3122        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3123        mUserPaddingStart = -1;
3124        mUserPaddingEnd = -1;
3125        mUserPaddingRelative = false;
3126    }
3127
3128    /**
3129     * Delegate for injecting accessiblity functionality.
3130     */
3131    AccessibilityDelegate mAccessibilityDelegate;
3132
3133    /**
3134     * Consistency verifier for debugging purposes.
3135     * @hide
3136     */
3137    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3138            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3139                    new InputEventConsistencyVerifier(this, 0) : null;
3140
3141    /**
3142     * Constructor that is called when inflating a view from XML. This is called
3143     * when a view is being constructed from an XML file, supplying attributes
3144     * that were specified in the XML file. This version uses a default style of
3145     * 0, so the only attribute values applied are those in the Context's Theme
3146     * and the given AttributeSet.
3147     *
3148     * <p>
3149     * The method onFinishInflate() will be called after all children have been
3150     * added.
3151     *
3152     * @param context The Context the view is running in, through which it can
3153     *        access the current theme, resources, etc.
3154     * @param attrs The attributes of the XML tag that is inflating the view.
3155     * @see #View(Context, AttributeSet, int)
3156     */
3157    public View(Context context, AttributeSet attrs) {
3158        this(context, attrs, 0);
3159    }
3160
3161    /**
3162     * Perform inflation from XML and apply a class-specific base style. This
3163     * constructor of View allows subclasses to use their own base style when
3164     * they are inflating. For example, a Button class's constructor would call
3165     * this version of the super class constructor and supply
3166     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3167     * the theme's button style to modify all of the base view attributes (in
3168     * particular its background) as well as the Button class's attributes.
3169     *
3170     * @param context The Context the view is running in, through which it can
3171     *        access the current theme, resources, etc.
3172     * @param attrs The attributes of the XML tag that is inflating the view.
3173     * @param defStyle The default style to apply to this view. If 0, no style
3174     *        will be applied (beyond what is included in the theme). This may
3175     *        either be an attribute resource, whose value will be retrieved
3176     *        from the current theme, or an explicit style resource.
3177     * @see #View(Context, AttributeSet)
3178     */
3179    public View(Context context, AttributeSet attrs, int defStyle) {
3180        this(context);
3181
3182        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3183                defStyle, 0);
3184
3185        Drawable background = null;
3186
3187        int leftPadding = -1;
3188        int topPadding = -1;
3189        int rightPadding = -1;
3190        int bottomPadding = -1;
3191        int startPadding = -1;
3192        int endPadding = -1;
3193
3194        int padding = -1;
3195
3196        int viewFlagValues = 0;
3197        int viewFlagMasks = 0;
3198
3199        boolean setScrollContainer = false;
3200
3201        int x = 0;
3202        int y = 0;
3203
3204        float tx = 0;
3205        float ty = 0;
3206        float rotation = 0;
3207        float rotationX = 0;
3208        float rotationY = 0;
3209        float sx = 1f;
3210        float sy = 1f;
3211        boolean transformSet = false;
3212
3213        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3214
3215        int overScrollMode = mOverScrollMode;
3216        final int N = a.getIndexCount();
3217        for (int i = 0; i < N; i++) {
3218            int attr = a.getIndex(i);
3219            switch (attr) {
3220                case com.android.internal.R.styleable.View_background:
3221                    background = a.getDrawable(attr);
3222                    break;
3223                case com.android.internal.R.styleable.View_padding:
3224                    padding = a.getDimensionPixelSize(attr, -1);
3225                    break;
3226                 case com.android.internal.R.styleable.View_paddingLeft:
3227                    leftPadding = a.getDimensionPixelSize(attr, -1);
3228                    break;
3229                case com.android.internal.R.styleable.View_paddingTop:
3230                    topPadding = a.getDimensionPixelSize(attr, -1);
3231                    break;
3232                case com.android.internal.R.styleable.View_paddingRight:
3233                    rightPadding = a.getDimensionPixelSize(attr, -1);
3234                    break;
3235                case com.android.internal.R.styleable.View_paddingBottom:
3236                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3237                    break;
3238                case com.android.internal.R.styleable.View_paddingStart:
3239                    startPadding = a.getDimensionPixelSize(attr, -1);
3240                    break;
3241                case com.android.internal.R.styleable.View_paddingEnd:
3242                    endPadding = a.getDimensionPixelSize(attr, -1);
3243                    break;
3244                case com.android.internal.R.styleable.View_scrollX:
3245                    x = a.getDimensionPixelOffset(attr, 0);
3246                    break;
3247                case com.android.internal.R.styleable.View_scrollY:
3248                    y = a.getDimensionPixelOffset(attr, 0);
3249                    break;
3250                case com.android.internal.R.styleable.View_alpha:
3251                    setAlpha(a.getFloat(attr, 1f));
3252                    break;
3253                case com.android.internal.R.styleable.View_transformPivotX:
3254                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3255                    break;
3256                case com.android.internal.R.styleable.View_transformPivotY:
3257                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3258                    break;
3259                case com.android.internal.R.styleable.View_translationX:
3260                    tx = a.getDimensionPixelOffset(attr, 0);
3261                    transformSet = true;
3262                    break;
3263                case com.android.internal.R.styleable.View_translationY:
3264                    ty = a.getDimensionPixelOffset(attr, 0);
3265                    transformSet = true;
3266                    break;
3267                case com.android.internal.R.styleable.View_rotation:
3268                    rotation = a.getFloat(attr, 0);
3269                    transformSet = true;
3270                    break;
3271                case com.android.internal.R.styleable.View_rotationX:
3272                    rotationX = a.getFloat(attr, 0);
3273                    transformSet = true;
3274                    break;
3275                case com.android.internal.R.styleable.View_rotationY:
3276                    rotationY = a.getFloat(attr, 0);
3277                    transformSet = true;
3278                    break;
3279                case com.android.internal.R.styleable.View_scaleX:
3280                    sx = a.getFloat(attr, 1f);
3281                    transformSet = true;
3282                    break;
3283                case com.android.internal.R.styleable.View_scaleY:
3284                    sy = a.getFloat(attr, 1f);
3285                    transformSet = true;
3286                    break;
3287                case com.android.internal.R.styleable.View_id:
3288                    mID = a.getResourceId(attr, NO_ID);
3289                    break;
3290                case com.android.internal.R.styleable.View_tag:
3291                    mTag = a.getText(attr);
3292                    break;
3293                case com.android.internal.R.styleable.View_fitsSystemWindows:
3294                    if (a.getBoolean(attr, false)) {
3295                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3296                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3297                    }
3298                    break;
3299                case com.android.internal.R.styleable.View_focusable:
3300                    if (a.getBoolean(attr, false)) {
3301                        viewFlagValues |= FOCUSABLE;
3302                        viewFlagMasks |= FOCUSABLE_MASK;
3303                    }
3304                    break;
3305                case com.android.internal.R.styleable.View_focusableInTouchMode:
3306                    if (a.getBoolean(attr, false)) {
3307                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3308                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3309                    }
3310                    break;
3311                case com.android.internal.R.styleable.View_clickable:
3312                    if (a.getBoolean(attr, false)) {
3313                        viewFlagValues |= CLICKABLE;
3314                        viewFlagMasks |= CLICKABLE;
3315                    }
3316                    break;
3317                case com.android.internal.R.styleable.View_longClickable:
3318                    if (a.getBoolean(attr, false)) {
3319                        viewFlagValues |= LONG_CLICKABLE;
3320                        viewFlagMasks |= LONG_CLICKABLE;
3321                    }
3322                    break;
3323                case com.android.internal.R.styleable.View_saveEnabled:
3324                    if (!a.getBoolean(attr, true)) {
3325                        viewFlagValues |= SAVE_DISABLED;
3326                        viewFlagMasks |= SAVE_DISABLED_MASK;
3327                    }
3328                    break;
3329                case com.android.internal.R.styleable.View_duplicateParentState:
3330                    if (a.getBoolean(attr, false)) {
3331                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3332                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3333                    }
3334                    break;
3335                case com.android.internal.R.styleable.View_visibility:
3336                    final int visibility = a.getInt(attr, 0);
3337                    if (visibility != 0) {
3338                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3339                        viewFlagMasks |= VISIBILITY_MASK;
3340                    }
3341                    break;
3342                case com.android.internal.R.styleable.View_layoutDirection:
3343                    // Clear any layout direction flags (included resolved bits) already set
3344                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3345                    // Set the layout direction flags depending on the value of the attribute
3346                    final int layoutDirection = a.getInt(attr, -1);
3347                    final int value = (layoutDirection != -1) ?
3348                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3349                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3350                    break;
3351                case com.android.internal.R.styleable.View_drawingCacheQuality:
3352                    final int cacheQuality = a.getInt(attr, 0);
3353                    if (cacheQuality != 0) {
3354                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3355                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3356                    }
3357                    break;
3358                case com.android.internal.R.styleable.View_contentDescription:
3359                    mContentDescription = a.getString(attr);
3360                    break;
3361                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3362                    if (!a.getBoolean(attr, true)) {
3363                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3364                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3365                    }
3366                    break;
3367                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3368                    if (!a.getBoolean(attr, true)) {
3369                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3370                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3371                    }
3372                    break;
3373                case R.styleable.View_scrollbars:
3374                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3375                    if (scrollbars != SCROLLBARS_NONE) {
3376                        viewFlagValues |= scrollbars;
3377                        viewFlagMasks |= SCROLLBARS_MASK;
3378                        initializeScrollbars(a);
3379                    }
3380                    break;
3381                //noinspection deprecation
3382                case R.styleable.View_fadingEdge:
3383                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3384                        // Ignore the attribute starting with ICS
3385                        break;
3386                    }
3387                    // With builds < ICS, fall through and apply fading edges
3388                case R.styleable.View_requiresFadingEdge:
3389                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3390                    if (fadingEdge != FADING_EDGE_NONE) {
3391                        viewFlagValues |= fadingEdge;
3392                        viewFlagMasks |= FADING_EDGE_MASK;
3393                        initializeFadingEdge(a);
3394                    }
3395                    break;
3396                case R.styleable.View_scrollbarStyle:
3397                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3398                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3399                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3400                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3401                    }
3402                    break;
3403                case R.styleable.View_isScrollContainer:
3404                    setScrollContainer = true;
3405                    if (a.getBoolean(attr, false)) {
3406                        setScrollContainer(true);
3407                    }
3408                    break;
3409                case com.android.internal.R.styleable.View_keepScreenOn:
3410                    if (a.getBoolean(attr, false)) {
3411                        viewFlagValues |= KEEP_SCREEN_ON;
3412                        viewFlagMasks |= KEEP_SCREEN_ON;
3413                    }
3414                    break;
3415                case R.styleable.View_filterTouchesWhenObscured:
3416                    if (a.getBoolean(attr, false)) {
3417                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3418                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3419                    }
3420                    break;
3421                case R.styleable.View_nextFocusLeft:
3422                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3423                    break;
3424                case R.styleable.View_nextFocusRight:
3425                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3426                    break;
3427                case R.styleable.View_nextFocusUp:
3428                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3429                    break;
3430                case R.styleable.View_nextFocusDown:
3431                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3432                    break;
3433                case R.styleable.View_nextFocusForward:
3434                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3435                    break;
3436                case R.styleable.View_minWidth:
3437                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3438                    break;
3439                case R.styleable.View_minHeight:
3440                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3441                    break;
3442                case R.styleable.View_onClick:
3443                    if (context.isRestricted()) {
3444                        throw new IllegalStateException("The android:onClick attribute cannot "
3445                                + "be used within a restricted context");
3446                    }
3447
3448                    final String handlerName = a.getString(attr);
3449                    if (handlerName != null) {
3450                        setOnClickListener(new OnClickListener() {
3451                            private Method mHandler;
3452
3453                            public void onClick(View v) {
3454                                if (mHandler == null) {
3455                                    try {
3456                                        mHandler = getContext().getClass().getMethod(handlerName,
3457                                                View.class);
3458                                    } catch (NoSuchMethodException e) {
3459                                        int id = getId();
3460                                        String idText = id == NO_ID ? "" : " with id '"
3461                                                + getContext().getResources().getResourceEntryName(
3462                                                    id) + "'";
3463                                        throw new IllegalStateException("Could not find a method " +
3464                                                handlerName + "(View) in the activity "
3465                                                + getContext().getClass() + " for onClick handler"
3466                                                + " on view " + View.this.getClass() + idText, e);
3467                                    }
3468                                }
3469
3470                                try {
3471                                    mHandler.invoke(getContext(), View.this);
3472                                } catch (IllegalAccessException e) {
3473                                    throw new IllegalStateException("Could not execute non "
3474                                            + "public method of the activity", e);
3475                                } catch (InvocationTargetException e) {
3476                                    throw new IllegalStateException("Could not execute "
3477                                            + "method of the activity", e);
3478                                }
3479                            }
3480                        });
3481                    }
3482                    break;
3483                case R.styleable.View_overScrollMode:
3484                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3485                    break;
3486                case R.styleable.View_verticalScrollbarPosition:
3487                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3488                    break;
3489                case R.styleable.View_layerType:
3490                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3491                    break;
3492                case R.styleable.View_textDirection:
3493                    // Clear any text direction flag already set
3494                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3495                    // Set the text direction flags depending on the value of the attribute
3496                    final int textDirection = a.getInt(attr, -1);
3497                    if (textDirection != -1) {
3498                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3499                    }
3500                    break;
3501                case R.styleable.View_textAlignment:
3502                    // Clear any text alignment flag already set
3503                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3504                    // Set the text alignment flag depending on the value of the attribute
3505                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3506                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3507                    break;
3508                case R.styleable.View_importantForAccessibility:
3509                    setImportantForAccessibility(a.getInt(attr,
3510                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3511            }
3512        }
3513
3514        a.recycle();
3515
3516        setOverScrollMode(overScrollMode);
3517
3518        if (background != null) {
3519            setBackground(background);
3520        }
3521
3522        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3523        // layout direction). Those cached values will be used later during padding resolution.
3524        mUserPaddingStart = startPadding;
3525        mUserPaddingEnd = endPadding;
3526
3527        updateUserPaddingRelative();
3528
3529        if (padding >= 0) {
3530            leftPadding = padding;
3531            topPadding = padding;
3532            rightPadding = padding;
3533            bottomPadding = padding;
3534        }
3535
3536        // If the user specified the padding (either with android:padding or
3537        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3538        // use the default padding or the padding from the background drawable
3539        // (stored at this point in mPadding*)
3540        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3541                topPadding >= 0 ? topPadding : mPaddingTop,
3542                rightPadding >= 0 ? rightPadding : mPaddingRight,
3543                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3544
3545        if (viewFlagMasks != 0) {
3546            setFlags(viewFlagValues, viewFlagMasks);
3547        }
3548
3549        // Needs to be called after mViewFlags is set
3550        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3551            recomputePadding();
3552        }
3553
3554        if (x != 0 || y != 0) {
3555            scrollTo(x, y);
3556        }
3557
3558        if (transformSet) {
3559            setTranslationX(tx);
3560            setTranslationY(ty);
3561            setRotation(rotation);
3562            setRotationX(rotationX);
3563            setRotationY(rotationY);
3564            setScaleX(sx);
3565            setScaleY(sy);
3566        }
3567
3568        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3569            setScrollContainer(true);
3570        }
3571
3572        computeOpaqueFlags();
3573    }
3574
3575    private void updateUserPaddingRelative() {
3576        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3577    }
3578
3579    /**
3580     * Non-public constructor for use in testing
3581     */
3582    View() {
3583        mResources = null;
3584    }
3585
3586    /**
3587     * <p>
3588     * Initializes the fading edges from a given set of styled attributes. This
3589     * method should be called by subclasses that need fading edges and when an
3590     * instance of these subclasses is created programmatically rather than
3591     * being inflated from XML. This method is automatically called when the XML
3592     * is inflated.
3593     * </p>
3594     *
3595     * @param a the styled attributes set to initialize the fading edges from
3596     */
3597    protected void initializeFadingEdge(TypedArray a) {
3598        initScrollCache();
3599
3600        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3601                R.styleable.View_fadingEdgeLength,
3602                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3603    }
3604
3605    /**
3606     * Returns the size of the vertical faded edges used to indicate that more
3607     * content in this view is visible.
3608     *
3609     * @return The size in pixels of the vertical faded edge or 0 if vertical
3610     *         faded edges are not enabled for this view.
3611     * @attr ref android.R.styleable#View_fadingEdgeLength
3612     */
3613    public int getVerticalFadingEdgeLength() {
3614        if (isVerticalFadingEdgeEnabled()) {
3615            ScrollabilityCache cache = mScrollCache;
3616            if (cache != null) {
3617                return cache.fadingEdgeLength;
3618            }
3619        }
3620        return 0;
3621    }
3622
3623    /**
3624     * Set the size of the faded edge used to indicate that more content in this
3625     * view is available.  Will not change whether the fading edge is enabled; use
3626     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3627     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3628     * for the vertical or horizontal fading edges.
3629     *
3630     * @param length The size in pixels of the faded edge used to indicate that more
3631     *        content in this view is visible.
3632     */
3633    public void setFadingEdgeLength(int length) {
3634        initScrollCache();
3635        mScrollCache.fadingEdgeLength = length;
3636    }
3637
3638    /**
3639     * Returns the size of the horizontal faded edges used to indicate that more
3640     * content in this view is visible.
3641     *
3642     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3643     *         faded edges are not enabled for this view.
3644     * @attr ref android.R.styleable#View_fadingEdgeLength
3645     */
3646    public int getHorizontalFadingEdgeLength() {
3647        if (isHorizontalFadingEdgeEnabled()) {
3648            ScrollabilityCache cache = mScrollCache;
3649            if (cache != null) {
3650                return cache.fadingEdgeLength;
3651            }
3652        }
3653        return 0;
3654    }
3655
3656    /**
3657     * Returns the width of the vertical scrollbar.
3658     *
3659     * @return The width in pixels of the vertical scrollbar or 0 if there
3660     *         is no vertical scrollbar.
3661     */
3662    public int getVerticalScrollbarWidth() {
3663        ScrollabilityCache cache = mScrollCache;
3664        if (cache != null) {
3665            ScrollBarDrawable scrollBar = cache.scrollBar;
3666            if (scrollBar != null) {
3667                int size = scrollBar.getSize(true);
3668                if (size <= 0) {
3669                    size = cache.scrollBarSize;
3670                }
3671                return size;
3672            }
3673            return 0;
3674        }
3675        return 0;
3676    }
3677
3678    /**
3679     * Returns the height of the horizontal scrollbar.
3680     *
3681     * @return The height in pixels of the horizontal scrollbar or 0 if
3682     *         there is no horizontal scrollbar.
3683     */
3684    protected int getHorizontalScrollbarHeight() {
3685        ScrollabilityCache cache = mScrollCache;
3686        if (cache != null) {
3687            ScrollBarDrawable scrollBar = cache.scrollBar;
3688            if (scrollBar != null) {
3689                int size = scrollBar.getSize(false);
3690                if (size <= 0) {
3691                    size = cache.scrollBarSize;
3692                }
3693                return size;
3694            }
3695            return 0;
3696        }
3697        return 0;
3698    }
3699
3700    /**
3701     * <p>
3702     * Initializes the scrollbars from a given set of styled attributes. This
3703     * method should be called by subclasses that need scrollbars and when an
3704     * instance of these subclasses is created programmatically rather than
3705     * being inflated from XML. This method is automatically called when the XML
3706     * is inflated.
3707     * </p>
3708     *
3709     * @param a the styled attributes set to initialize the scrollbars from
3710     */
3711    protected void initializeScrollbars(TypedArray a) {
3712        initScrollCache();
3713
3714        final ScrollabilityCache scrollabilityCache = mScrollCache;
3715
3716        if (scrollabilityCache.scrollBar == null) {
3717            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3718        }
3719
3720        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3721
3722        if (!fadeScrollbars) {
3723            scrollabilityCache.state = ScrollabilityCache.ON;
3724        }
3725        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3726
3727
3728        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3729                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3730                        .getScrollBarFadeDuration());
3731        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3732                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3733                ViewConfiguration.getScrollDefaultDelay());
3734
3735
3736        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3737                com.android.internal.R.styleable.View_scrollbarSize,
3738                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3739
3740        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3741        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3742
3743        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3744        if (thumb != null) {
3745            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3746        }
3747
3748        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3749                false);
3750        if (alwaysDraw) {
3751            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3752        }
3753
3754        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3755        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3756
3757        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3758        if (thumb != null) {
3759            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3760        }
3761
3762        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3763                false);
3764        if (alwaysDraw) {
3765            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3766        }
3767
3768        // Re-apply user/background padding so that scrollbar(s) get added
3769        resolvePadding();
3770    }
3771
3772    /**
3773     * <p>
3774     * Initalizes the scrollability cache if necessary.
3775     * </p>
3776     */
3777    private void initScrollCache() {
3778        if (mScrollCache == null) {
3779            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3780        }
3781    }
3782
3783    private ScrollabilityCache getScrollCache() {
3784        initScrollCache();
3785        return mScrollCache;
3786    }
3787
3788    /**
3789     * Set the position of the vertical scroll bar. Should be one of
3790     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3791     * {@link #SCROLLBAR_POSITION_RIGHT}.
3792     *
3793     * @param position Where the vertical scroll bar should be positioned.
3794     */
3795    public void setVerticalScrollbarPosition(int position) {
3796        if (mVerticalScrollbarPosition != position) {
3797            mVerticalScrollbarPosition = position;
3798            computeOpaqueFlags();
3799            resolvePadding();
3800        }
3801    }
3802
3803    /**
3804     * @return The position where the vertical scroll bar will show, if applicable.
3805     * @see #setVerticalScrollbarPosition(int)
3806     */
3807    public int getVerticalScrollbarPosition() {
3808        return mVerticalScrollbarPosition;
3809    }
3810
3811    ListenerInfo getListenerInfo() {
3812        if (mListenerInfo != null) {
3813            return mListenerInfo;
3814        }
3815        mListenerInfo = new ListenerInfo();
3816        return mListenerInfo;
3817    }
3818
3819    /**
3820     * Register a callback to be invoked when focus of this view changed.
3821     *
3822     * @param l The callback that will run.
3823     */
3824    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3825        getListenerInfo().mOnFocusChangeListener = l;
3826    }
3827
3828    /**
3829     * Add a listener that will be called when the bounds of the view change due to
3830     * layout processing.
3831     *
3832     * @param listener The listener that will be called when layout bounds change.
3833     */
3834    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3835        ListenerInfo li = getListenerInfo();
3836        if (li.mOnLayoutChangeListeners == null) {
3837            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3838        }
3839        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3840            li.mOnLayoutChangeListeners.add(listener);
3841        }
3842    }
3843
3844    /**
3845     * Remove a listener for layout changes.
3846     *
3847     * @param listener The listener for layout bounds change.
3848     */
3849    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3850        ListenerInfo li = mListenerInfo;
3851        if (li == null || li.mOnLayoutChangeListeners == null) {
3852            return;
3853        }
3854        li.mOnLayoutChangeListeners.remove(listener);
3855    }
3856
3857    /**
3858     * Add a listener for attach state changes.
3859     *
3860     * This listener will be called whenever this view is attached or detached
3861     * from a window. Remove the listener using
3862     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3863     *
3864     * @param listener Listener to attach
3865     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3866     */
3867    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3868        ListenerInfo li = getListenerInfo();
3869        if (li.mOnAttachStateChangeListeners == null) {
3870            li.mOnAttachStateChangeListeners
3871                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3872        }
3873        li.mOnAttachStateChangeListeners.add(listener);
3874    }
3875
3876    /**
3877     * Remove a listener for attach state changes. The listener will receive no further
3878     * notification of window attach/detach events.
3879     *
3880     * @param listener Listener to remove
3881     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3882     */
3883    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3884        ListenerInfo li = mListenerInfo;
3885        if (li == null || li.mOnAttachStateChangeListeners == null) {
3886            return;
3887        }
3888        li.mOnAttachStateChangeListeners.remove(listener);
3889    }
3890
3891    /**
3892     * Returns the focus-change callback registered for this view.
3893     *
3894     * @return The callback, or null if one is not registered.
3895     */
3896    public OnFocusChangeListener getOnFocusChangeListener() {
3897        ListenerInfo li = mListenerInfo;
3898        return li != null ? li.mOnFocusChangeListener : null;
3899    }
3900
3901    /**
3902     * Register a callback to be invoked when this view is clicked. If this view is not
3903     * clickable, it becomes clickable.
3904     *
3905     * @param l The callback that will run
3906     *
3907     * @see #setClickable(boolean)
3908     */
3909    public void setOnClickListener(OnClickListener l) {
3910        if (!isClickable()) {
3911            setClickable(true);
3912        }
3913        getListenerInfo().mOnClickListener = l;
3914    }
3915
3916    /**
3917     * Return whether this view has an attached OnClickListener.  Returns
3918     * true if there is a listener, false if there is none.
3919     */
3920    public boolean hasOnClickListeners() {
3921        ListenerInfo li = mListenerInfo;
3922        return (li != null && li.mOnClickListener != null);
3923    }
3924
3925    /**
3926     * Register a callback to be invoked when this view is clicked and held. If this view is not
3927     * long clickable, it becomes long clickable.
3928     *
3929     * @param l The callback that will run
3930     *
3931     * @see #setLongClickable(boolean)
3932     */
3933    public void setOnLongClickListener(OnLongClickListener l) {
3934        if (!isLongClickable()) {
3935            setLongClickable(true);
3936        }
3937        getListenerInfo().mOnLongClickListener = l;
3938    }
3939
3940    /**
3941     * Register a callback to be invoked when the context menu for this view is
3942     * being built. If this view is not long clickable, it becomes long clickable.
3943     *
3944     * @param l The callback that will run
3945     *
3946     */
3947    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3948        if (!isLongClickable()) {
3949            setLongClickable(true);
3950        }
3951        getListenerInfo().mOnCreateContextMenuListener = l;
3952    }
3953
3954    /**
3955     * Call this view's OnClickListener, if it is defined.  Performs all normal
3956     * actions associated with clicking: reporting accessibility event, playing
3957     * a sound, etc.
3958     *
3959     * @return True there was an assigned OnClickListener that was called, false
3960     *         otherwise is returned.
3961     */
3962    public boolean performClick() {
3963        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3964
3965        ListenerInfo li = mListenerInfo;
3966        if (li != null && li.mOnClickListener != null) {
3967            playSoundEffect(SoundEffectConstants.CLICK);
3968            li.mOnClickListener.onClick(this);
3969            return true;
3970        }
3971
3972        return false;
3973    }
3974
3975    /**
3976     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3977     * this only calls the listener, and does not do any associated clicking
3978     * actions like reporting an accessibility event.
3979     *
3980     * @return True there was an assigned OnClickListener that was called, false
3981     *         otherwise is returned.
3982     */
3983    public boolean callOnClick() {
3984        ListenerInfo li = mListenerInfo;
3985        if (li != null && li.mOnClickListener != null) {
3986            li.mOnClickListener.onClick(this);
3987            return true;
3988        }
3989        return false;
3990    }
3991
3992    /**
3993     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3994     * OnLongClickListener did not consume the event.
3995     *
3996     * @return True if one of the above receivers consumed the event, false otherwise.
3997     */
3998    public boolean performLongClick() {
3999        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4000
4001        boolean handled = false;
4002        ListenerInfo li = mListenerInfo;
4003        if (li != null && li.mOnLongClickListener != null) {
4004            handled = li.mOnLongClickListener.onLongClick(View.this);
4005        }
4006        if (!handled) {
4007            handled = showContextMenu();
4008        }
4009        if (handled) {
4010            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4011        }
4012        return handled;
4013    }
4014
4015    /**
4016     * Performs button-related actions during a touch down event.
4017     *
4018     * @param event The event.
4019     * @return True if the down was consumed.
4020     *
4021     * @hide
4022     */
4023    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4024        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4025            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4026                return true;
4027            }
4028        }
4029        return false;
4030    }
4031
4032    /**
4033     * Bring up the context menu for this view.
4034     *
4035     * @return Whether a context menu was displayed.
4036     */
4037    public boolean showContextMenu() {
4038        return getParent().showContextMenuForChild(this);
4039    }
4040
4041    /**
4042     * Bring up the context menu for this view, referring to the item under the specified point.
4043     *
4044     * @param x The referenced x coordinate.
4045     * @param y The referenced y coordinate.
4046     * @param metaState The keyboard modifiers that were pressed.
4047     * @return Whether a context menu was displayed.
4048     *
4049     * @hide
4050     */
4051    public boolean showContextMenu(float x, float y, int metaState) {
4052        return showContextMenu();
4053    }
4054
4055    /**
4056     * Start an action mode.
4057     *
4058     * @param callback Callback that will control the lifecycle of the action mode
4059     * @return The new action mode if it is started, null otherwise
4060     *
4061     * @see ActionMode
4062     */
4063    public ActionMode startActionMode(ActionMode.Callback callback) {
4064        ViewParent parent = getParent();
4065        if (parent == null) return null;
4066        return parent.startActionModeForChild(this, callback);
4067    }
4068
4069    /**
4070     * Register a callback to be invoked when a key is pressed in this view.
4071     * @param l the key listener to attach to this view
4072     */
4073    public void setOnKeyListener(OnKeyListener l) {
4074        getListenerInfo().mOnKeyListener = l;
4075    }
4076
4077    /**
4078     * Register a callback to be invoked when a touch event is sent to this view.
4079     * @param l the touch listener to attach to this view
4080     */
4081    public void setOnTouchListener(OnTouchListener l) {
4082        getListenerInfo().mOnTouchListener = l;
4083    }
4084
4085    /**
4086     * Register a callback to be invoked when a generic motion event is sent to this view.
4087     * @param l the generic motion listener to attach to this view
4088     */
4089    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4090        getListenerInfo().mOnGenericMotionListener = l;
4091    }
4092
4093    /**
4094     * Register a callback to be invoked when a hover event is sent to this view.
4095     * @param l the hover listener to attach to this view
4096     */
4097    public void setOnHoverListener(OnHoverListener l) {
4098        getListenerInfo().mOnHoverListener = l;
4099    }
4100
4101    /**
4102     * Register a drag event listener callback object for this View. The parameter is
4103     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4104     * View, the system calls the
4105     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4106     * @param l An implementation of {@link android.view.View.OnDragListener}.
4107     */
4108    public void setOnDragListener(OnDragListener l) {
4109        getListenerInfo().mOnDragListener = l;
4110    }
4111
4112    /**
4113     * Give this view focus. This will cause
4114     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4115     *
4116     * Note: this does not check whether this {@link View} should get focus, it just
4117     * gives it focus no matter what.  It should only be called internally by framework
4118     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4119     *
4120     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4121     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4122     *        focus moved when requestFocus() is called. It may not always
4123     *        apply, in which case use the default View.FOCUS_DOWN.
4124     * @param previouslyFocusedRect The rectangle of the view that had focus
4125     *        prior in this View's coordinate system.
4126     */
4127    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4128        if (DBG) {
4129            System.out.println(this + " requestFocus()");
4130        }
4131
4132        if ((mPrivateFlags & FOCUSED) == 0) {
4133            mPrivateFlags |= FOCUSED;
4134
4135            if (mParent != null) {
4136                mParent.requestChildFocus(this, this);
4137            }
4138
4139            onFocusChanged(true, direction, previouslyFocusedRect);
4140            refreshDrawableState();
4141
4142            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4143                notifyAccessibilityStateChanged();
4144            }
4145        }
4146    }
4147
4148    /**
4149     * Request that a rectangle of this view be visible on the screen,
4150     * scrolling if necessary just enough.
4151     *
4152     * <p>A View should call this if it maintains some notion of which part
4153     * of its content is interesting.  For example, a text editing view
4154     * should call this when its cursor moves.
4155     *
4156     * @param rectangle The rectangle.
4157     * @return Whether any parent scrolled.
4158     */
4159    public boolean requestRectangleOnScreen(Rect rectangle) {
4160        return requestRectangleOnScreen(rectangle, false);
4161    }
4162
4163    /**
4164     * Request that a rectangle of this view be visible on the screen,
4165     * scrolling if necessary just enough.
4166     *
4167     * <p>A View should call this if it maintains some notion of which part
4168     * of its content is interesting.  For example, a text editing view
4169     * should call this when its cursor moves.
4170     *
4171     * <p>When <code>immediate</code> is set to true, scrolling will not be
4172     * animated.
4173     *
4174     * @param rectangle The rectangle.
4175     * @param immediate True to forbid animated scrolling, false otherwise
4176     * @return Whether any parent scrolled.
4177     */
4178    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4179        View child = this;
4180        ViewParent parent = mParent;
4181        boolean scrolled = false;
4182        while (parent != null) {
4183            scrolled |= parent.requestChildRectangleOnScreen(child,
4184                    rectangle, immediate);
4185
4186            // offset rect so next call has the rectangle in the
4187            // coordinate system of its direct child.
4188            rectangle.offset(child.getLeft(), child.getTop());
4189            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4190
4191            if (!(parent instanceof View)) {
4192                break;
4193            }
4194
4195            child = (View) parent;
4196            parent = child.getParent();
4197        }
4198        return scrolled;
4199    }
4200
4201    /**
4202     * Called when this view wants to give up focus. If focus is cleared
4203     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4204     * <p>
4205     * <strong>Note:</strong> When a View clears focus the framework is trying
4206     * to give focus to the first focusable View from the top. Hence, if this
4207     * View is the first from the top that can take focus, then all callbacks
4208     * related to clearing focus will be invoked after wich the framework will
4209     * give focus to this view.
4210     * </p>
4211     */
4212    public void clearFocus() {
4213        if (DBG) {
4214            System.out.println(this + " clearFocus()");
4215        }
4216
4217        if ((mPrivateFlags & FOCUSED) != 0) {
4218            mPrivateFlags &= ~FOCUSED;
4219
4220            if (mParent != null) {
4221                mParent.clearChildFocus(this);
4222            }
4223
4224            onFocusChanged(false, 0, null);
4225
4226            refreshDrawableState();
4227
4228            ensureInputFocusOnFirstFocusable();
4229
4230            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4231                notifyAccessibilityStateChanged();
4232            }
4233        }
4234    }
4235
4236    void ensureInputFocusOnFirstFocusable() {
4237        View root = getRootView();
4238        if (root != null) {
4239            root.requestFocus();
4240        }
4241    }
4242
4243    /**
4244     * Called internally by the view system when a new view is getting focus.
4245     * This is what clears the old focus.
4246     */
4247    void unFocus() {
4248        if (DBG) {
4249            System.out.println(this + " unFocus()");
4250        }
4251
4252        if ((mPrivateFlags & FOCUSED) != 0) {
4253            mPrivateFlags &= ~FOCUSED;
4254
4255            onFocusChanged(false, 0, null);
4256            refreshDrawableState();
4257
4258            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4259                notifyAccessibilityStateChanged();
4260            }
4261        }
4262    }
4263
4264    /**
4265     * Returns true if this view has focus iteself, or is the ancestor of the
4266     * view that has focus.
4267     *
4268     * @return True if this view has or contains focus, false otherwise.
4269     */
4270    @ViewDebug.ExportedProperty(category = "focus")
4271    public boolean hasFocus() {
4272        return (mPrivateFlags & FOCUSED) != 0;
4273    }
4274
4275    /**
4276     * Returns true if this view is focusable or if it contains a reachable View
4277     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4278     * is a View whose parents do not block descendants focus.
4279     *
4280     * Only {@link #VISIBLE} views are considered focusable.
4281     *
4282     * @return True if the view is focusable or if the view contains a focusable
4283     *         View, false otherwise.
4284     *
4285     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4286     */
4287    public boolean hasFocusable() {
4288        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4289    }
4290
4291    /**
4292     * Called by the view system when the focus state of this view changes.
4293     * When the focus change event is caused by directional navigation, direction
4294     * and previouslyFocusedRect provide insight into where the focus is coming from.
4295     * When overriding, be sure to call up through to the super class so that
4296     * the standard focus handling will occur.
4297     *
4298     * @param gainFocus True if the View has focus; false otherwise.
4299     * @param direction The direction focus has moved when requestFocus()
4300     *                  is called to give this view focus. Values are
4301     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4302     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4303     *                  It may not always apply, in which case use the default.
4304     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4305     *        system, of the previously focused view.  If applicable, this will be
4306     *        passed in as finer grained information about where the focus is coming
4307     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4308     */
4309    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4310        if (gainFocus) {
4311            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4312                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4313            }
4314        }
4315
4316        InputMethodManager imm = InputMethodManager.peekInstance();
4317        if (!gainFocus) {
4318            if (isPressed()) {
4319                setPressed(false);
4320            }
4321            if (imm != null && mAttachInfo != null
4322                    && mAttachInfo.mHasWindowFocus) {
4323                imm.focusOut(this);
4324            }
4325            onFocusLost();
4326        } else if (imm != null && mAttachInfo != null
4327                && mAttachInfo.mHasWindowFocus) {
4328            imm.focusIn(this);
4329        }
4330
4331        invalidate(true);
4332        ListenerInfo li = mListenerInfo;
4333        if (li != null && li.mOnFocusChangeListener != null) {
4334            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4335        }
4336
4337        if (mAttachInfo != null) {
4338            mAttachInfo.mKeyDispatchState.reset(this);
4339        }
4340    }
4341
4342    /**
4343     * Sends an accessibility event of the given type. If accessiiblity is
4344     * not enabled this method has no effect. The default implementation calls
4345     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4346     * to populate information about the event source (this View), then calls
4347     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4348     * populate the text content of the event source including its descendants,
4349     * and last calls
4350     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4351     * on its parent to resuest sending of the event to interested parties.
4352     * <p>
4353     * If an {@link AccessibilityDelegate} has been specified via calling
4354     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4355     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4356     * responsible for handling this call.
4357     * </p>
4358     *
4359     * @param eventType The type of the event to send, as defined by several types from
4360     * {@link android.view.accessibility.AccessibilityEvent}, such as
4361     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4362     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4363     *
4364     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4365     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4366     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4367     * @see AccessibilityDelegate
4368     */
4369    public void sendAccessibilityEvent(int eventType) {
4370        if (mAccessibilityDelegate != null) {
4371            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4372        } else {
4373            sendAccessibilityEventInternal(eventType);
4374        }
4375    }
4376
4377    /**
4378     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4379     * {@link AccessibilityEvent} to make an announcement which is related to some
4380     * sort of a context change for which none of the events representing UI transitions
4381     * is a good fit. For example, announcing a new page in a book. If accessibility
4382     * is not enabled this method does nothing.
4383     *
4384     * @param text The announcement text.
4385     */
4386    public void announceForAccessibility(CharSequence text) {
4387        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4388            AccessibilityEvent event = AccessibilityEvent.obtain(
4389                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4390            event.getText().add(text);
4391            sendAccessibilityEventUnchecked(event);
4392        }
4393    }
4394
4395    /**
4396     * @see #sendAccessibilityEvent(int)
4397     *
4398     * Note: Called from the default {@link AccessibilityDelegate}.
4399     */
4400    void sendAccessibilityEventInternal(int eventType) {
4401        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4402            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4403        }
4404    }
4405
4406    /**
4407     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4408     * takes as an argument an empty {@link AccessibilityEvent} and does not
4409     * perform a check whether accessibility is enabled.
4410     * <p>
4411     * If an {@link AccessibilityDelegate} has been specified via calling
4412     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4413     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4414     * is responsible for handling this call.
4415     * </p>
4416     *
4417     * @param event The event to send.
4418     *
4419     * @see #sendAccessibilityEvent(int)
4420     */
4421    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4422        if (mAccessibilityDelegate != null) {
4423            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4424        } else {
4425            sendAccessibilityEventUncheckedInternal(event);
4426        }
4427    }
4428
4429    /**
4430     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4431     *
4432     * Note: Called from the default {@link AccessibilityDelegate}.
4433     */
4434    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4435        if (!isShown()) {
4436            return;
4437        }
4438        onInitializeAccessibilityEvent(event);
4439        // Only a subset of accessibility events populates text content.
4440        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4441            dispatchPopulateAccessibilityEvent(event);
4442        }
4443        // Intercept accessibility focus events fired by virtual nodes to keep
4444        // track of accessibility focus position in such nodes.
4445        final int eventType = event.getEventType();
4446        switch (eventType) {
4447            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4448                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4449                        event.getSourceNodeId());
4450                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4451                    ViewRootImpl viewRootImpl = getViewRootImpl();
4452                    if (viewRootImpl != null) {
4453                        viewRootImpl.setAccessibilityFocusedHost(this);
4454                    }
4455                }
4456            } break;
4457            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4458                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4459                        event.getSourceNodeId());
4460                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4461                    ViewRootImpl viewRootImpl = getViewRootImpl();
4462                    if (viewRootImpl != null) {
4463                        viewRootImpl.setAccessibilityFocusedHost(null);
4464                    }
4465                }
4466            } break;
4467        }
4468        // In the beginning we called #isShown(), so we know that getParent() is not null.
4469        getParent().requestSendAccessibilityEvent(this, event);
4470    }
4471
4472    /**
4473     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4474     * to its children for adding their text content to the event. Note that the
4475     * event text is populated in a separate dispatch path since we add to the
4476     * event not only the text of the source but also the text of all its descendants.
4477     * A typical implementation will call
4478     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4479     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4480     * on each child. Override this method if custom population of the event text
4481     * content is required.
4482     * <p>
4483     * If an {@link AccessibilityDelegate} has been specified via calling
4484     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4485     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4486     * is responsible for handling this call.
4487     * </p>
4488     * <p>
4489     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4490     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4491     * </p>
4492     *
4493     * @param event The event.
4494     *
4495     * @return True if the event population was completed.
4496     */
4497    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4498        if (mAccessibilityDelegate != null) {
4499            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4500        } else {
4501            return dispatchPopulateAccessibilityEventInternal(event);
4502        }
4503    }
4504
4505    /**
4506     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4507     *
4508     * Note: Called from the default {@link AccessibilityDelegate}.
4509     */
4510    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4511        onPopulateAccessibilityEvent(event);
4512        return false;
4513    }
4514
4515    /**
4516     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4517     * giving a chance to this View to populate the accessibility event with its
4518     * text content. While this method is free to modify event
4519     * attributes other than text content, doing so should normally be performed in
4520     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4521     * <p>
4522     * Example: Adding formatted date string to an accessibility event in addition
4523     *          to the text added by the super implementation:
4524     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4525     *     super.onPopulateAccessibilityEvent(event);
4526     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4527     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4528     *         mCurrentDate.getTimeInMillis(), flags);
4529     *     event.getText().add(selectedDateUtterance);
4530     * }</pre>
4531     * <p>
4532     * If an {@link AccessibilityDelegate} has been specified via calling
4533     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4534     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4535     * is responsible for handling this call.
4536     * </p>
4537     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4538     * information to the event, in case the default implementation has basic information to add.
4539     * </p>
4540     *
4541     * @param event The accessibility event which to populate.
4542     *
4543     * @see #sendAccessibilityEvent(int)
4544     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4545     */
4546    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4547        if (mAccessibilityDelegate != null) {
4548            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4549        } else {
4550            onPopulateAccessibilityEventInternal(event);
4551        }
4552    }
4553
4554    /**
4555     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4556     *
4557     * Note: Called from the default {@link AccessibilityDelegate}.
4558     */
4559    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4560
4561    }
4562
4563    /**
4564     * Initializes an {@link AccessibilityEvent} with information about
4565     * this View which is the event source. In other words, the source of
4566     * an accessibility event is the view whose state change triggered firing
4567     * the event.
4568     * <p>
4569     * Example: Setting the password property of an event in addition
4570     *          to properties set by the super implementation:
4571     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4572     *     super.onInitializeAccessibilityEvent(event);
4573     *     event.setPassword(true);
4574     * }</pre>
4575     * <p>
4576     * If an {@link AccessibilityDelegate} has been specified via calling
4577     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4578     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4579     * is responsible for handling this call.
4580     * </p>
4581     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4582     * information to the event, in case the default implementation has basic information to add.
4583     * </p>
4584     * @param event The event to initialize.
4585     *
4586     * @see #sendAccessibilityEvent(int)
4587     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4588     */
4589    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4590        if (mAccessibilityDelegate != null) {
4591            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4592        } else {
4593            onInitializeAccessibilityEventInternal(event);
4594        }
4595    }
4596
4597    /**
4598     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4599     *
4600     * Note: Called from the default {@link AccessibilityDelegate}.
4601     */
4602    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4603        event.setSource(this);
4604        event.setClassName(View.class.getName());
4605        event.setPackageName(getContext().getPackageName());
4606        event.setEnabled(isEnabled());
4607        event.setContentDescription(mContentDescription);
4608
4609        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4610            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4611            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4612                    FOCUSABLES_ALL);
4613            event.setItemCount(focusablesTempList.size());
4614            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4615            focusablesTempList.clear();
4616        }
4617    }
4618
4619    /**
4620     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4621     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4622     * This method is responsible for obtaining an accessibility node info from a
4623     * pool of reusable instances and calling
4624     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4625     * initialize the former.
4626     * <p>
4627     * Note: The client is responsible for recycling the obtained instance by calling
4628     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4629     * </p>
4630     *
4631     * @return A populated {@link AccessibilityNodeInfo}.
4632     *
4633     * @see AccessibilityNodeInfo
4634     */
4635    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4636        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4637        if (provider != null) {
4638            return provider.createAccessibilityNodeInfo(View.NO_ID);
4639        } else {
4640            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4641            onInitializeAccessibilityNodeInfo(info);
4642            return info;
4643        }
4644    }
4645
4646    /**
4647     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4648     * The base implementation sets:
4649     * <ul>
4650     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4651     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4652     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4653     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4654     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4655     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4656     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4657     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4658     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4659     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4660     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4661     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4662     * </ul>
4663     * <p>
4664     * Subclasses should override this method, call the super implementation,
4665     * and set additional attributes.
4666     * </p>
4667     * <p>
4668     * If an {@link AccessibilityDelegate} has been specified via calling
4669     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4670     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4671     * is responsible for handling this call.
4672     * </p>
4673     *
4674     * @param info The instance to initialize.
4675     */
4676    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4677        if (mAccessibilityDelegate != null) {
4678            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4679        } else {
4680            onInitializeAccessibilityNodeInfoInternal(info);
4681        }
4682    }
4683
4684    /**
4685     * Gets the location of this view in screen coordintates.
4686     *
4687     * @param outRect The output location
4688     */
4689    private void getBoundsOnScreen(Rect outRect) {
4690        if (mAttachInfo == null) {
4691            return;
4692        }
4693
4694        RectF position = mAttachInfo.mTmpTransformRect;
4695        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4696
4697        if (!hasIdentityMatrix()) {
4698            getMatrix().mapRect(position);
4699        }
4700
4701        position.offset(mLeft, mTop);
4702
4703        ViewParent parent = mParent;
4704        while (parent instanceof View) {
4705            View parentView = (View) parent;
4706
4707            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4708
4709            if (!parentView.hasIdentityMatrix()) {
4710                parentView.getMatrix().mapRect(position);
4711            }
4712
4713            position.offset(parentView.mLeft, parentView.mTop);
4714
4715            parent = parentView.mParent;
4716        }
4717
4718        if (parent instanceof ViewRootImpl) {
4719            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4720            position.offset(0, -viewRootImpl.mCurScrollY);
4721        }
4722
4723        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4724
4725        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4726                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4727    }
4728
4729    /**
4730     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4731     *
4732     * Note: Called from the default {@link AccessibilityDelegate}.
4733     */
4734    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4735        Rect bounds = mAttachInfo.mTmpInvalRect;
4736        getDrawingRect(bounds);
4737        info.setBoundsInParent(bounds);
4738
4739        getBoundsOnScreen(bounds);
4740        info.setBoundsInScreen(bounds);
4741
4742        ViewParent parent = getParentForAccessibility();
4743        if (parent instanceof View) {
4744            info.setParent((View) parent);
4745        }
4746
4747        info.setVisibleToUser(isVisibleToUser());
4748
4749        info.setPackageName(mContext.getPackageName());
4750        info.setClassName(View.class.getName());
4751        info.setContentDescription(getContentDescription());
4752
4753        info.setEnabled(isEnabled());
4754        info.setClickable(isClickable());
4755        info.setFocusable(isFocusable());
4756        info.setFocused(isFocused());
4757        info.setAccessibilityFocused(isAccessibilityFocused());
4758        info.setSelected(isSelected());
4759        info.setLongClickable(isLongClickable());
4760
4761        // TODO: These make sense only if we are in an AdapterView but all
4762        // views can be selected. Maybe from accessiiblity perspective
4763        // we should report as selectable view in an AdapterView.
4764        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4765        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4766
4767        if (isFocusable()) {
4768            if (isFocused()) {
4769                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4770            } else {
4771                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4772            }
4773        }
4774
4775        if (!isAccessibilityFocused()) {
4776            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4777        } else {
4778            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4779        }
4780
4781        if (isClickable() && isEnabled()) {
4782            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4783        }
4784
4785        if (isLongClickable() && isEnabled()) {
4786            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4787        }
4788
4789        if (mContentDescription != null && mContentDescription.length() > 0) {
4790            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4791            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4792            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4793                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4794                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4795        }
4796    }
4797
4798    /**
4799     * Computes whether this view is visible to the user. Such a view is
4800     * attached, visible, all its predecessors are visible, it is not clipped
4801     * entirely by its predecessors, and has an alpha greater than zero.
4802     *
4803     * @return Whether the view is visible on the screen.
4804     *
4805     * @hide
4806     */
4807    protected boolean isVisibleToUser() {
4808        return isVisibleToUser(null);
4809    }
4810
4811    /**
4812     * Computes whether the given portion of this view is visible to the user. Such a view is
4813     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4814     * the specified portion is not clipped entirely by its predecessors.
4815     *
4816     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4817     *                    <code>null</code>, and the entire view will be tested in this case.
4818     *                    When <code>true</code> is returned by the function, the actual visible
4819     *                    region will be stored in this parameter; that is, if boundInView is fully
4820     *                    contained within the view, no modification will be made, otherwise regions
4821     *                    outside of the visible area of the view will be clipped.
4822     *
4823     * @return Whether the specified portion of the view is visible on the screen.
4824     *
4825     * @hide
4826     */
4827    protected boolean isVisibleToUser(Rect boundInView) {
4828        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4829        Point offset = mAttachInfo.mPoint;
4830        // The first two checks are made also made by isShown() which
4831        // however traverses the tree up to the parent to catch that.
4832        // Therefore, we do some fail fast check to minimize the up
4833        // tree traversal.
4834        boolean isVisible = mAttachInfo != null
4835            && mAttachInfo.mWindowVisibility == View.VISIBLE
4836            && getAlpha() > 0
4837            && isShown()
4838            && getGlobalVisibleRect(visibleRect, offset);
4839            if (isVisible && boundInView != null) {
4840                visibleRect.offset(-offset.x, -offset.y);
4841                isVisible &= boundInView.intersect(visibleRect);
4842            }
4843            return isVisible;
4844    }
4845
4846    /**
4847     * Sets a delegate for implementing accessibility support via compositon as
4848     * opposed to inheritance. The delegate's primary use is for implementing
4849     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4850     *
4851     * @param delegate The delegate instance.
4852     *
4853     * @see AccessibilityDelegate
4854     */
4855    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4856        mAccessibilityDelegate = delegate;
4857    }
4858
4859    /**
4860     * Gets the provider for managing a virtual view hierarchy rooted at this View
4861     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4862     * that explore the window content.
4863     * <p>
4864     * If this method returns an instance, this instance is responsible for managing
4865     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4866     * View including the one representing the View itself. Similarly the returned
4867     * instance is responsible for performing accessibility actions on any virtual
4868     * view or the root view itself.
4869     * </p>
4870     * <p>
4871     * If an {@link AccessibilityDelegate} has been specified via calling
4872     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4873     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4874     * is responsible for handling this call.
4875     * </p>
4876     *
4877     * @return The provider.
4878     *
4879     * @see AccessibilityNodeProvider
4880     */
4881    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4882        if (mAccessibilityDelegate != null) {
4883            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4884        } else {
4885            return null;
4886        }
4887    }
4888
4889    /**
4890     * Gets the unique identifier of this view on the screen for accessibility purposes.
4891     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4892     *
4893     * @return The view accessibility id.
4894     *
4895     * @hide
4896     */
4897    public int getAccessibilityViewId() {
4898        if (mAccessibilityViewId == NO_ID) {
4899            mAccessibilityViewId = sNextAccessibilityViewId++;
4900        }
4901        return mAccessibilityViewId;
4902    }
4903
4904    /**
4905     * Gets the unique identifier of the window in which this View reseides.
4906     *
4907     * @return The window accessibility id.
4908     *
4909     * @hide
4910     */
4911    public int getAccessibilityWindowId() {
4912        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4913    }
4914
4915    /**
4916     * Gets the {@link View} description. It briefly describes the view and is
4917     * primarily used for accessibility support. Set this property to enable
4918     * better accessibility support for your application. This is especially
4919     * true for views that do not have textual representation (For example,
4920     * ImageButton).
4921     *
4922     * @return The content description.
4923     *
4924     * @attr ref android.R.styleable#View_contentDescription
4925     */
4926    @ViewDebug.ExportedProperty(category = "accessibility")
4927    public CharSequence getContentDescription() {
4928        return mContentDescription;
4929    }
4930
4931    /**
4932     * Sets the {@link View} description. It briefly describes the view and is
4933     * primarily used for accessibility support. Set this property to enable
4934     * better accessibility support for your application. This is especially
4935     * true for views that do not have textual representation (For example,
4936     * ImageButton).
4937     *
4938     * @param contentDescription The content description.
4939     *
4940     * @attr ref android.R.styleable#View_contentDescription
4941     */
4942    @RemotableViewMethod
4943    public void setContentDescription(CharSequence contentDescription) {
4944        mContentDescription = contentDescription;
4945    }
4946
4947    /**
4948     * Invoked whenever this view loses focus, either by losing window focus or by losing
4949     * focus within its window. This method can be used to clear any state tied to the
4950     * focus. For instance, if a button is held pressed with the trackball and the window
4951     * loses focus, this method can be used to cancel the press.
4952     *
4953     * Subclasses of View overriding this method should always call super.onFocusLost().
4954     *
4955     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4956     * @see #onWindowFocusChanged(boolean)
4957     *
4958     * @hide pending API council approval
4959     */
4960    protected void onFocusLost() {
4961        resetPressedState();
4962    }
4963
4964    private void resetPressedState() {
4965        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4966            return;
4967        }
4968
4969        if (isPressed()) {
4970            setPressed(false);
4971
4972            if (!mHasPerformedLongPress) {
4973                removeLongPressCallback();
4974            }
4975        }
4976    }
4977
4978    /**
4979     * Returns true if this view has focus
4980     *
4981     * @return True if this view has focus, false otherwise.
4982     */
4983    @ViewDebug.ExportedProperty(category = "focus")
4984    public boolean isFocused() {
4985        return (mPrivateFlags & FOCUSED) != 0;
4986    }
4987
4988    /**
4989     * Find the view in the hierarchy rooted at this view that currently has
4990     * focus.
4991     *
4992     * @return The view that currently has focus, or null if no focused view can
4993     *         be found.
4994     */
4995    public View findFocus() {
4996        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4997    }
4998
4999    /**
5000     * Indicates whether this view is one of the set of scrollable containers in
5001     * its window.
5002     *
5003     * @return whether this view is one of the set of scrollable containers in
5004     * its window
5005     *
5006     * @attr ref android.R.styleable#View_isScrollContainer
5007     */
5008    public boolean isScrollContainer() {
5009        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5010    }
5011
5012    /**
5013     * Change whether this view is one of the set of scrollable containers in
5014     * its window.  This will be used to determine whether the window can
5015     * resize or must pan when a soft input area is open -- scrollable
5016     * containers allow the window to use resize mode since the container
5017     * will appropriately shrink.
5018     *
5019     * @attr ref android.R.styleable#View_isScrollContainer
5020     */
5021    public void setScrollContainer(boolean isScrollContainer) {
5022        if (isScrollContainer) {
5023            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5024                mAttachInfo.mScrollContainers.add(this);
5025                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5026            }
5027            mPrivateFlags |= SCROLL_CONTAINER;
5028        } else {
5029            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5030                mAttachInfo.mScrollContainers.remove(this);
5031            }
5032            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5033        }
5034    }
5035
5036    /**
5037     * Returns the quality of the drawing cache.
5038     *
5039     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5040     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5041     *
5042     * @see #setDrawingCacheQuality(int)
5043     * @see #setDrawingCacheEnabled(boolean)
5044     * @see #isDrawingCacheEnabled()
5045     *
5046     * @attr ref android.R.styleable#View_drawingCacheQuality
5047     */
5048    public int getDrawingCacheQuality() {
5049        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5050    }
5051
5052    /**
5053     * Set the drawing cache quality of this view. This value is used only when the
5054     * drawing cache is enabled
5055     *
5056     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5057     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5058     *
5059     * @see #getDrawingCacheQuality()
5060     * @see #setDrawingCacheEnabled(boolean)
5061     * @see #isDrawingCacheEnabled()
5062     *
5063     * @attr ref android.R.styleable#View_drawingCacheQuality
5064     */
5065    public void setDrawingCacheQuality(int quality) {
5066        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5067    }
5068
5069    /**
5070     * Returns whether the screen should remain on, corresponding to the current
5071     * value of {@link #KEEP_SCREEN_ON}.
5072     *
5073     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5074     *
5075     * @see #setKeepScreenOn(boolean)
5076     *
5077     * @attr ref android.R.styleable#View_keepScreenOn
5078     */
5079    public boolean getKeepScreenOn() {
5080        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5081    }
5082
5083    /**
5084     * Controls whether the screen should remain on, modifying the
5085     * value of {@link #KEEP_SCREEN_ON}.
5086     *
5087     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5088     *
5089     * @see #getKeepScreenOn()
5090     *
5091     * @attr ref android.R.styleable#View_keepScreenOn
5092     */
5093    public void setKeepScreenOn(boolean keepScreenOn) {
5094        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5095    }
5096
5097    /**
5098     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5099     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5100     *
5101     * @attr ref android.R.styleable#View_nextFocusLeft
5102     */
5103    public int getNextFocusLeftId() {
5104        return mNextFocusLeftId;
5105    }
5106
5107    /**
5108     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5109     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5110     * decide automatically.
5111     *
5112     * @attr ref android.R.styleable#View_nextFocusLeft
5113     */
5114    public void setNextFocusLeftId(int nextFocusLeftId) {
5115        mNextFocusLeftId = nextFocusLeftId;
5116    }
5117
5118    /**
5119     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5120     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5121     *
5122     * @attr ref android.R.styleable#View_nextFocusRight
5123     */
5124    public int getNextFocusRightId() {
5125        return mNextFocusRightId;
5126    }
5127
5128    /**
5129     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5130     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5131     * decide automatically.
5132     *
5133     * @attr ref android.R.styleable#View_nextFocusRight
5134     */
5135    public void setNextFocusRightId(int nextFocusRightId) {
5136        mNextFocusRightId = nextFocusRightId;
5137    }
5138
5139    /**
5140     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5141     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5142     *
5143     * @attr ref android.R.styleable#View_nextFocusUp
5144     */
5145    public int getNextFocusUpId() {
5146        return mNextFocusUpId;
5147    }
5148
5149    /**
5150     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5151     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5152     * decide automatically.
5153     *
5154     * @attr ref android.R.styleable#View_nextFocusUp
5155     */
5156    public void setNextFocusUpId(int nextFocusUpId) {
5157        mNextFocusUpId = nextFocusUpId;
5158    }
5159
5160    /**
5161     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5162     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5163     *
5164     * @attr ref android.R.styleable#View_nextFocusDown
5165     */
5166    public int getNextFocusDownId() {
5167        return mNextFocusDownId;
5168    }
5169
5170    /**
5171     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5172     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5173     * decide automatically.
5174     *
5175     * @attr ref android.R.styleable#View_nextFocusDown
5176     */
5177    public void setNextFocusDownId(int nextFocusDownId) {
5178        mNextFocusDownId = nextFocusDownId;
5179    }
5180
5181    /**
5182     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5183     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5184     *
5185     * @attr ref android.R.styleable#View_nextFocusForward
5186     */
5187    public int getNextFocusForwardId() {
5188        return mNextFocusForwardId;
5189    }
5190
5191    /**
5192     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5193     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5194     * decide automatically.
5195     *
5196     * @attr ref android.R.styleable#View_nextFocusForward
5197     */
5198    public void setNextFocusForwardId(int nextFocusForwardId) {
5199        mNextFocusForwardId = nextFocusForwardId;
5200    }
5201
5202    /**
5203     * Returns the visibility of this view and all of its ancestors
5204     *
5205     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5206     */
5207    public boolean isShown() {
5208        View current = this;
5209        //noinspection ConstantConditions
5210        do {
5211            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5212                return false;
5213            }
5214            ViewParent parent = current.mParent;
5215            if (parent == null) {
5216                return false; // We are not attached to the view root
5217            }
5218            if (!(parent instanceof View)) {
5219                return true;
5220            }
5221            current = (View) parent;
5222        } while (current != null);
5223
5224        return false;
5225    }
5226
5227    /**
5228     * Called by the view hierarchy when the content insets for a window have
5229     * changed, to allow it to adjust its content to fit within those windows.
5230     * The content insets tell you the space that the status bar, input method,
5231     * and other system windows infringe on the application's window.
5232     *
5233     * <p>You do not normally need to deal with this function, since the default
5234     * window decoration given to applications takes care of applying it to the
5235     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5236     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5237     * and your content can be placed under those system elements.  You can then
5238     * use this method within your view hierarchy if you have parts of your UI
5239     * which you would like to ensure are not being covered.
5240     *
5241     * <p>The default implementation of this method simply applies the content
5242     * inset's to the view's padding, consuming that content (modifying the
5243     * insets to be 0), and returning true.  This behavior is off by default, but can
5244     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5245     *
5246     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5247     * insets object is propagated down the hierarchy, so any changes made to it will
5248     * be seen by all following views (including potentially ones above in
5249     * the hierarchy since this is a depth-first traversal).  The first view
5250     * that returns true will abort the entire traversal.
5251     *
5252     * <p>The default implementation works well for a situation where it is
5253     * used with a container that covers the entire window, allowing it to
5254     * apply the appropriate insets to its content on all edges.  If you need
5255     * a more complicated layout (such as two different views fitting system
5256     * windows, one on the top of the window, and one on the bottom),
5257     * you can override the method and handle the insets however you would like.
5258     * Note that the insets provided by the framework are always relative to the
5259     * far edges of the window, not accounting for the location of the called view
5260     * within that window.  (In fact when this method is called you do not yet know
5261     * where the layout will place the view, as it is done before layout happens.)
5262     *
5263     * <p>Note: unlike many View methods, there is no dispatch phase to this
5264     * call.  If you are overriding it in a ViewGroup and want to allow the
5265     * call to continue to your children, you must be sure to call the super
5266     * implementation.
5267     *
5268     * <p>Here is a sample layout that makes use of fitting system windows
5269     * to have controls for a video view placed inside of the window decorations
5270     * that it hides and shows.  This can be used with code like the second
5271     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5272     *
5273     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5274     *
5275     * @param insets Current content insets of the window.  Prior to
5276     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5277     * the insets or else you and Android will be unhappy.
5278     *
5279     * @return Return true if this view applied the insets and it should not
5280     * continue propagating further down the hierarchy, false otherwise.
5281     * @see #getFitsSystemWindows()
5282     * @see #setFitsSystemWindows()
5283     * @see #setSystemUiVisibility(int)
5284     */
5285    protected boolean fitSystemWindows(Rect insets) {
5286        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5287            mUserPaddingStart = -1;
5288            mUserPaddingEnd = -1;
5289            mUserPaddingRelative = false;
5290            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5291                    || mAttachInfo == null
5292                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5293                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5294                return true;
5295            } else {
5296                internalSetPadding(0, 0, 0, 0);
5297                return false;
5298            }
5299        }
5300        return false;
5301    }
5302
5303    /**
5304     * Sets whether or not this view should account for system screen decorations
5305     * such as the status bar and inset its content; that is, controlling whether
5306     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5307     * executed.  See that method for more details.
5308     *
5309     * <p>Note that if you are providing your own implementation of
5310     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5311     * flag to true -- your implementation will be overriding the default
5312     * implementation that checks this flag.
5313     *
5314     * @param fitSystemWindows If true, then the default implementation of
5315     * {@link #fitSystemWindows(Rect)} will be executed.
5316     *
5317     * @attr ref android.R.styleable#View_fitsSystemWindows
5318     * @see #getFitsSystemWindows()
5319     * @see #fitSystemWindows(Rect)
5320     * @see #setSystemUiVisibility(int)
5321     */
5322    public void setFitsSystemWindows(boolean fitSystemWindows) {
5323        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5324    }
5325
5326    /**
5327     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5328     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5329     * will be executed.
5330     *
5331     * @return Returns true if the default implementation of
5332     * {@link #fitSystemWindows(Rect)} will be executed.
5333     *
5334     * @attr ref android.R.styleable#View_fitsSystemWindows
5335     * @see #setFitsSystemWindows()
5336     * @see #fitSystemWindows(Rect)
5337     * @see #setSystemUiVisibility(int)
5338     */
5339    public boolean getFitsSystemWindows() {
5340        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5341    }
5342
5343    /** @hide */
5344    public boolean fitsSystemWindows() {
5345        return getFitsSystemWindows();
5346    }
5347
5348    /**
5349     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5350     */
5351    public void requestFitSystemWindows() {
5352        if (mParent != null) {
5353            mParent.requestFitSystemWindows();
5354        }
5355    }
5356
5357    /**
5358     * For use by PhoneWindow to make its own system window fitting optional.
5359     * @hide
5360     */
5361    public void makeOptionalFitsSystemWindows() {
5362        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5363    }
5364
5365    /**
5366     * Returns the visibility status for this view.
5367     *
5368     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5369     * @attr ref android.R.styleable#View_visibility
5370     */
5371    @ViewDebug.ExportedProperty(mapping = {
5372        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5373        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5374        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5375    })
5376    public int getVisibility() {
5377        return mViewFlags & VISIBILITY_MASK;
5378    }
5379
5380    /**
5381     * Set the enabled state of this view.
5382     *
5383     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5384     * @attr ref android.R.styleable#View_visibility
5385     */
5386    @RemotableViewMethod
5387    public void setVisibility(int visibility) {
5388        setFlags(visibility, VISIBILITY_MASK);
5389        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5390    }
5391
5392    /**
5393     * Returns the enabled status for this view. The interpretation of the
5394     * enabled state varies by subclass.
5395     *
5396     * @return True if this view is enabled, false otherwise.
5397     */
5398    @ViewDebug.ExportedProperty
5399    public boolean isEnabled() {
5400        return (mViewFlags & ENABLED_MASK) == ENABLED;
5401    }
5402
5403    /**
5404     * Set the enabled state of this view. The interpretation of the enabled
5405     * state varies by subclass.
5406     *
5407     * @param enabled True if this view is enabled, false otherwise.
5408     */
5409    @RemotableViewMethod
5410    public void setEnabled(boolean enabled) {
5411        if (enabled == isEnabled()) return;
5412
5413        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5414
5415        /*
5416         * The View most likely has to change its appearance, so refresh
5417         * the drawable state.
5418         */
5419        refreshDrawableState();
5420
5421        // Invalidate too, since the default behavior for views is to be
5422        // be drawn at 50% alpha rather than to change the drawable.
5423        invalidate(true);
5424    }
5425
5426    /**
5427     * Set whether this view can receive the focus.
5428     *
5429     * Setting this to false will also ensure that this view is not focusable
5430     * in touch mode.
5431     *
5432     * @param focusable If true, this view can receive the focus.
5433     *
5434     * @see #setFocusableInTouchMode(boolean)
5435     * @attr ref android.R.styleable#View_focusable
5436     */
5437    public void setFocusable(boolean focusable) {
5438        if (!focusable) {
5439            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5440        }
5441        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5442    }
5443
5444    /**
5445     * Set whether this view can receive focus while in touch mode.
5446     *
5447     * Setting this to true will also ensure that this view is focusable.
5448     *
5449     * @param focusableInTouchMode If true, this view can receive the focus while
5450     *   in touch mode.
5451     *
5452     * @see #setFocusable(boolean)
5453     * @attr ref android.R.styleable#View_focusableInTouchMode
5454     */
5455    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5456        // Focusable in touch mode should always be set before the focusable flag
5457        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5458        // which, in touch mode, will not successfully request focus on this view
5459        // because the focusable in touch mode flag is not set
5460        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5461        if (focusableInTouchMode) {
5462            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5463        }
5464    }
5465
5466    /**
5467     * Set whether this view should have sound effects enabled for events such as
5468     * clicking and touching.
5469     *
5470     * <p>You may wish to disable sound effects for a view if you already play sounds,
5471     * for instance, a dial key that plays dtmf tones.
5472     *
5473     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5474     * @see #isSoundEffectsEnabled()
5475     * @see #playSoundEffect(int)
5476     * @attr ref android.R.styleable#View_soundEffectsEnabled
5477     */
5478    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5479        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5480    }
5481
5482    /**
5483     * @return whether this view should have sound effects enabled for events such as
5484     *     clicking and touching.
5485     *
5486     * @see #setSoundEffectsEnabled(boolean)
5487     * @see #playSoundEffect(int)
5488     * @attr ref android.R.styleable#View_soundEffectsEnabled
5489     */
5490    @ViewDebug.ExportedProperty
5491    public boolean isSoundEffectsEnabled() {
5492        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5493    }
5494
5495    /**
5496     * Set whether this view should have haptic feedback for events such as
5497     * long presses.
5498     *
5499     * <p>You may wish to disable haptic feedback if your view already controls
5500     * its own haptic feedback.
5501     *
5502     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5503     * @see #isHapticFeedbackEnabled()
5504     * @see #performHapticFeedback(int)
5505     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5506     */
5507    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5508        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5509    }
5510
5511    /**
5512     * @return whether this view should have haptic feedback enabled for events
5513     * long presses.
5514     *
5515     * @see #setHapticFeedbackEnabled(boolean)
5516     * @see #performHapticFeedback(int)
5517     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5518     */
5519    @ViewDebug.ExportedProperty
5520    public boolean isHapticFeedbackEnabled() {
5521        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5522    }
5523
5524    /**
5525     * Returns the layout direction for this view.
5526     *
5527     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5528     *   {@link #LAYOUT_DIRECTION_RTL},
5529     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5530     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5531     * @attr ref android.R.styleable#View_layoutDirection
5532     */
5533    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5534        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5535        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5536        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5537        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5538    })
5539    public int getLayoutDirection() {
5540        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5541    }
5542
5543    /**
5544     * Set the layout direction for this view. This will propagate a reset of layout direction
5545     * resolution to the view's children and resolve layout direction for this view.
5546     *
5547     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5548     *   {@link #LAYOUT_DIRECTION_RTL},
5549     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5550     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5551     *
5552     * @attr ref android.R.styleable#View_layoutDirection
5553     */
5554    @RemotableViewMethod
5555    public void setLayoutDirection(int layoutDirection) {
5556        if (getLayoutDirection() != layoutDirection) {
5557            // Reset the current layout direction and the resolved one
5558            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5559            resetResolvedLayoutDirection();
5560            // Set the new layout direction (filtered) and ask for a layout pass
5561            mPrivateFlags2 |=
5562                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5563            requestLayout();
5564        }
5565    }
5566
5567    /**
5568     * Returns the resolved layout direction for this view.
5569     *
5570     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5571     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5572     */
5573    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5574        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5575        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5576    })
5577    public int getResolvedLayoutDirection() {
5578        // The layout diretion will be resolved only if needed
5579        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5580            resolveLayoutDirection();
5581        }
5582        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5583                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5584    }
5585
5586    /**
5587     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5588     * layout attribute and/or the inherited value from the parent
5589     *
5590     * @return true if the layout is right-to-left.
5591     */
5592    @ViewDebug.ExportedProperty(category = "layout")
5593    public boolean isLayoutRtl() {
5594        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5595    }
5596
5597    /**
5598     * Indicates whether the view is currently tracking transient state that the
5599     * app should not need to concern itself with saving and restoring, but that
5600     * the framework should take special note to preserve when possible.
5601     *
5602     * <p>A view with transient state cannot be trivially rebound from an external
5603     * data source, such as an adapter binding item views in a list. This may be
5604     * because the view is performing an animation, tracking user selection
5605     * of content, or similar.</p>
5606     *
5607     * @return true if the view has transient state
5608     */
5609    @ViewDebug.ExportedProperty(category = "layout")
5610    public boolean hasTransientState() {
5611        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5612    }
5613
5614    /**
5615     * Set whether this view is currently tracking transient state that the
5616     * framework should attempt to preserve when possible. This flag is reference counted,
5617     * so every call to setHasTransientState(true) should be paired with a later call
5618     * to setHasTransientState(false).
5619     *
5620     * <p>A view with transient state cannot be trivially rebound from an external
5621     * data source, such as an adapter binding item views in a list. This may be
5622     * because the view is performing an animation, tracking user selection
5623     * of content, or similar.</p>
5624     *
5625     * @param hasTransientState true if this view has transient state
5626     */
5627    public void setHasTransientState(boolean hasTransientState) {
5628        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5629                mTransientStateCount - 1;
5630        if (mTransientStateCount < 0) {
5631            mTransientStateCount = 0;
5632            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5633                    "unmatched pair of setHasTransientState calls");
5634        }
5635        if ((hasTransientState && mTransientStateCount == 1) ||
5636                (!hasTransientState && mTransientStateCount == 0)) {
5637            // update flag if we've just incremented up from 0 or decremented down to 0
5638            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5639                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5640            if (mParent != null) {
5641                try {
5642                    mParent.childHasTransientStateChanged(this, hasTransientState);
5643                } catch (AbstractMethodError e) {
5644                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5645                            " does not fully implement ViewParent", e);
5646                }
5647            }
5648        }
5649    }
5650
5651    /**
5652     * If this view doesn't do any drawing on its own, set this flag to
5653     * allow further optimizations. By default, this flag is not set on
5654     * View, but could be set on some View subclasses such as ViewGroup.
5655     *
5656     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5657     * you should clear this flag.
5658     *
5659     * @param willNotDraw whether or not this View draw on its own
5660     */
5661    public void setWillNotDraw(boolean willNotDraw) {
5662        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5663    }
5664
5665    /**
5666     * Returns whether or not this View draws on its own.
5667     *
5668     * @return true if this view has nothing to draw, false otherwise
5669     */
5670    @ViewDebug.ExportedProperty(category = "drawing")
5671    public boolean willNotDraw() {
5672        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5673    }
5674
5675    /**
5676     * When a View's drawing cache is enabled, drawing is redirected to an
5677     * offscreen bitmap. Some views, like an ImageView, must be able to
5678     * bypass this mechanism if they already draw a single bitmap, to avoid
5679     * unnecessary usage of the memory.
5680     *
5681     * @param willNotCacheDrawing true if this view does not cache its
5682     *        drawing, false otherwise
5683     */
5684    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5685        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5686    }
5687
5688    /**
5689     * Returns whether or not this View can cache its drawing or not.
5690     *
5691     * @return true if this view does not cache its drawing, false otherwise
5692     */
5693    @ViewDebug.ExportedProperty(category = "drawing")
5694    public boolean willNotCacheDrawing() {
5695        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5696    }
5697
5698    /**
5699     * Indicates whether this view reacts to click events or not.
5700     *
5701     * @return true if the view is clickable, false otherwise
5702     *
5703     * @see #setClickable(boolean)
5704     * @attr ref android.R.styleable#View_clickable
5705     */
5706    @ViewDebug.ExportedProperty
5707    public boolean isClickable() {
5708        return (mViewFlags & CLICKABLE) == CLICKABLE;
5709    }
5710
5711    /**
5712     * Enables or disables click events for this view. When a view
5713     * is clickable it will change its state to "pressed" on every click.
5714     * Subclasses should set the view clickable to visually react to
5715     * user's clicks.
5716     *
5717     * @param clickable true to make the view clickable, false otherwise
5718     *
5719     * @see #isClickable()
5720     * @attr ref android.R.styleable#View_clickable
5721     */
5722    public void setClickable(boolean clickable) {
5723        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5724    }
5725
5726    /**
5727     * Indicates whether this view reacts to long click events or not.
5728     *
5729     * @return true if the view is long clickable, false otherwise
5730     *
5731     * @see #setLongClickable(boolean)
5732     * @attr ref android.R.styleable#View_longClickable
5733     */
5734    public boolean isLongClickable() {
5735        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5736    }
5737
5738    /**
5739     * Enables or disables long click events for this view. When a view is long
5740     * clickable it reacts to the user holding down the button for a longer
5741     * duration than a tap. This event can either launch the listener or a
5742     * context menu.
5743     *
5744     * @param longClickable true to make the view long clickable, false otherwise
5745     * @see #isLongClickable()
5746     * @attr ref android.R.styleable#View_longClickable
5747     */
5748    public void setLongClickable(boolean longClickable) {
5749        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5750    }
5751
5752    /**
5753     * Sets the pressed state for this view.
5754     *
5755     * @see #isClickable()
5756     * @see #setClickable(boolean)
5757     *
5758     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5759     *        the View's internal state from a previously set "pressed" state.
5760     */
5761    public void setPressed(boolean pressed) {
5762        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5763
5764        if (pressed) {
5765            mPrivateFlags |= PRESSED;
5766        } else {
5767            mPrivateFlags &= ~PRESSED;
5768        }
5769
5770        if (needsRefresh) {
5771            refreshDrawableState();
5772        }
5773        dispatchSetPressed(pressed);
5774    }
5775
5776    /**
5777     * Dispatch setPressed to all of this View's children.
5778     *
5779     * @see #setPressed(boolean)
5780     *
5781     * @param pressed The new pressed state
5782     */
5783    protected void dispatchSetPressed(boolean pressed) {
5784    }
5785
5786    /**
5787     * Indicates whether the view is currently in pressed state. Unless
5788     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5789     * the pressed state.
5790     *
5791     * @see #setPressed(boolean)
5792     * @see #isClickable()
5793     * @see #setClickable(boolean)
5794     *
5795     * @return true if the view is currently pressed, false otherwise
5796     */
5797    public boolean isPressed() {
5798        return (mPrivateFlags & PRESSED) == PRESSED;
5799    }
5800
5801    /**
5802     * Indicates whether this view will save its state (that is,
5803     * whether its {@link #onSaveInstanceState} method will be called).
5804     *
5805     * @return Returns true if the view state saving is enabled, else false.
5806     *
5807     * @see #setSaveEnabled(boolean)
5808     * @attr ref android.R.styleable#View_saveEnabled
5809     */
5810    public boolean isSaveEnabled() {
5811        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5812    }
5813
5814    /**
5815     * Controls whether the saving of this view's state is
5816     * enabled (that is, whether its {@link #onSaveInstanceState} method
5817     * will be called).  Note that even if freezing is enabled, the
5818     * view still must have an id assigned to it (via {@link #setId(int)})
5819     * for its state to be saved.  This flag can only disable the
5820     * saving of this view; any child views may still have their state saved.
5821     *
5822     * @param enabled Set to false to <em>disable</em> state saving, or true
5823     * (the default) to allow it.
5824     *
5825     * @see #isSaveEnabled()
5826     * @see #setId(int)
5827     * @see #onSaveInstanceState()
5828     * @attr ref android.R.styleable#View_saveEnabled
5829     */
5830    public void setSaveEnabled(boolean enabled) {
5831        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5832    }
5833
5834    /**
5835     * Gets whether the framework should discard touches when the view's
5836     * window is obscured by another visible window.
5837     * Refer to the {@link View} security documentation for more details.
5838     *
5839     * @return True if touch filtering is enabled.
5840     *
5841     * @see #setFilterTouchesWhenObscured(boolean)
5842     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5843     */
5844    @ViewDebug.ExportedProperty
5845    public boolean getFilterTouchesWhenObscured() {
5846        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5847    }
5848
5849    /**
5850     * Sets whether the framework should discard touches when the view's
5851     * window is obscured by another visible window.
5852     * Refer to the {@link View} security documentation for more details.
5853     *
5854     * @param enabled True if touch filtering should be enabled.
5855     *
5856     * @see #getFilterTouchesWhenObscured
5857     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5858     */
5859    public void setFilterTouchesWhenObscured(boolean enabled) {
5860        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5861                FILTER_TOUCHES_WHEN_OBSCURED);
5862    }
5863
5864    /**
5865     * Indicates whether the entire hierarchy under this view will save its
5866     * state when a state saving traversal occurs from its parent.  The default
5867     * is true; if false, these views will not be saved unless
5868     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5869     *
5870     * @return Returns true if the view state saving from parent is enabled, else false.
5871     *
5872     * @see #setSaveFromParentEnabled(boolean)
5873     */
5874    public boolean isSaveFromParentEnabled() {
5875        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5876    }
5877
5878    /**
5879     * Controls whether the entire hierarchy under this view will save its
5880     * state when a state saving traversal occurs from its parent.  The default
5881     * is true; if false, these views will not be saved unless
5882     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5883     *
5884     * @param enabled Set to false to <em>disable</em> state saving, or true
5885     * (the default) to allow it.
5886     *
5887     * @see #isSaveFromParentEnabled()
5888     * @see #setId(int)
5889     * @see #onSaveInstanceState()
5890     */
5891    public void setSaveFromParentEnabled(boolean enabled) {
5892        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5893    }
5894
5895
5896    /**
5897     * Returns whether this View is able to take focus.
5898     *
5899     * @return True if this view can take focus, or false otherwise.
5900     * @attr ref android.R.styleable#View_focusable
5901     */
5902    @ViewDebug.ExportedProperty(category = "focus")
5903    public final boolean isFocusable() {
5904        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5905    }
5906
5907    /**
5908     * When a view is focusable, it may not want to take focus when in touch mode.
5909     * For example, a button would like focus when the user is navigating via a D-pad
5910     * so that the user can click on it, but once the user starts touching the screen,
5911     * the button shouldn't take focus
5912     * @return Whether the view is focusable in touch mode.
5913     * @attr ref android.R.styleable#View_focusableInTouchMode
5914     */
5915    @ViewDebug.ExportedProperty
5916    public final boolean isFocusableInTouchMode() {
5917        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5918    }
5919
5920    /**
5921     * Find the nearest view in the specified direction that can take focus.
5922     * This does not actually give focus to that view.
5923     *
5924     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5925     *
5926     * @return The nearest focusable in the specified direction, or null if none
5927     *         can be found.
5928     */
5929    public View focusSearch(int direction) {
5930        if (mParent != null) {
5931            return mParent.focusSearch(this, direction);
5932        } else {
5933            return null;
5934        }
5935    }
5936
5937    /**
5938     * This method is the last chance for the focused view and its ancestors to
5939     * respond to an arrow key. This is called when the focused view did not
5940     * consume the key internally, nor could the view system find a new view in
5941     * the requested direction to give focus to.
5942     *
5943     * @param focused The currently focused view.
5944     * @param direction The direction focus wants to move. One of FOCUS_UP,
5945     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5946     * @return True if the this view consumed this unhandled move.
5947     */
5948    public boolean dispatchUnhandledMove(View focused, int direction) {
5949        return false;
5950    }
5951
5952    /**
5953     * If a user manually specified the next view id for a particular direction,
5954     * use the root to look up the view.
5955     * @param root The root view of the hierarchy containing this view.
5956     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5957     * or FOCUS_BACKWARD.
5958     * @return The user specified next view, or null if there is none.
5959     */
5960    View findUserSetNextFocus(View root, int direction) {
5961        switch (direction) {
5962            case FOCUS_LEFT:
5963                if (mNextFocusLeftId == View.NO_ID) return null;
5964                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5965            case FOCUS_RIGHT:
5966                if (mNextFocusRightId == View.NO_ID) return null;
5967                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5968            case FOCUS_UP:
5969                if (mNextFocusUpId == View.NO_ID) return null;
5970                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5971            case FOCUS_DOWN:
5972                if (mNextFocusDownId == View.NO_ID) return null;
5973                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5974            case FOCUS_FORWARD:
5975                if (mNextFocusForwardId == View.NO_ID) return null;
5976                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5977            case FOCUS_BACKWARD: {
5978                if (mID == View.NO_ID) return null;
5979                final int id = mID;
5980                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5981                    @Override
5982                    public boolean apply(View t) {
5983                        return t.mNextFocusForwardId == id;
5984                    }
5985                });
5986            }
5987        }
5988        return null;
5989    }
5990
5991    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5992        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5993            @Override
5994            public boolean apply(View t) {
5995                return t.mID == childViewId;
5996            }
5997        });
5998
5999        if (result == null) {
6000            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
6001                    + "by user for id " + childViewId);
6002        }
6003        return result;
6004    }
6005
6006    /**
6007     * Find and return all focusable views that are descendants of this view,
6008     * possibly including this view if it is focusable itself.
6009     *
6010     * @param direction The direction of the focus
6011     * @return A list of focusable views
6012     */
6013    public ArrayList<View> getFocusables(int direction) {
6014        ArrayList<View> result = new ArrayList<View>(24);
6015        addFocusables(result, direction);
6016        return result;
6017    }
6018
6019    /**
6020     * Add any focusable views that are descendants of this view (possibly
6021     * including this view if it is focusable itself) to views.  If we are in touch mode,
6022     * only add views that are also focusable in touch mode.
6023     *
6024     * @param views Focusable views found so far
6025     * @param direction The direction of the focus
6026     */
6027    public void addFocusables(ArrayList<View> views, int direction) {
6028        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6029    }
6030
6031    /**
6032     * Adds any focusable views that are descendants of this view (possibly
6033     * including this view if it is focusable itself) to views. This method
6034     * adds all focusable views regardless if we are in touch mode or
6035     * only views focusable in touch mode if we are in touch mode or
6036     * only views that can take accessibility focus if accessibility is enabeld
6037     * depending on the focusable mode paramater.
6038     *
6039     * @param views Focusable views found so far or null if all we are interested is
6040     *        the number of focusables.
6041     * @param direction The direction of the focus.
6042     * @param focusableMode The type of focusables to be added.
6043     *
6044     * @see #FOCUSABLES_ALL
6045     * @see #FOCUSABLES_TOUCH_MODE
6046     */
6047    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6048        if (views == null) {
6049            return;
6050        }
6051        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6052            if (canTakeAccessibilityFocusFromHover() || getAccessibilityNodeProvider() != null) {
6053                views.add(this);
6054                return;
6055            }
6056        }
6057        if (!isFocusable()) {
6058            return;
6059        }
6060        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6061                && isInTouchMode() && !isFocusableInTouchMode()) {
6062            return;
6063        }
6064        views.add(this);
6065    }
6066
6067    /**
6068     * Finds the Views that contain given text. The containment is case insensitive.
6069     * The search is performed by either the text that the View renders or the content
6070     * description that describes the view for accessibility purposes and the view does
6071     * not render or both. Clients can specify how the search is to be performed via
6072     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6073     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6074     *
6075     * @param outViews The output list of matching Views.
6076     * @param searched The text to match against.
6077     *
6078     * @see #FIND_VIEWS_WITH_TEXT
6079     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6080     * @see #setContentDescription(CharSequence)
6081     */
6082    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6083        if (getAccessibilityNodeProvider() != null) {
6084            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6085                outViews.add(this);
6086            }
6087        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6088                && (searched != null && searched.length() > 0)
6089                && (mContentDescription != null && mContentDescription.length() > 0)) {
6090            String searchedLowerCase = searched.toString().toLowerCase();
6091            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6092            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6093                outViews.add(this);
6094            }
6095        }
6096    }
6097
6098    /**
6099     * Find and return all touchable views that are descendants of this view,
6100     * possibly including this view if it is touchable itself.
6101     *
6102     * @return A list of touchable views
6103     */
6104    public ArrayList<View> getTouchables() {
6105        ArrayList<View> result = new ArrayList<View>();
6106        addTouchables(result);
6107        return result;
6108    }
6109
6110    /**
6111     * Add any touchable views that are descendants of this view (possibly
6112     * including this view if it is touchable itself) to views.
6113     *
6114     * @param views Touchable views found so far
6115     */
6116    public void addTouchables(ArrayList<View> views) {
6117        final int viewFlags = mViewFlags;
6118
6119        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6120                && (viewFlags & ENABLED_MASK) == ENABLED) {
6121            views.add(this);
6122        }
6123    }
6124
6125    /**
6126     * Returns whether this View is accessibility focused.
6127     *
6128     * @return True if this View is accessibility focused.
6129     */
6130    boolean isAccessibilityFocused() {
6131        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6132    }
6133
6134    /**
6135     * Call this to try to give accessibility focus to this view.
6136     *
6137     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6138     * returns false or the view is no visible or the view already has accessibility
6139     * focus.
6140     *
6141     * See also {@link #focusSearch(int)}, which is what you call to say that you
6142     * have focus, and you want your parent to look for the next one.
6143     *
6144     * @return Whether this view actually took accessibility focus.
6145     *
6146     * @hide
6147     */
6148    public boolean requestAccessibilityFocus() {
6149        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6150        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6151            return false;
6152        }
6153        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6154            return false;
6155        }
6156        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6157            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6158            ViewRootImpl viewRootImpl = getViewRootImpl();
6159            if (viewRootImpl != null) {
6160                viewRootImpl.setAccessibilityFocusedHost(this);
6161            }
6162            invalidate();
6163            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6164            notifyAccessibilityStateChanged();
6165            return true;
6166        }
6167        return false;
6168    }
6169
6170    /**
6171     * Call this to try to clear accessibility focus of this view.
6172     *
6173     * See also {@link #focusSearch(int)}, which is what you call to say that you
6174     * have focus, and you want your parent to look for the next one.
6175     *
6176     * @hide
6177     */
6178    public void clearAccessibilityFocus() {
6179        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6180            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6181            invalidate();
6182            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6183            notifyAccessibilityStateChanged();
6184            // Clear the text navigation state.
6185            setAccessibilityCursorPosition(-1);
6186        }
6187        // Clear the global reference of accessibility focus if this
6188        // view or any of its descendants had accessibility focus.
6189        ViewRootImpl viewRootImpl = getViewRootImpl();
6190        if (viewRootImpl != null) {
6191            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6192            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6193                viewRootImpl.setAccessibilityFocusedHost(null);
6194            }
6195        }
6196    }
6197
6198    private void requestAccessibilityFocusFromHover() {
6199        if (includeForAccessibility() && isActionableForAccessibility()) {
6200            requestAccessibilityFocus();
6201            requestFocusNoSearch(View.FOCUS_DOWN, null);
6202        } else {
6203            if (mParent != null) {
6204                View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
6205                if (nextFocus != null) {
6206                    nextFocus.requestAccessibilityFocus();
6207                    nextFocus.requestFocusNoSearch(View.FOCUS_DOWN, null);
6208                }
6209            }
6210        }
6211    }
6212
6213    /**
6214     * @hide
6215     */
6216    public boolean canTakeAccessibilityFocusFromHover() {
6217        if (includeForAccessibility() && isActionableForAccessibility()) {
6218            return true;
6219        }
6220        if (mParent != null) {
6221            return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
6222        }
6223        return false;
6224    }
6225
6226    /**
6227     * Clears accessibility focus without calling any callback methods
6228     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6229     * is used for clearing accessibility focus when giving this focus to
6230     * another view.
6231     */
6232    void clearAccessibilityFocusNoCallbacks() {
6233        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6234            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6235            invalidate();
6236        }
6237    }
6238
6239    /**
6240     * Call this to try to give focus to a specific view or to one of its
6241     * descendants.
6242     *
6243     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6244     * false), or if it is focusable and it is not focusable in touch mode
6245     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6246     *
6247     * See also {@link #focusSearch(int)}, which is what you call to say that you
6248     * have focus, and you want your parent to look for the next one.
6249     *
6250     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6251     * {@link #FOCUS_DOWN} and <code>null</code>.
6252     *
6253     * @return Whether this view or one of its descendants actually took focus.
6254     */
6255    public final boolean requestFocus() {
6256        return requestFocus(View.FOCUS_DOWN);
6257    }
6258
6259    /**
6260     * Call this to try to give focus to a specific view or to one of its
6261     * descendants and give it a hint about what direction focus is heading.
6262     *
6263     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6264     * false), or if it is focusable and it is not focusable in touch mode
6265     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6266     *
6267     * See also {@link #focusSearch(int)}, which is what you call to say that you
6268     * have focus, and you want your parent to look for the next one.
6269     *
6270     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6271     * <code>null</code> set for the previously focused rectangle.
6272     *
6273     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6274     * @return Whether this view or one of its descendants actually took focus.
6275     */
6276    public final boolean requestFocus(int direction) {
6277        return requestFocus(direction, null);
6278    }
6279
6280    /**
6281     * Call this to try to give focus to a specific view or to one of its descendants
6282     * and give it hints about the direction and a specific rectangle that the focus
6283     * is coming from.  The rectangle can help give larger views a finer grained hint
6284     * about where focus is coming from, and therefore, where to show selection, or
6285     * forward focus change internally.
6286     *
6287     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6288     * false), or if it is focusable and it is not focusable in touch mode
6289     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6290     *
6291     * A View will not take focus if it is not visible.
6292     *
6293     * A View will not take focus if one of its parents has
6294     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6295     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6296     *
6297     * See also {@link #focusSearch(int)}, which is what you call to say that you
6298     * have focus, and you want your parent to look for the next one.
6299     *
6300     * You may wish to override this method if your custom {@link View} has an internal
6301     * {@link View} that it wishes to forward the request to.
6302     *
6303     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6304     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6305     *        to give a finer grained hint about where focus is coming from.  May be null
6306     *        if there is no hint.
6307     * @return Whether this view or one of its descendants actually took focus.
6308     */
6309    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6310        return requestFocusNoSearch(direction, previouslyFocusedRect);
6311    }
6312
6313    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6314        // need to be focusable
6315        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6316                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6317            return false;
6318        }
6319
6320        // need to be focusable in touch mode if in touch mode
6321        if (isInTouchMode() &&
6322            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6323               return false;
6324        }
6325
6326        // need to not have any parents blocking us
6327        if (hasAncestorThatBlocksDescendantFocus()) {
6328            return false;
6329        }
6330
6331        handleFocusGainInternal(direction, previouslyFocusedRect);
6332        return true;
6333    }
6334
6335    /**
6336     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6337     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6338     * touch mode to request focus when they are touched.
6339     *
6340     * @return Whether this view or one of its descendants actually took focus.
6341     *
6342     * @see #isInTouchMode()
6343     *
6344     */
6345    public final boolean requestFocusFromTouch() {
6346        // Leave touch mode if we need to
6347        if (isInTouchMode()) {
6348            ViewRootImpl viewRoot = getViewRootImpl();
6349            if (viewRoot != null) {
6350                viewRoot.ensureTouchMode(false);
6351            }
6352        }
6353        return requestFocus(View.FOCUS_DOWN);
6354    }
6355
6356    /**
6357     * @return Whether any ancestor of this view blocks descendant focus.
6358     */
6359    private boolean hasAncestorThatBlocksDescendantFocus() {
6360        ViewParent ancestor = mParent;
6361        while (ancestor instanceof ViewGroup) {
6362            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6363            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6364                return true;
6365            } else {
6366                ancestor = vgAncestor.getParent();
6367            }
6368        }
6369        return false;
6370    }
6371
6372    /**
6373     * Gets the mode for determining whether this View is important for accessibility
6374     * which is if it fires accessibility events and if it is reported to
6375     * accessibility services that query the screen.
6376     *
6377     * @return The mode for determining whether a View is important for accessibility.
6378     *
6379     * @attr ref android.R.styleable#View_importantForAccessibility
6380     *
6381     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6382     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6383     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6384     */
6385    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6386            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6387                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6388            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6389                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6390            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6391                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6392        })
6393    public int getImportantForAccessibility() {
6394        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6395                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6396    }
6397
6398    /**
6399     * Sets how to determine whether this view is important for accessibility
6400     * which is if it fires accessibility events and if it is reported to
6401     * accessibility services that query the screen.
6402     *
6403     * @param mode How to determine whether this view is important for accessibility.
6404     *
6405     * @attr ref android.R.styleable#View_importantForAccessibility
6406     *
6407     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6408     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6409     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6410     */
6411    public void setImportantForAccessibility(int mode) {
6412        if (mode != getImportantForAccessibility()) {
6413            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6414            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6415                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6416            notifyAccessibilityStateChanged();
6417        }
6418    }
6419
6420    /**
6421     * Gets whether this view should be exposed for accessibility.
6422     *
6423     * @return Whether the view is exposed for accessibility.
6424     *
6425     * @hide
6426     */
6427    public boolean isImportantForAccessibility() {
6428        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6429                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6430        switch (mode) {
6431            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6432                return true;
6433            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6434                return false;
6435            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6436                return isActionableForAccessibility() || hasListenersForAccessibility();
6437            default:
6438                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6439                        + mode);
6440        }
6441    }
6442
6443    /**
6444     * Gets the parent for accessibility purposes. Note that the parent for
6445     * accessibility is not necessary the immediate parent. It is the first
6446     * predecessor that is important for accessibility.
6447     *
6448     * @return The parent for accessibility purposes.
6449     */
6450    public ViewParent getParentForAccessibility() {
6451        if (mParent instanceof View) {
6452            View parentView = (View) mParent;
6453            if (parentView.includeForAccessibility()) {
6454                return mParent;
6455            } else {
6456                return mParent.getParentForAccessibility();
6457            }
6458        }
6459        return null;
6460    }
6461
6462    /**
6463     * Adds the children of a given View for accessibility. Since some Views are
6464     * not important for accessibility the children for accessibility are not
6465     * necessarily direct children of the riew, rather they are the first level of
6466     * descendants important for accessibility.
6467     *
6468     * @param children The list of children for accessibility.
6469     */
6470    public void addChildrenForAccessibility(ArrayList<View> children) {
6471        if (includeForAccessibility()) {
6472            children.add(this);
6473        }
6474    }
6475
6476    /**
6477     * Whether to regard this view for accessibility. A view is regarded for
6478     * accessibility if it is important for accessibility or the querying
6479     * accessibility service has explicitly requested that view not
6480     * important for accessibility are regarded.
6481     *
6482     * @return Whether to regard the view for accessibility.
6483     *
6484     * @hide
6485     */
6486    public boolean includeForAccessibility() {
6487        if (mAttachInfo != null) {
6488            if (!mAttachInfo.mIncludeNotImportantViews) {
6489                return isImportantForAccessibility();
6490            }
6491            return true;
6492        }
6493        return false;
6494    }
6495
6496    /**
6497     * Returns whether the View is considered actionable from
6498     * accessibility perspective. Such view are important for
6499     * accessiiblity.
6500     *
6501     * @return True if the view is actionable for accessibility.
6502     *
6503     * @hide
6504     */
6505    public boolean isActionableForAccessibility() {
6506        return (isClickable() || isLongClickable() || isFocusable());
6507    }
6508
6509    /**
6510     * Returns whether the View has registered callbacks wich makes it
6511     * important for accessiiblity.
6512     *
6513     * @return True if the view is actionable for accessibility.
6514     */
6515    private boolean hasListenersForAccessibility() {
6516        ListenerInfo info = getListenerInfo();
6517        return mTouchDelegate != null || info.mOnKeyListener != null
6518                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6519                || info.mOnHoverListener != null || info.mOnDragListener != null;
6520    }
6521
6522    /**
6523     * Notifies accessibility services that some view's important for
6524     * accessibility state has changed. Note that such notifications
6525     * are made at most once every
6526     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6527     * to avoid unnecessary load to the system. Also once a view has
6528     * made a notifucation this method is a NOP until the notification has
6529     * been sent to clients.
6530     *
6531     * @hide
6532     *
6533     * TODO: Makse sure this method is called for any view state change
6534     *       that is interesting for accessilility purposes.
6535     */
6536    public void notifyAccessibilityStateChanged() {
6537        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6538            return;
6539        }
6540        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6541            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6542            if (mParent != null) {
6543                mParent.childAccessibilityStateChanged(this);
6544            }
6545        }
6546    }
6547
6548    /**
6549     * Reset the state indicating the this view has requested clients
6550     * interested in its accessiblity state to be notified.
6551     *
6552     * @hide
6553     */
6554    public void resetAccessibilityStateChanged() {
6555        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6556    }
6557
6558    /**
6559     * Performs the specified accessibility action on the view. For
6560     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6561    * <p>
6562    * If an {@link AccessibilityDelegate} has been specified via calling
6563    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6564    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6565    * is responsible for handling this call.
6566    * </p>
6567     *
6568     * @param action The action to perform.
6569     * @param arguments Optional action arguments.
6570     * @return Whether the action was performed.
6571     */
6572    public boolean performAccessibilityAction(int action, Bundle arguments) {
6573      if (mAccessibilityDelegate != null) {
6574          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6575      } else {
6576          return performAccessibilityActionInternal(action, arguments);
6577      }
6578    }
6579
6580   /**
6581    * @see #performAccessibilityAction(int, Bundle)
6582    *
6583    * Note: Called from the default {@link AccessibilityDelegate}.
6584    */
6585    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6586        switch (action) {
6587            case AccessibilityNodeInfo.ACTION_CLICK: {
6588                if (isClickable()) {
6589                    return performClick();
6590                }
6591            } break;
6592            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6593                if (isLongClickable()) {
6594                    return performLongClick();
6595                }
6596            } break;
6597            case AccessibilityNodeInfo.ACTION_FOCUS: {
6598                if (!hasFocus()) {
6599                    // Get out of touch mode since accessibility
6600                    // wants to move focus around.
6601                    getViewRootImpl().ensureTouchMode(false);
6602                    return requestFocus();
6603                }
6604            } break;
6605            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6606                if (hasFocus()) {
6607                    clearFocus();
6608                    return !isFocused();
6609                }
6610            } break;
6611            case AccessibilityNodeInfo.ACTION_SELECT: {
6612                if (!isSelected()) {
6613                    setSelected(true);
6614                    return isSelected();
6615                }
6616            } break;
6617            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6618                if (isSelected()) {
6619                    setSelected(false);
6620                    return !isSelected();
6621                }
6622            } break;
6623            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6624                if (!isAccessibilityFocused()) {
6625                    return requestAccessibilityFocus();
6626                }
6627            } break;
6628            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6629                if (isAccessibilityFocused()) {
6630                    clearAccessibilityFocus();
6631                    return true;
6632                }
6633            } break;
6634            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6635                if (arguments != null) {
6636                    final int granularity = arguments.getInt(
6637                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6638                    return nextAtGranularity(granularity);
6639                }
6640            } break;
6641            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6642                if (arguments != null) {
6643                    final int granularity = arguments.getInt(
6644                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6645                    return previousAtGranularity(granularity);
6646                }
6647            } break;
6648        }
6649        return false;
6650    }
6651
6652    private boolean nextAtGranularity(int granularity) {
6653        CharSequence text = getIterableTextForAccessibility();
6654        if (text == null || text.length() == 0) {
6655            return false;
6656        }
6657        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6658        if (iterator == null) {
6659            return false;
6660        }
6661        final int current = getAccessibilityCursorPosition();
6662        final int[] range = iterator.following(current);
6663        if (range == null) {
6664            setAccessibilityCursorPosition(-1);
6665            return false;
6666        }
6667        final int start = range[0];
6668        final int end = range[1];
6669        setAccessibilityCursorPosition(start);
6670        sendViewTextTraversedAtGranularityEvent(
6671                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6672                granularity, start, end);
6673        return true;
6674    }
6675
6676    private boolean previousAtGranularity(int granularity) {
6677        CharSequence text = getIterableTextForAccessibility();
6678        if (text == null || text.length() == 0) {
6679            return false;
6680        }
6681        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6682        if (iterator == null) {
6683            return false;
6684        }
6685        final int selectionStart = getAccessibilityCursorPosition();
6686        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6687        final int[] range = iterator.preceding(current);
6688        if (range == null) {
6689            setAccessibilityCursorPosition(-1);
6690            return false;
6691        }
6692        final int start = range[0];
6693        final int end = range[1];
6694        setAccessibilityCursorPosition(end);
6695        sendViewTextTraversedAtGranularityEvent(
6696                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6697                granularity, start, end);
6698        return true;
6699    }
6700
6701    /**
6702     * Gets the text reported for accessibility purposes.
6703     *
6704     * @return The accessibility text.
6705     *
6706     * @hide
6707     */
6708    public CharSequence getIterableTextForAccessibility() {
6709        return mContentDescription;
6710    }
6711
6712    /**
6713     * @hide
6714     */
6715    public int getAccessibilityCursorPosition() {
6716        return mAccessibilityCursorPosition;
6717    }
6718
6719    /**
6720     * @hide
6721     */
6722    public void setAccessibilityCursorPosition(int position) {
6723        mAccessibilityCursorPosition = position;
6724    }
6725
6726    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6727            int fromIndex, int toIndex) {
6728        if (mParent == null) {
6729            return;
6730        }
6731        AccessibilityEvent event = AccessibilityEvent.obtain(
6732                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6733        onInitializeAccessibilityEvent(event);
6734        onPopulateAccessibilityEvent(event);
6735        event.setFromIndex(fromIndex);
6736        event.setToIndex(toIndex);
6737        event.setAction(action);
6738        event.setMovementGranularity(granularity);
6739        mParent.requestSendAccessibilityEvent(this, event);
6740    }
6741
6742    /**
6743     * @hide
6744     */
6745    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6746        switch (granularity) {
6747            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6748                CharSequence text = getIterableTextForAccessibility();
6749                if (text != null && text.length() > 0) {
6750                    CharacterTextSegmentIterator iterator =
6751                        CharacterTextSegmentIterator.getInstance(mContext);
6752                    iterator.initialize(text.toString());
6753                    return iterator;
6754                }
6755            } break;
6756            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6757                CharSequence text = getIterableTextForAccessibility();
6758                if (text != null && text.length() > 0) {
6759                    WordTextSegmentIterator iterator =
6760                        WordTextSegmentIterator.getInstance(mContext);
6761                    iterator.initialize(text.toString());
6762                    return iterator;
6763                }
6764            } break;
6765            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6766                CharSequence text = getIterableTextForAccessibility();
6767                if (text != null && text.length() > 0) {
6768                    ParagraphTextSegmentIterator iterator =
6769                        ParagraphTextSegmentIterator.getInstance();
6770                    iterator.initialize(text.toString());
6771                    return iterator;
6772                }
6773            } break;
6774        }
6775        return null;
6776    }
6777
6778    /**
6779     * @hide
6780     */
6781    public void dispatchStartTemporaryDetach() {
6782        clearAccessibilityFocus();
6783        onStartTemporaryDetach();
6784    }
6785
6786    /**
6787     * This is called when a container is going to temporarily detach a child, with
6788     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6789     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6790     * {@link #onDetachedFromWindow()} when the container is done.
6791     */
6792    public void onStartTemporaryDetach() {
6793        removeUnsetPressCallback();
6794        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6795    }
6796
6797    /**
6798     * @hide
6799     */
6800    public void dispatchFinishTemporaryDetach() {
6801        onFinishTemporaryDetach();
6802    }
6803
6804    /**
6805     * Called after {@link #onStartTemporaryDetach} when the container is done
6806     * changing the view.
6807     */
6808    public void onFinishTemporaryDetach() {
6809    }
6810
6811    /**
6812     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6813     * for this view's window.  Returns null if the view is not currently attached
6814     * to the window.  Normally you will not need to use this directly, but
6815     * just use the standard high-level event callbacks like
6816     * {@link #onKeyDown(int, KeyEvent)}.
6817     */
6818    public KeyEvent.DispatcherState getKeyDispatcherState() {
6819        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6820    }
6821
6822    /**
6823     * Dispatch a key event before it is processed by any input method
6824     * associated with the view hierarchy.  This can be used to intercept
6825     * key events in special situations before the IME consumes them; a
6826     * typical example would be handling the BACK key to update the application's
6827     * UI instead of allowing the IME to see it and close itself.
6828     *
6829     * @param event The key event to be dispatched.
6830     * @return True if the event was handled, false otherwise.
6831     */
6832    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6833        return onKeyPreIme(event.getKeyCode(), event);
6834    }
6835
6836    /**
6837     * Dispatch a key event to the next view on the focus path. This path runs
6838     * from the top of the view tree down to the currently focused view. If this
6839     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6840     * the next node down the focus path. This method also fires any key
6841     * listeners.
6842     *
6843     * @param event The key event to be dispatched.
6844     * @return True if the event was handled, false otherwise.
6845     */
6846    public boolean dispatchKeyEvent(KeyEvent event) {
6847        if (mInputEventConsistencyVerifier != null) {
6848            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6849        }
6850
6851        // Give any attached key listener a first crack at the event.
6852        //noinspection SimplifiableIfStatement
6853        ListenerInfo li = mListenerInfo;
6854        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6855                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6856            return true;
6857        }
6858
6859        if (event.dispatch(this, mAttachInfo != null
6860                ? mAttachInfo.mKeyDispatchState : null, this)) {
6861            return true;
6862        }
6863
6864        if (mInputEventConsistencyVerifier != null) {
6865            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6866        }
6867        return false;
6868    }
6869
6870    /**
6871     * Dispatches a key shortcut event.
6872     *
6873     * @param event The key event to be dispatched.
6874     * @return True if the event was handled by the view, false otherwise.
6875     */
6876    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6877        return onKeyShortcut(event.getKeyCode(), event);
6878    }
6879
6880    /**
6881     * Pass the touch screen motion event down to the target view, or this
6882     * view if it is the target.
6883     *
6884     * @param event The motion event to be dispatched.
6885     * @return True if the event was handled by the view, false otherwise.
6886     */
6887    public boolean dispatchTouchEvent(MotionEvent event) {
6888        if (mInputEventConsistencyVerifier != null) {
6889            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6890        }
6891
6892        if (onFilterTouchEventForSecurity(event)) {
6893            //noinspection SimplifiableIfStatement
6894            ListenerInfo li = mListenerInfo;
6895            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6896                    && li.mOnTouchListener.onTouch(this, event)) {
6897                return true;
6898            }
6899
6900            if (onTouchEvent(event)) {
6901                return true;
6902            }
6903        }
6904
6905        if (mInputEventConsistencyVerifier != null) {
6906            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6907        }
6908        return false;
6909    }
6910
6911    /**
6912     * Filter the touch event to apply security policies.
6913     *
6914     * @param event The motion event to be filtered.
6915     * @return True if the event should be dispatched, false if the event should be dropped.
6916     *
6917     * @see #getFilterTouchesWhenObscured
6918     */
6919    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6920        //noinspection RedundantIfStatement
6921        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6922                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6923            // Window is obscured, drop this touch.
6924            return false;
6925        }
6926        return true;
6927    }
6928
6929    /**
6930     * Pass a trackball motion event down to the focused view.
6931     *
6932     * @param event The motion event to be dispatched.
6933     * @return True if the event was handled by the view, false otherwise.
6934     */
6935    public boolean dispatchTrackballEvent(MotionEvent event) {
6936        if (mInputEventConsistencyVerifier != null) {
6937            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6938        }
6939
6940        return onTrackballEvent(event);
6941    }
6942
6943    /**
6944     * Dispatch a generic motion event.
6945     * <p>
6946     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6947     * are delivered to the view under the pointer.  All other generic motion events are
6948     * delivered to the focused view.  Hover events are handled specially and are delivered
6949     * to {@link #onHoverEvent(MotionEvent)}.
6950     * </p>
6951     *
6952     * @param event The motion event to be dispatched.
6953     * @return True if the event was handled by the view, false otherwise.
6954     */
6955    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6956        if (mInputEventConsistencyVerifier != null) {
6957            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6958        }
6959
6960        final int source = event.getSource();
6961        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6962            final int action = event.getAction();
6963            if (action == MotionEvent.ACTION_HOVER_ENTER
6964                    || action == MotionEvent.ACTION_HOVER_MOVE
6965                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6966                if (dispatchHoverEvent(event)) {
6967                    return true;
6968                }
6969            } else if (dispatchGenericPointerEvent(event)) {
6970                return true;
6971            }
6972        } else if (dispatchGenericFocusedEvent(event)) {
6973            return true;
6974        }
6975
6976        if (dispatchGenericMotionEventInternal(event)) {
6977            return true;
6978        }
6979
6980        if (mInputEventConsistencyVerifier != null) {
6981            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6982        }
6983        return false;
6984    }
6985
6986    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6987        //noinspection SimplifiableIfStatement
6988        ListenerInfo li = mListenerInfo;
6989        if (li != null && li.mOnGenericMotionListener != null
6990                && (mViewFlags & ENABLED_MASK) == ENABLED
6991                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6992            return true;
6993        }
6994
6995        if (onGenericMotionEvent(event)) {
6996            return true;
6997        }
6998
6999        if (mInputEventConsistencyVerifier != null) {
7000            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7001        }
7002        return false;
7003    }
7004
7005    /**
7006     * Dispatch a hover event.
7007     * <p>
7008     * Do not call this method directly.
7009     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7010     * </p>
7011     *
7012     * @param event The motion event to be dispatched.
7013     * @return True if the event was handled by the view, false otherwise.
7014     */
7015    protected boolean dispatchHoverEvent(MotionEvent event) {
7016        //noinspection SimplifiableIfStatement
7017        ListenerInfo li = mListenerInfo;
7018        if (li != null && li.mOnHoverListener != null
7019                && (mViewFlags & ENABLED_MASK) == ENABLED
7020                && li.mOnHoverListener.onHover(this, event)) {
7021            return true;
7022        }
7023
7024        return onHoverEvent(event);
7025    }
7026
7027    /**
7028     * Returns true if the view has a child to which it has recently sent
7029     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7030     * it does not have a hovered child, then it must be the innermost hovered view.
7031     * @hide
7032     */
7033    protected boolean hasHoveredChild() {
7034        return false;
7035    }
7036
7037    /**
7038     * Dispatch a generic motion event to the view under the first pointer.
7039     * <p>
7040     * Do not call this method directly.
7041     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7042     * </p>
7043     *
7044     * @param event The motion event to be dispatched.
7045     * @return True if the event was handled by the view, false otherwise.
7046     */
7047    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7048        return false;
7049    }
7050
7051    /**
7052     * Dispatch a generic motion event to the currently focused view.
7053     * <p>
7054     * Do not call this method directly.
7055     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7056     * </p>
7057     *
7058     * @param event The motion event to be dispatched.
7059     * @return True if the event was handled by the view, false otherwise.
7060     */
7061    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7062        return false;
7063    }
7064
7065    /**
7066     * Dispatch a pointer event.
7067     * <p>
7068     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7069     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7070     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7071     * and should not be expected to handle other pointing device features.
7072     * </p>
7073     *
7074     * @param event The motion event to be dispatched.
7075     * @return True if the event was handled by the view, false otherwise.
7076     * @hide
7077     */
7078    public final boolean dispatchPointerEvent(MotionEvent event) {
7079        if (event.isTouchEvent()) {
7080            return dispatchTouchEvent(event);
7081        } else {
7082            return dispatchGenericMotionEvent(event);
7083        }
7084    }
7085
7086    /**
7087     * Called when the window containing this view gains or loses window focus.
7088     * ViewGroups should override to route to their children.
7089     *
7090     * @param hasFocus True if the window containing this view now has focus,
7091     *        false otherwise.
7092     */
7093    public void dispatchWindowFocusChanged(boolean hasFocus) {
7094        onWindowFocusChanged(hasFocus);
7095    }
7096
7097    /**
7098     * Called when the window containing this view gains or loses focus.  Note
7099     * that this is separate from view focus: to receive key events, both
7100     * your view and its window must have focus.  If a window is displayed
7101     * on top of yours that takes input focus, then your own window will lose
7102     * focus but the view focus will remain unchanged.
7103     *
7104     * @param hasWindowFocus True if the window containing this view now has
7105     *        focus, false otherwise.
7106     */
7107    public void onWindowFocusChanged(boolean hasWindowFocus) {
7108        InputMethodManager imm = InputMethodManager.peekInstance();
7109        if (!hasWindowFocus) {
7110            if (isPressed()) {
7111                setPressed(false);
7112            }
7113            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7114                imm.focusOut(this);
7115            }
7116            removeLongPressCallback();
7117            removeTapCallback();
7118            onFocusLost();
7119        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7120            imm.focusIn(this);
7121        }
7122        refreshDrawableState();
7123    }
7124
7125    /**
7126     * Returns true if this view is in a window that currently has window focus.
7127     * Note that this is not the same as the view itself having focus.
7128     *
7129     * @return True if this view is in a window that currently has window focus.
7130     */
7131    public boolean hasWindowFocus() {
7132        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7133    }
7134
7135    /**
7136     * Dispatch a view visibility change down the view hierarchy.
7137     * ViewGroups should override to route to their children.
7138     * @param changedView The view whose visibility changed. Could be 'this' or
7139     * an ancestor view.
7140     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7141     * {@link #INVISIBLE} or {@link #GONE}.
7142     */
7143    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7144        onVisibilityChanged(changedView, visibility);
7145    }
7146
7147    /**
7148     * Called when the visibility of the view or an ancestor of the view is changed.
7149     * @param changedView The view whose visibility changed. Could be 'this' or
7150     * an ancestor view.
7151     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7152     * {@link #INVISIBLE} or {@link #GONE}.
7153     */
7154    protected void onVisibilityChanged(View changedView, int visibility) {
7155        if (visibility == VISIBLE) {
7156            if (mAttachInfo != null) {
7157                initialAwakenScrollBars();
7158            } else {
7159                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7160            }
7161        }
7162    }
7163
7164    /**
7165     * Dispatch a hint about whether this view is displayed. For instance, when
7166     * a View moves out of the screen, it might receives a display hint indicating
7167     * the view is not displayed. Applications should not <em>rely</em> on this hint
7168     * as there is no guarantee that they will receive one.
7169     *
7170     * @param hint A hint about whether or not this view is displayed:
7171     * {@link #VISIBLE} or {@link #INVISIBLE}.
7172     */
7173    public void dispatchDisplayHint(int hint) {
7174        onDisplayHint(hint);
7175    }
7176
7177    /**
7178     * Gives this view a hint about whether is displayed or not. For instance, when
7179     * a View moves out of the screen, it might receives a display hint indicating
7180     * the view is not displayed. Applications should not <em>rely</em> on this hint
7181     * as there is no guarantee that they will receive one.
7182     *
7183     * @param hint A hint about whether or not this view is displayed:
7184     * {@link #VISIBLE} or {@link #INVISIBLE}.
7185     */
7186    protected void onDisplayHint(int hint) {
7187    }
7188
7189    /**
7190     * Dispatch a window visibility change down the view hierarchy.
7191     * ViewGroups should override to route to their children.
7192     *
7193     * @param visibility The new visibility of the window.
7194     *
7195     * @see #onWindowVisibilityChanged(int)
7196     */
7197    public void dispatchWindowVisibilityChanged(int visibility) {
7198        onWindowVisibilityChanged(visibility);
7199    }
7200
7201    /**
7202     * Called when the window containing has change its visibility
7203     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7204     * that this tells you whether or not your window is being made visible
7205     * to the window manager; this does <em>not</em> tell you whether or not
7206     * your window is obscured by other windows on the screen, even if it
7207     * is itself visible.
7208     *
7209     * @param visibility The new visibility of the window.
7210     */
7211    protected void onWindowVisibilityChanged(int visibility) {
7212        if (visibility == VISIBLE) {
7213            initialAwakenScrollBars();
7214        }
7215    }
7216
7217    /**
7218     * Returns the current visibility of the window this view is attached to
7219     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7220     *
7221     * @return Returns the current visibility of the view's window.
7222     */
7223    public int getWindowVisibility() {
7224        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7225    }
7226
7227    /**
7228     * Retrieve the overall visible display size in which the window this view is
7229     * attached to has been positioned in.  This takes into account screen
7230     * decorations above the window, for both cases where the window itself
7231     * is being position inside of them or the window is being placed under
7232     * then and covered insets are used for the window to position its content
7233     * inside.  In effect, this tells you the available area where content can
7234     * be placed and remain visible to users.
7235     *
7236     * <p>This function requires an IPC back to the window manager to retrieve
7237     * the requested information, so should not be used in performance critical
7238     * code like drawing.
7239     *
7240     * @param outRect Filled in with the visible display frame.  If the view
7241     * is not attached to a window, this is simply the raw display size.
7242     */
7243    public void getWindowVisibleDisplayFrame(Rect outRect) {
7244        if (mAttachInfo != null) {
7245            try {
7246                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7247            } catch (RemoteException e) {
7248                return;
7249            }
7250            // XXX This is really broken, and probably all needs to be done
7251            // in the window manager, and we need to know more about whether
7252            // we want the area behind or in front of the IME.
7253            final Rect insets = mAttachInfo.mVisibleInsets;
7254            outRect.left += insets.left;
7255            outRect.top += insets.top;
7256            outRect.right -= insets.right;
7257            outRect.bottom -= insets.bottom;
7258            return;
7259        }
7260        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7261        d.getRectSize(outRect);
7262    }
7263
7264    /**
7265     * Dispatch a notification about a resource configuration change down
7266     * the view hierarchy.
7267     * ViewGroups should override to route to their children.
7268     *
7269     * @param newConfig The new resource configuration.
7270     *
7271     * @see #onConfigurationChanged(android.content.res.Configuration)
7272     */
7273    public void dispatchConfigurationChanged(Configuration newConfig) {
7274        onConfigurationChanged(newConfig);
7275    }
7276
7277    /**
7278     * Called when the current configuration of the resources being used
7279     * by the application have changed.  You can use this to decide when
7280     * to reload resources that can changed based on orientation and other
7281     * configuration characterstics.  You only need to use this if you are
7282     * not relying on the normal {@link android.app.Activity} mechanism of
7283     * recreating the activity instance upon a configuration change.
7284     *
7285     * @param newConfig The new resource configuration.
7286     */
7287    protected void onConfigurationChanged(Configuration newConfig) {
7288    }
7289
7290    /**
7291     * Private function to aggregate all per-view attributes in to the view
7292     * root.
7293     */
7294    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7295        performCollectViewAttributes(attachInfo, visibility);
7296    }
7297
7298    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7299        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7300            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7301                attachInfo.mKeepScreenOn = true;
7302            }
7303            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7304            ListenerInfo li = mListenerInfo;
7305            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7306                attachInfo.mHasSystemUiListeners = true;
7307            }
7308        }
7309    }
7310
7311    void needGlobalAttributesUpdate(boolean force) {
7312        final AttachInfo ai = mAttachInfo;
7313        if (ai != null) {
7314            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7315                    || ai.mHasSystemUiListeners) {
7316                ai.mRecomputeGlobalAttributes = true;
7317            }
7318        }
7319    }
7320
7321    /**
7322     * Returns whether the device is currently in touch mode.  Touch mode is entered
7323     * once the user begins interacting with the device by touch, and affects various
7324     * things like whether focus is always visible to the user.
7325     *
7326     * @return Whether the device is in touch mode.
7327     */
7328    @ViewDebug.ExportedProperty
7329    public boolean isInTouchMode() {
7330        if (mAttachInfo != null) {
7331            return mAttachInfo.mInTouchMode;
7332        } else {
7333            return ViewRootImpl.isInTouchMode();
7334        }
7335    }
7336
7337    /**
7338     * Returns the context the view is running in, through which it can
7339     * access the current theme, resources, etc.
7340     *
7341     * @return The view's Context.
7342     */
7343    @ViewDebug.CapturedViewProperty
7344    public final Context getContext() {
7345        return mContext;
7346    }
7347
7348    /**
7349     * Handle a key event before it is processed by any input method
7350     * associated with the view hierarchy.  This can be used to intercept
7351     * key events in special situations before the IME consumes them; a
7352     * typical example would be handling the BACK key to update the application's
7353     * UI instead of allowing the IME to see it and close itself.
7354     *
7355     * @param keyCode The value in event.getKeyCode().
7356     * @param event Description of the key event.
7357     * @return If you handled the event, return true. If you want to allow the
7358     *         event to be handled by the next receiver, return false.
7359     */
7360    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7361        return false;
7362    }
7363
7364    /**
7365     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7366     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7367     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7368     * is released, if the view is enabled and clickable.
7369     *
7370     * @param keyCode A key code that represents the button pressed, from
7371     *                {@link android.view.KeyEvent}.
7372     * @param event   The KeyEvent object that defines the button action.
7373     */
7374    public boolean onKeyDown(int keyCode, KeyEvent event) {
7375        boolean result = false;
7376
7377        switch (keyCode) {
7378            case KeyEvent.KEYCODE_DPAD_CENTER:
7379            case KeyEvent.KEYCODE_ENTER: {
7380                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7381                    return true;
7382                }
7383                // Long clickable items don't necessarily have to be clickable
7384                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7385                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7386                        (event.getRepeatCount() == 0)) {
7387                    setPressed(true);
7388                    checkForLongClick(0);
7389                    return true;
7390                }
7391                break;
7392            }
7393        }
7394        return result;
7395    }
7396
7397    /**
7398     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7399     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7400     * the event).
7401     */
7402    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7403        return false;
7404    }
7405
7406    /**
7407     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7408     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7409     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7410     * {@link KeyEvent#KEYCODE_ENTER} is released.
7411     *
7412     * @param keyCode A key code that represents the button pressed, from
7413     *                {@link android.view.KeyEvent}.
7414     * @param event   The KeyEvent object that defines the button action.
7415     */
7416    public boolean onKeyUp(int keyCode, KeyEvent event) {
7417        boolean result = false;
7418
7419        switch (keyCode) {
7420            case KeyEvent.KEYCODE_DPAD_CENTER:
7421            case KeyEvent.KEYCODE_ENTER: {
7422                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7423                    return true;
7424                }
7425                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7426                    setPressed(false);
7427
7428                    if (!mHasPerformedLongPress) {
7429                        // This is a tap, so remove the longpress check
7430                        removeLongPressCallback();
7431
7432                        result = performClick();
7433                    }
7434                }
7435                break;
7436            }
7437        }
7438        return result;
7439    }
7440
7441    /**
7442     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7443     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7444     * the event).
7445     *
7446     * @param keyCode     A key code that represents the button pressed, from
7447     *                    {@link android.view.KeyEvent}.
7448     * @param repeatCount The number of times the action was made.
7449     * @param event       The KeyEvent object that defines the button action.
7450     */
7451    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7452        return false;
7453    }
7454
7455    /**
7456     * Called on the focused view when a key shortcut event is not handled.
7457     * Override this method to implement local key shortcuts for the View.
7458     * Key shortcuts can also be implemented by setting the
7459     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7460     *
7461     * @param keyCode The value in event.getKeyCode().
7462     * @param event Description of the key event.
7463     * @return If you handled the event, return true. If you want to allow the
7464     *         event to be handled by the next receiver, return false.
7465     */
7466    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7467        return false;
7468    }
7469
7470    /**
7471     * Check whether the called view is a text editor, in which case it
7472     * would make sense to automatically display a soft input window for
7473     * it.  Subclasses should override this if they implement
7474     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7475     * a call on that method would return a non-null InputConnection, and
7476     * they are really a first-class editor that the user would normally
7477     * start typing on when the go into a window containing your view.
7478     *
7479     * <p>The default implementation always returns false.  This does
7480     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7481     * will not be called or the user can not otherwise perform edits on your
7482     * view; it is just a hint to the system that this is not the primary
7483     * purpose of this view.
7484     *
7485     * @return Returns true if this view is a text editor, else false.
7486     */
7487    public boolean onCheckIsTextEditor() {
7488        return false;
7489    }
7490
7491    /**
7492     * Create a new InputConnection for an InputMethod to interact
7493     * with the view.  The default implementation returns null, since it doesn't
7494     * support input methods.  You can override this to implement such support.
7495     * This is only needed for views that take focus and text input.
7496     *
7497     * <p>When implementing this, you probably also want to implement
7498     * {@link #onCheckIsTextEditor()} to indicate you will return a
7499     * non-null InputConnection.
7500     *
7501     * @param outAttrs Fill in with attribute information about the connection.
7502     */
7503    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7504        return null;
7505    }
7506
7507    /**
7508     * Called by the {@link android.view.inputmethod.InputMethodManager}
7509     * when a view who is not the current
7510     * input connection target is trying to make a call on the manager.  The
7511     * default implementation returns false; you can override this to return
7512     * true for certain views if you are performing InputConnection proxying
7513     * to them.
7514     * @param view The View that is making the InputMethodManager call.
7515     * @return Return true to allow the call, false to reject.
7516     */
7517    public boolean checkInputConnectionProxy(View view) {
7518        return false;
7519    }
7520
7521    /**
7522     * Show the context menu for this view. It is not safe to hold on to the
7523     * menu after returning from this method.
7524     *
7525     * You should normally not overload this method. Overload
7526     * {@link #onCreateContextMenu(ContextMenu)} or define an
7527     * {@link OnCreateContextMenuListener} to add items to the context menu.
7528     *
7529     * @param menu The context menu to populate
7530     */
7531    public void createContextMenu(ContextMenu menu) {
7532        ContextMenuInfo menuInfo = getContextMenuInfo();
7533
7534        // Sets the current menu info so all items added to menu will have
7535        // my extra info set.
7536        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7537
7538        onCreateContextMenu(menu);
7539        ListenerInfo li = mListenerInfo;
7540        if (li != null && li.mOnCreateContextMenuListener != null) {
7541            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7542        }
7543
7544        // Clear the extra information so subsequent items that aren't mine don't
7545        // have my extra info.
7546        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7547
7548        if (mParent != null) {
7549            mParent.createContextMenu(menu);
7550        }
7551    }
7552
7553    /**
7554     * Views should implement this if they have extra information to associate
7555     * with the context menu. The return result is supplied as a parameter to
7556     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7557     * callback.
7558     *
7559     * @return Extra information about the item for which the context menu
7560     *         should be shown. This information will vary across different
7561     *         subclasses of View.
7562     */
7563    protected ContextMenuInfo getContextMenuInfo() {
7564        return null;
7565    }
7566
7567    /**
7568     * Views should implement this if the view itself is going to add items to
7569     * the context menu.
7570     *
7571     * @param menu the context menu to populate
7572     */
7573    protected void onCreateContextMenu(ContextMenu menu) {
7574    }
7575
7576    /**
7577     * Implement this method to handle trackball motion events.  The
7578     * <em>relative</em> movement of the trackball since the last event
7579     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7580     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7581     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7582     * they will often be fractional values, representing the more fine-grained
7583     * movement information available from a trackball).
7584     *
7585     * @param event The motion event.
7586     * @return True if the event was handled, false otherwise.
7587     */
7588    public boolean onTrackballEvent(MotionEvent event) {
7589        return false;
7590    }
7591
7592    /**
7593     * Implement this method to handle generic motion events.
7594     * <p>
7595     * Generic motion events describe joystick movements, mouse hovers, track pad
7596     * touches, scroll wheel movements and other input events.  The
7597     * {@link MotionEvent#getSource() source} of the motion event specifies
7598     * the class of input that was received.  Implementations of this method
7599     * must examine the bits in the source before processing the event.
7600     * The following code example shows how this is done.
7601     * </p><p>
7602     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7603     * are delivered to the view under the pointer.  All other generic motion events are
7604     * delivered to the focused view.
7605     * </p>
7606     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7607     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7608     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7609     *             // process the joystick movement...
7610     *             return true;
7611     *         }
7612     *     }
7613     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7614     *         switch (event.getAction()) {
7615     *             case MotionEvent.ACTION_HOVER_MOVE:
7616     *                 // process the mouse hover movement...
7617     *                 return true;
7618     *             case MotionEvent.ACTION_SCROLL:
7619     *                 // process the scroll wheel movement...
7620     *                 return true;
7621     *         }
7622     *     }
7623     *     return super.onGenericMotionEvent(event);
7624     * }</pre>
7625     *
7626     * @param event The generic motion event being processed.
7627     * @return True if the event was handled, false otherwise.
7628     */
7629    public boolean onGenericMotionEvent(MotionEvent event) {
7630        return false;
7631    }
7632
7633    /**
7634     * Implement this method to handle hover events.
7635     * <p>
7636     * This method is called whenever a pointer is hovering into, over, or out of the
7637     * bounds of a view and the view is not currently being touched.
7638     * Hover events are represented as pointer events with action
7639     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7640     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7641     * </p>
7642     * <ul>
7643     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7644     * when the pointer enters the bounds of the view.</li>
7645     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7646     * when the pointer has already entered the bounds of the view and has moved.</li>
7647     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7648     * when the pointer has exited the bounds of the view or when the pointer is
7649     * about to go down due to a button click, tap, or similar user action that
7650     * causes the view to be touched.</li>
7651     * </ul>
7652     * <p>
7653     * The view should implement this method to return true to indicate that it is
7654     * handling the hover event, such as by changing its drawable state.
7655     * </p><p>
7656     * The default implementation calls {@link #setHovered} to update the hovered state
7657     * of the view when a hover enter or hover exit event is received, if the view
7658     * is enabled and is clickable.  The default implementation also sends hover
7659     * accessibility events.
7660     * </p>
7661     *
7662     * @param event The motion event that describes the hover.
7663     * @return True if the view handled the hover event.
7664     *
7665     * @see #isHovered
7666     * @see #setHovered
7667     * @see #onHoverChanged
7668     */
7669    public boolean onHoverEvent(MotionEvent event) {
7670        // The root view may receive hover (or touch) events that are outside the bounds of
7671        // the window.  This code ensures that we only send accessibility events for
7672        // hovers that are actually within the bounds of the root view.
7673        final int action = event.getActionMasked();
7674        if (!mSendingHoverAccessibilityEvents) {
7675            if ((action == MotionEvent.ACTION_HOVER_ENTER
7676                    || action == MotionEvent.ACTION_HOVER_MOVE)
7677                    && !hasHoveredChild()
7678                    && pointInView(event.getX(), event.getY())) {
7679                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7680                mSendingHoverAccessibilityEvents = true;
7681                requestAccessibilityFocusFromHover();
7682            }
7683        } else {
7684            if (action == MotionEvent.ACTION_HOVER_EXIT
7685                    || (action == MotionEvent.ACTION_MOVE
7686                            && !pointInView(event.getX(), event.getY()))) {
7687                mSendingHoverAccessibilityEvents = false;
7688                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7689                // If the window does not have input focus we take away accessibility
7690                // focus as soon as the user stop hovering over the view.
7691                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7692                    getViewRootImpl().setAccessibilityFocusedHost(null);
7693                }
7694            }
7695        }
7696
7697        if (isHoverable()) {
7698            switch (action) {
7699                case MotionEvent.ACTION_HOVER_ENTER:
7700                    setHovered(true);
7701                    break;
7702                case MotionEvent.ACTION_HOVER_EXIT:
7703                    setHovered(false);
7704                    break;
7705            }
7706
7707            // Dispatch the event to onGenericMotionEvent before returning true.
7708            // This is to provide compatibility with existing applications that
7709            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7710            // break because of the new default handling for hoverable views
7711            // in onHoverEvent.
7712            // Note that onGenericMotionEvent will be called by default when
7713            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7714            dispatchGenericMotionEventInternal(event);
7715            return true;
7716        }
7717
7718        return false;
7719    }
7720
7721    /**
7722     * Returns true if the view should handle {@link #onHoverEvent}
7723     * by calling {@link #setHovered} to change its hovered state.
7724     *
7725     * @return True if the view is hoverable.
7726     */
7727    private boolean isHoverable() {
7728        final int viewFlags = mViewFlags;
7729        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7730            return false;
7731        }
7732
7733        return (viewFlags & CLICKABLE) == CLICKABLE
7734                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7735    }
7736
7737    /**
7738     * Returns true if the view is currently hovered.
7739     *
7740     * @return True if the view is currently hovered.
7741     *
7742     * @see #setHovered
7743     * @see #onHoverChanged
7744     */
7745    @ViewDebug.ExportedProperty
7746    public boolean isHovered() {
7747        return (mPrivateFlags & HOVERED) != 0;
7748    }
7749
7750    /**
7751     * Sets whether the view is currently hovered.
7752     * <p>
7753     * Calling this method also changes the drawable state of the view.  This
7754     * enables the view to react to hover by using different drawable resources
7755     * to change its appearance.
7756     * </p><p>
7757     * The {@link #onHoverChanged} method is called when the hovered state changes.
7758     * </p>
7759     *
7760     * @param hovered True if the view is hovered.
7761     *
7762     * @see #isHovered
7763     * @see #onHoverChanged
7764     */
7765    public void setHovered(boolean hovered) {
7766        if (hovered) {
7767            if ((mPrivateFlags & HOVERED) == 0) {
7768                mPrivateFlags |= HOVERED;
7769                refreshDrawableState();
7770                onHoverChanged(true);
7771            }
7772        } else {
7773            if ((mPrivateFlags & HOVERED) != 0) {
7774                mPrivateFlags &= ~HOVERED;
7775                refreshDrawableState();
7776                onHoverChanged(false);
7777            }
7778        }
7779    }
7780
7781    /**
7782     * Implement this method to handle hover state changes.
7783     * <p>
7784     * This method is called whenever the hover state changes as a result of a
7785     * call to {@link #setHovered}.
7786     * </p>
7787     *
7788     * @param hovered The current hover state, as returned by {@link #isHovered}.
7789     *
7790     * @see #isHovered
7791     * @see #setHovered
7792     */
7793    public void onHoverChanged(boolean hovered) {
7794    }
7795
7796    /**
7797     * Implement this method to handle touch screen motion events.
7798     *
7799     * @param event The motion event.
7800     * @return True if the event was handled, false otherwise.
7801     */
7802    public boolean onTouchEvent(MotionEvent event) {
7803        final int viewFlags = mViewFlags;
7804
7805        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7806            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7807                setPressed(false);
7808            }
7809            // A disabled view that is clickable still consumes the touch
7810            // events, it just doesn't respond to them.
7811            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7812                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7813        }
7814
7815        if (mTouchDelegate != null) {
7816            if (mTouchDelegate.onTouchEvent(event)) {
7817                return true;
7818            }
7819        }
7820
7821        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7822                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7823            switch (event.getAction()) {
7824                case MotionEvent.ACTION_UP:
7825                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7826                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7827                        // take focus if we don't have it already and we should in
7828                        // touch mode.
7829                        boolean focusTaken = false;
7830                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7831                            focusTaken = requestFocus();
7832                        }
7833
7834                        if (prepressed) {
7835                            // The button is being released before we actually
7836                            // showed it as pressed.  Make it show the pressed
7837                            // state now (before scheduling the click) to ensure
7838                            // the user sees it.
7839                            setPressed(true);
7840                       }
7841
7842                        if (!mHasPerformedLongPress) {
7843                            // This is a tap, so remove the longpress check
7844                            removeLongPressCallback();
7845
7846                            // Only perform take click actions if we were in the pressed state
7847                            if (!focusTaken) {
7848                                // Use a Runnable and post this rather than calling
7849                                // performClick directly. This lets other visual state
7850                                // of the view update before click actions start.
7851                                if (mPerformClick == null) {
7852                                    mPerformClick = new PerformClick();
7853                                }
7854                                if (!post(mPerformClick)) {
7855                                    performClick();
7856                                }
7857                            }
7858                        }
7859
7860                        if (mUnsetPressedState == null) {
7861                            mUnsetPressedState = new UnsetPressedState();
7862                        }
7863
7864                        if (prepressed) {
7865                            postDelayed(mUnsetPressedState,
7866                                    ViewConfiguration.getPressedStateDuration());
7867                        } else if (!post(mUnsetPressedState)) {
7868                            // If the post failed, unpress right now
7869                            mUnsetPressedState.run();
7870                        }
7871                        removeTapCallback();
7872                    }
7873                    break;
7874
7875                case MotionEvent.ACTION_DOWN:
7876                    mHasPerformedLongPress = false;
7877
7878                    if (performButtonActionOnTouchDown(event)) {
7879                        break;
7880                    }
7881
7882                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7883                    boolean isInScrollingContainer = isInScrollingContainer();
7884
7885                    // For views inside a scrolling container, delay the pressed feedback for
7886                    // a short period in case this is a scroll.
7887                    if (isInScrollingContainer) {
7888                        mPrivateFlags |= PREPRESSED;
7889                        if (mPendingCheckForTap == null) {
7890                            mPendingCheckForTap = new CheckForTap();
7891                        }
7892                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7893                    } else {
7894                        // Not inside a scrolling container, so show the feedback right away
7895                        setPressed(true);
7896                        checkForLongClick(0);
7897                    }
7898                    break;
7899
7900                case MotionEvent.ACTION_CANCEL:
7901                    setPressed(false);
7902                    removeTapCallback();
7903                    break;
7904
7905                case MotionEvent.ACTION_MOVE:
7906                    final int x = (int) event.getX();
7907                    final int y = (int) event.getY();
7908
7909                    // Be lenient about moving outside of buttons
7910                    if (!pointInView(x, y, mTouchSlop)) {
7911                        // Outside button
7912                        removeTapCallback();
7913                        if ((mPrivateFlags & PRESSED) != 0) {
7914                            // Remove any future long press/tap checks
7915                            removeLongPressCallback();
7916
7917                            setPressed(false);
7918                        }
7919                    }
7920                    break;
7921            }
7922            return true;
7923        }
7924
7925        return false;
7926    }
7927
7928    /**
7929     * @hide
7930     */
7931    public boolean isInScrollingContainer() {
7932        ViewParent p = getParent();
7933        while (p != null && p instanceof ViewGroup) {
7934            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7935                return true;
7936            }
7937            p = p.getParent();
7938        }
7939        return false;
7940    }
7941
7942    /**
7943     * Remove the longpress detection timer.
7944     */
7945    private void removeLongPressCallback() {
7946        if (mPendingCheckForLongPress != null) {
7947          removeCallbacks(mPendingCheckForLongPress);
7948        }
7949    }
7950
7951    /**
7952     * Remove the pending click action
7953     */
7954    private void removePerformClickCallback() {
7955        if (mPerformClick != null) {
7956            removeCallbacks(mPerformClick);
7957        }
7958    }
7959
7960    /**
7961     * Remove the prepress detection timer.
7962     */
7963    private void removeUnsetPressCallback() {
7964        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7965            setPressed(false);
7966            removeCallbacks(mUnsetPressedState);
7967        }
7968    }
7969
7970    /**
7971     * Remove the tap detection timer.
7972     */
7973    private void removeTapCallback() {
7974        if (mPendingCheckForTap != null) {
7975            mPrivateFlags &= ~PREPRESSED;
7976            removeCallbacks(mPendingCheckForTap);
7977        }
7978    }
7979
7980    /**
7981     * Cancels a pending long press.  Your subclass can use this if you
7982     * want the context menu to come up if the user presses and holds
7983     * at the same place, but you don't want it to come up if they press
7984     * and then move around enough to cause scrolling.
7985     */
7986    public void cancelLongPress() {
7987        removeLongPressCallback();
7988
7989        /*
7990         * The prepressed state handled by the tap callback is a display
7991         * construct, but the tap callback will post a long press callback
7992         * less its own timeout. Remove it here.
7993         */
7994        removeTapCallback();
7995    }
7996
7997    /**
7998     * Remove the pending callback for sending a
7999     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8000     */
8001    private void removeSendViewScrolledAccessibilityEventCallback() {
8002        if (mSendViewScrolledAccessibilityEvent != null) {
8003            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8004        }
8005    }
8006
8007    /**
8008     * Sets the TouchDelegate for this View.
8009     */
8010    public void setTouchDelegate(TouchDelegate delegate) {
8011        mTouchDelegate = delegate;
8012    }
8013
8014    /**
8015     * Gets the TouchDelegate for this View.
8016     */
8017    public TouchDelegate getTouchDelegate() {
8018        return mTouchDelegate;
8019    }
8020
8021    /**
8022     * Set flags controlling behavior of this view.
8023     *
8024     * @param flags Constant indicating the value which should be set
8025     * @param mask Constant indicating the bit range that should be changed
8026     */
8027    void setFlags(int flags, int mask) {
8028        int old = mViewFlags;
8029        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8030
8031        int changed = mViewFlags ^ old;
8032        if (changed == 0) {
8033            return;
8034        }
8035        int privateFlags = mPrivateFlags;
8036
8037        /* Check if the FOCUSABLE bit has changed */
8038        if (((changed & FOCUSABLE_MASK) != 0) &&
8039                ((privateFlags & HAS_BOUNDS) !=0)) {
8040            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8041                    && ((privateFlags & FOCUSED) != 0)) {
8042                /* Give up focus if we are no longer focusable */
8043                clearFocus();
8044            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8045                    && ((privateFlags & FOCUSED) == 0)) {
8046                /*
8047                 * Tell the view system that we are now available to take focus
8048                 * if no one else already has it.
8049                 */
8050                if (mParent != null) mParent.focusableViewAvailable(this);
8051            }
8052            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8053                notifyAccessibilityStateChanged();
8054            }
8055        }
8056
8057        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8058            if ((changed & VISIBILITY_MASK) != 0) {
8059                /*
8060                 * If this view is becoming visible, invalidate it in case it changed while
8061                 * it was not visible. Marking it drawn ensures that the invalidation will
8062                 * go through.
8063                 */
8064                mPrivateFlags |= DRAWN;
8065                invalidate(true);
8066
8067                needGlobalAttributesUpdate(true);
8068
8069                // a view becoming visible is worth notifying the parent
8070                // about in case nothing has focus.  even if this specific view
8071                // isn't focusable, it may contain something that is, so let
8072                // the root view try to give this focus if nothing else does.
8073                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8074                    mParent.focusableViewAvailable(this);
8075                }
8076            }
8077        }
8078
8079        /* Check if the GONE bit has changed */
8080        if ((changed & GONE) != 0) {
8081            needGlobalAttributesUpdate(false);
8082            requestLayout();
8083
8084            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8085                if (hasFocus()) clearFocus();
8086                clearAccessibilityFocus();
8087                destroyDrawingCache();
8088                if (mParent instanceof View) {
8089                    // GONE views noop invalidation, so invalidate the parent
8090                    ((View) mParent).invalidate(true);
8091                }
8092                // Mark the view drawn to ensure that it gets invalidated properly the next
8093                // time it is visible and gets invalidated
8094                mPrivateFlags |= DRAWN;
8095            }
8096            if (mAttachInfo != null) {
8097                mAttachInfo.mViewVisibilityChanged = true;
8098            }
8099        }
8100
8101        /* Check if the VISIBLE bit has changed */
8102        if ((changed & INVISIBLE) != 0) {
8103            needGlobalAttributesUpdate(false);
8104            /*
8105             * If this view is becoming invisible, set the DRAWN flag so that
8106             * the next invalidate() will not be skipped.
8107             */
8108            mPrivateFlags |= DRAWN;
8109
8110            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8111                // root view becoming invisible shouldn't clear focus and accessibility focus
8112                if (getRootView() != this) {
8113                    clearFocus();
8114                    clearAccessibilityFocus();
8115                }
8116            }
8117            if (mAttachInfo != null) {
8118                mAttachInfo.mViewVisibilityChanged = true;
8119            }
8120        }
8121
8122        if ((changed & VISIBILITY_MASK) != 0) {
8123            if (mParent instanceof ViewGroup) {
8124                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8125                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8126                ((View) mParent).invalidate(true);
8127            } else if (mParent != null) {
8128                mParent.invalidateChild(this, null);
8129            }
8130            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8131        }
8132
8133        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8134            destroyDrawingCache();
8135        }
8136
8137        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8138            destroyDrawingCache();
8139            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8140            invalidateParentCaches();
8141        }
8142
8143        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8144            destroyDrawingCache();
8145            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8146        }
8147
8148        if ((changed & DRAW_MASK) != 0) {
8149            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8150                if (mBackground != null) {
8151                    mPrivateFlags &= ~SKIP_DRAW;
8152                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8153                } else {
8154                    mPrivateFlags |= SKIP_DRAW;
8155                }
8156            } else {
8157                mPrivateFlags &= ~SKIP_DRAW;
8158            }
8159            requestLayout();
8160            invalidate(true);
8161        }
8162
8163        if ((changed & KEEP_SCREEN_ON) != 0) {
8164            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8165                mParent.recomputeViewAttributes(this);
8166            }
8167        }
8168
8169        if (AccessibilityManager.getInstance(mContext).isEnabled()
8170                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8171                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8172            notifyAccessibilityStateChanged();
8173        }
8174    }
8175
8176    /**
8177     * Change the view's z order in the tree, so it's on top of other sibling
8178     * views
8179     */
8180    public void bringToFront() {
8181        if (mParent != null) {
8182            mParent.bringChildToFront(this);
8183        }
8184    }
8185
8186    /**
8187     * This is called in response to an internal scroll in this view (i.e., the
8188     * view scrolled its own contents). This is typically as a result of
8189     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8190     * called.
8191     *
8192     * @param l Current horizontal scroll origin.
8193     * @param t Current vertical scroll origin.
8194     * @param oldl Previous horizontal scroll origin.
8195     * @param oldt Previous vertical scroll origin.
8196     */
8197    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8198        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8199            postSendViewScrolledAccessibilityEventCallback();
8200        }
8201
8202        mBackgroundSizeChanged = true;
8203
8204        final AttachInfo ai = mAttachInfo;
8205        if (ai != null) {
8206            ai.mViewScrollChanged = true;
8207        }
8208    }
8209
8210    /**
8211     * Interface definition for a callback to be invoked when the layout bounds of a view
8212     * changes due to layout processing.
8213     */
8214    public interface OnLayoutChangeListener {
8215        /**
8216         * Called when the focus state of a view has changed.
8217         *
8218         * @param v The view whose state has changed.
8219         * @param left The new value of the view's left property.
8220         * @param top The new value of the view's top property.
8221         * @param right The new value of the view's right property.
8222         * @param bottom The new value of the view's bottom property.
8223         * @param oldLeft The previous value of the view's left property.
8224         * @param oldTop The previous value of the view's top property.
8225         * @param oldRight The previous value of the view's right property.
8226         * @param oldBottom The previous value of the view's bottom property.
8227         */
8228        void onLayoutChange(View v, int left, int top, int right, int bottom,
8229            int oldLeft, int oldTop, int oldRight, int oldBottom);
8230    }
8231
8232    /**
8233     * This is called during layout when the size of this view has changed. If
8234     * you were just added to the view hierarchy, you're called with the old
8235     * values of 0.
8236     *
8237     * @param w Current width of this view.
8238     * @param h Current height of this view.
8239     * @param oldw Old width of this view.
8240     * @param oldh Old height of this view.
8241     */
8242    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8243    }
8244
8245    /**
8246     * Called by draw to draw the child views. This may be overridden
8247     * by derived classes to gain control just before its children are drawn
8248     * (but after its own view has been drawn).
8249     * @param canvas the canvas on which to draw the view
8250     */
8251    protected void dispatchDraw(Canvas canvas) {
8252
8253    }
8254
8255    /**
8256     * Gets the parent of this view. Note that the parent is a
8257     * ViewParent and not necessarily a View.
8258     *
8259     * @return Parent of this view.
8260     */
8261    public final ViewParent getParent() {
8262        return mParent;
8263    }
8264
8265    /**
8266     * Set the horizontal scrolled position of your view. This will cause a call to
8267     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8268     * invalidated.
8269     * @param value the x position to scroll to
8270     */
8271    public void setScrollX(int value) {
8272        scrollTo(value, mScrollY);
8273    }
8274
8275    /**
8276     * Set the vertical scrolled position of your view. This will cause a call to
8277     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8278     * invalidated.
8279     * @param value the y position to scroll to
8280     */
8281    public void setScrollY(int value) {
8282        scrollTo(mScrollX, value);
8283    }
8284
8285    /**
8286     * Return the scrolled left position of this view. This is the left edge of
8287     * the displayed part of your view. You do not need to draw any pixels
8288     * farther left, since those are outside of the frame of your view on
8289     * screen.
8290     *
8291     * @return The left edge of the displayed part of your view, in pixels.
8292     */
8293    public final int getScrollX() {
8294        return mScrollX;
8295    }
8296
8297    /**
8298     * Return the scrolled top position of this view. This is the top edge of
8299     * the displayed part of your view. You do not need to draw any pixels above
8300     * it, since those are outside of the frame of your view on screen.
8301     *
8302     * @return The top edge of the displayed part of your view, in pixels.
8303     */
8304    public final int getScrollY() {
8305        return mScrollY;
8306    }
8307
8308    /**
8309     * Return the width of the your view.
8310     *
8311     * @return The width of your view, in pixels.
8312     */
8313    @ViewDebug.ExportedProperty(category = "layout")
8314    public final int getWidth() {
8315        return mRight - mLeft;
8316    }
8317
8318    /**
8319     * Return the height of your view.
8320     *
8321     * @return The height of your view, in pixels.
8322     */
8323    @ViewDebug.ExportedProperty(category = "layout")
8324    public final int getHeight() {
8325        return mBottom - mTop;
8326    }
8327
8328    /**
8329     * Return the visible drawing bounds of your view. Fills in the output
8330     * rectangle with the values from getScrollX(), getScrollY(),
8331     * getWidth(), and getHeight().
8332     *
8333     * @param outRect The (scrolled) drawing bounds of the view.
8334     */
8335    public void getDrawingRect(Rect outRect) {
8336        outRect.left = mScrollX;
8337        outRect.top = mScrollY;
8338        outRect.right = mScrollX + (mRight - mLeft);
8339        outRect.bottom = mScrollY + (mBottom - mTop);
8340    }
8341
8342    /**
8343     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8344     * raw width component (that is the result is masked by
8345     * {@link #MEASURED_SIZE_MASK}).
8346     *
8347     * @return The raw measured width of this view.
8348     */
8349    public final int getMeasuredWidth() {
8350        return mMeasuredWidth & MEASURED_SIZE_MASK;
8351    }
8352
8353    /**
8354     * Return the full width measurement information for this view as computed
8355     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8356     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8357     * This should be used during measurement and layout calculations only. Use
8358     * {@link #getWidth()} to see how wide a view is after layout.
8359     *
8360     * @return The measured width of this view as a bit mask.
8361     */
8362    public final int getMeasuredWidthAndState() {
8363        return mMeasuredWidth;
8364    }
8365
8366    /**
8367     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8368     * raw width component (that is the result is masked by
8369     * {@link #MEASURED_SIZE_MASK}).
8370     *
8371     * @return The raw measured height of this view.
8372     */
8373    public final int getMeasuredHeight() {
8374        return mMeasuredHeight & MEASURED_SIZE_MASK;
8375    }
8376
8377    /**
8378     * Return the full height measurement information for this view as computed
8379     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8380     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8381     * This should be used during measurement and layout calculations only. Use
8382     * {@link #getHeight()} to see how wide a view is after layout.
8383     *
8384     * @return The measured width of this view as a bit mask.
8385     */
8386    public final int getMeasuredHeightAndState() {
8387        return mMeasuredHeight;
8388    }
8389
8390    /**
8391     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8392     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8393     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8394     * and the height component is at the shifted bits
8395     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8396     */
8397    public final int getMeasuredState() {
8398        return (mMeasuredWidth&MEASURED_STATE_MASK)
8399                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8400                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8401    }
8402
8403    /**
8404     * The transform matrix of this view, which is calculated based on the current
8405     * roation, scale, and pivot properties.
8406     *
8407     * @see #getRotation()
8408     * @see #getScaleX()
8409     * @see #getScaleY()
8410     * @see #getPivotX()
8411     * @see #getPivotY()
8412     * @return The current transform matrix for the view
8413     */
8414    public Matrix getMatrix() {
8415        if (mTransformationInfo != null) {
8416            updateMatrix();
8417            return mTransformationInfo.mMatrix;
8418        }
8419        return Matrix.IDENTITY_MATRIX;
8420    }
8421
8422    /**
8423     * Utility function to determine if the value is far enough away from zero to be
8424     * considered non-zero.
8425     * @param value A floating point value to check for zero-ness
8426     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8427     */
8428    private static boolean nonzero(float value) {
8429        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8430    }
8431
8432    /**
8433     * Returns true if the transform matrix is the identity matrix.
8434     * Recomputes the matrix if necessary.
8435     *
8436     * @return True if the transform matrix is the identity matrix, false otherwise.
8437     */
8438    final boolean hasIdentityMatrix() {
8439        if (mTransformationInfo != null) {
8440            updateMatrix();
8441            return mTransformationInfo.mMatrixIsIdentity;
8442        }
8443        return true;
8444    }
8445
8446    void ensureTransformationInfo() {
8447        if (mTransformationInfo == null) {
8448            mTransformationInfo = new TransformationInfo();
8449        }
8450    }
8451
8452    /**
8453     * Recomputes the transform matrix if necessary.
8454     */
8455    private void updateMatrix() {
8456        final TransformationInfo info = mTransformationInfo;
8457        if (info == null) {
8458            return;
8459        }
8460        if (info.mMatrixDirty) {
8461            // transform-related properties have changed since the last time someone
8462            // asked for the matrix; recalculate it with the current values
8463
8464            // Figure out if we need to update the pivot point
8465            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8466                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8467                    info.mPrevWidth = mRight - mLeft;
8468                    info.mPrevHeight = mBottom - mTop;
8469                    info.mPivotX = info.mPrevWidth / 2f;
8470                    info.mPivotY = info.mPrevHeight / 2f;
8471                }
8472            }
8473            info.mMatrix.reset();
8474            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8475                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8476                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8477                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8478            } else {
8479                if (info.mCamera == null) {
8480                    info.mCamera = new Camera();
8481                    info.matrix3D = new Matrix();
8482                }
8483                info.mCamera.save();
8484                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8485                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8486                info.mCamera.getMatrix(info.matrix3D);
8487                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8488                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8489                        info.mPivotY + info.mTranslationY);
8490                info.mMatrix.postConcat(info.matrix3D);
8491                info.mCamera.restore();
8492            }
8493            info.mMatrixDirty = false;
8494            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8495            info.mInverseMatrixDirty = true;
8496        }
8497    }
8498
8499    /**
8500     * Utility method to retrieve the inverse of the current mMatrix property.
8501     * We cache the matrix to avoid recalculating it when transform properties
8502     * have not changed.
8503     *
8504     * @return The inverse of the current matrix of this view.
8505     */
8506    final Matrix getInverseMatrix() {
8507        final TransformationInfo info = mTransformationInfo;
8508        if (info != null) {
8509            updateMatrix();
8510            if (info.mInverseMatrixDirty) {
8511                if (info.mInverseMatrix == null) {
8512                    info.mInverseMatrix = new Matrix();
8513                }
8514                info.mMatrix.invert(info.mInverseMatrix);
8515                info.mInverseMatrixDirty = false;
8516            }
8517            return info.mInverseMatrix;
8518        }
8519        return Matrix.IDENTITY_MATRIX;
8520    }
8521
8522    /**
8523     * Gets the distance along the Z axis from the camera to this view.
8524     *
8525     * @see #setCameraDistance(float)
8526     *
8527     * @return The distance along the Z axis.
8528     */
8529    public float getCameraDistance() {
8530        ensureTransformationInfo();
8531        final float dpi = mResources.getDisplayMetrics().densityDpi;
8532        final TransformationInfo info = mTransformationInfo;
8533        if (info.mCamera == null) {
8534            info.mCamera = new Camera();
8535            info.matrix3D = new Matrix();
8536        }
8537        return -(info.mCamera.getLocationZ() * dpi);
8538    }
8539
8540    /**
8541     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8542     * views are drawn) from the camera to this view. The camera's distance
8543     * affects 3D transformations, for instance rotations around the X and Y
8544     * axis. If the rotationX or rotationY properties are changed and this view is
8545     * large (more than half the size of the screen), it is recommended to always
8546     * use a camera distance that's greater than the height (X axis rotation) or
8547     * the width (Y axis rotation) of this view.</p>
8548     *
8549     * <p>The distance of the camera from the view plane can have an affect on the
8550     * perspective distortion of the view when it is rotated around the x or y axis.
8551     * For example, a large distance will result in a large viewing angle, and there
8552     * will not be much perspective distortion of the view as it rotates. A short
8553     * distance may cause much more perspective distortion upon rotation, and can
8554     * also result in some drawing artifacts if the rotated view ends up partially
8555     * behind the camera (which is why the recommendation is to use a distance at
8556     * least as far as the size of the view, if the view is to be rotated.)</p>
8557     *
8558     * <p>The distance is expressed in "depth pixels." The default distance depends
8559     * on the screen density. For instance, on a medium density display, the
8560     * default distance is 1280. On a high density display, the default distance
8561     * is 1920.</p>
8562     *
8563     * <p>If you want to specify a distance that leads to visually consistent
8564     * results across various densities, use the following formula:</p>
8565     * <pre>
8566     * float scale = context.getResources().getDisplayMetrics().density;
8567     * view.setCameraDistance(distance * scale);
8568     * </pre>
8569     *
8570     * <p>The density scale factor of a high density display is 1.5,
8571     * and 1920 = 1280 * 1.5.</p>
8572     *
8573     * @param distance The distance in "depth pixels", if negative the opposite
8574     *        value is used
8575     *
8576     * @see #setRotationX(float)
8577     * @see #setRotationY(float)
8578     */
8579    public void setCameraDistance(float distance) {
8580        invalidateViewProperty(true, false);
8581
8582        ensureTransformationInfo();
8583        final float dpi = mResources.getDisplayMetrics().densityDpi;
8584        final TransformationInfo info = mTransformationInfo;
8585        if (info.mCamera == null) {
8586            info.mCamera = new Camera();
8587            info.matrix3D = new Matrix();
8588        }
8589
8590        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8591        info.mMatrixDirty = true;
8592
8593        invalidateViewProperty(false, false);
8594        if (mDisplayList != null) {
8595            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8596        }
8597        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8598            // View was rejected last time it was drawn by its parent; this may have changed
8599            invalidateParentIfNeeded();
8600        }
8601    }
8602
8603    /**
8604     * The degrees that the view is rotated around the pivot point.
8605     *
8606     * @see #setRotation(float)
8607     * @see #getPivotX()
8608     * @see #getPivotY()
8609     *
8610     * @return The degrees of rotation.
8611     */
8612    @ViewDebug.ExportedProperty(category = "drawing")
8613    public float getRotation() {
8614        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8615    }
8616
8617    /**
8618     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8619     * result in clockwise rotation.
8620     *
8621     * @param rotation The degrees of rotation.
8622     *
8623     * @see #getRotation()
8624     * @see #getPivotX()
8625     * @see #getPivotY()
8626     * @see #setRotationX(float)
8627     * @see #setRotationY(float)
8628     *
8629     * @attr ref android.R.styleable#View_rotation
8630     */
8631    public void setRotation(float rotation) {
8632        ensureTransformationInfo();
8633        final TransformationInfo info = mTransformationInfo;
8634        if (info.mRotation != rotation) {
8635            // Double-invalidation is necessary to capture view's old and new areas
8636            invalidateViewProperty(true, false);
8637            info.mRotation = rotation;
8638            info.mMatrixDirty = true;
8639            invalidateViewProperty(false, true);
8640            if (mDisplayList != null) {
8641                mDisplayList.setRotation(rotation);
8642            }
8643            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8644                // View was rejected last time it was drawn by its parent; this may have changed
8645                invalidateParentIfNeeded();
8646            }
8647        }
8648    }
8649
8650    /**
8651     * The degrees that the view is rotated around the vertical axis through the pivot point.
8652     *
8653     * @see #getPivotX()
8654     * @see #getPivotY()
8655     * @see #setRotationY(float)
8656     *
8657     * @return The degrees of Y rotation.
8658     */
8659    @ViewDebug.ExportedProperty(category = "drawing")
8660    public float getRotationY() {
8661        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8662    }
8663
8664    /**
8665     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8666     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8667     * down the y axis.
8668     *
8669     * When rotating large views, it is recommended to adjust the camera distance
8670     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8671     *
8672     * @param rotationY The degrees of Y rotation.
8673     *
8674     * @see #getRotationY()
8675     * @see #getPivotX()
8676     * @see #getPivotY()
8677     * @see #setRotation(float)
8678     * @see #setRotationX(float)
8679     * @see #setCameraDistance(float)
8680     *
8681     * @attr ref android.R.styleable#View_rotationY
8682     */
8683    public void setRotationY(float rotationY) {
8684        ensureTransformationInfo();
8685        final TransformationInfo info = mTransformationInfo;
8686        if (info.mRotationY != rotationY) {
8687            invalidateViewProperty(true, false);
8688            info.mRotationY = rotationY;
8689            info.mMatrixDirty = true;
8690            invalidateViewProperty(false, true);
8691            if (mDisplayList != null) {
8692                mDisplayList.setRotationY(rotationY);
8693            }
8694            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8695                // View was rejected last time it was drawn by its parent; this may have changed
8696                invalidateParentIfNeeded();
8697            }
8698        }
8699    }
8700
8701    /**
8702     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8703     *
8704     * @see #getPivotX()
8705     * @see #getPivotY()
8706     * @see #setRotationX(float)
8707     *
8708     * @return The degrees of X rotation.
8709     */
8710    @ViewDebug.ExportedProperty(category = "drawing")
8711    public float getRotationX() {
8712        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8713    }
8714
8715    /**
8716     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8717     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8718     * x axis.
8719     *
8720     * When rotating large views, it is recommended to adjust the camera distance
8721     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8722     *
8723     * @param rotationX The degrees of X rotation.
8724     *
8725     * @see #getRotationX()
8726     * @see #getPivotX()
8727     * @see #getPivotY()
8728     * @see #setRotation(float)
8729     * @see #setRotationY(float)
8730     * @see #setCameraDistance(float)
8731     *
8732     * @attr ref android.R.styleable#View_rotationX
8733     */
8734    public void setRotationX(float rotationX) {
8735        ensureTransformationInfo();
8736        final TransformationInfo info = mTransformationInfo;
8737        if (info.mRotationX != rotationX) {
8738            invalidateViewProperty(true, false);
8739            info.mRotationX = rotationX;
8740            info.mMatrixDirty = true;
8741            invalidateViewProperty(false, true);
8742            if (mDisplayList != null) {
8743                mDisplayList.setRotationX(rotationX);
8744            }
8745            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8746                // View was rejected last time it was drawn by its parent; this may have changed
8747                invalidateParentIfNeeded();
8748            }
8749        }
8750    }
8751
8752    /**
8753     * The amount that the view is scaled in x around the pivot point, as a proportion of
8754     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8755     *
8756     * <p>By default, this is 1.0f.
8757     *
8758     * @see #getPivotX()
8759     * @see #getPivotY()
8760     * @return The scaling factor.
8761     */
8762    @ViewDebug.ExportedProperty(category = "drawing")
8763    public float getScaleX() {
8764        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8765    }
8766
8767    /**
8768     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8769     * the view's unscaled width. A value of 1 means that no scaling is applied.
8770     *
8771     * @param scaleX The scaling factor.
8772     * @see #getPivotX()
8773     * @see #getPivotY()
8774     *
8775     * @attr ref android.R.styleable#View_scaleX
8776     */
8777    public void setScaleX(float scaleX) {
8778        ensureTransformationInfo();
8779        final TransformationInfo info = mTransformationInfo;
8780        if (info.mScaleX != scaleX) {
8781            invalidateViewProperty(true, false);
8782            info.mScaleX = scaleX;
8783            info.mMatrixDirty = true;
8784            invalidateViewProperty(false, true);
8785            if (mDisplayList != null) {
8786                mDisplayList.setScaleX(scaleX);
8787            }
8788            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8789                // View was rejected last time it was drawn by its parent; this may have changed
8790                invalidateParentIfNeeded();
8791            }
8792        }
8793    }
8794
8795    /**
8796     * The amount that the view is scaled in y around the pivot point, as a proportion of
8797     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8798     *
8799     * <p>By default, this is 1.0f.
8800     *
8801     * @see #getPivotX()
8802     * @see #getPivotY()
8803     * @return The scaling factor.
8804     */
8805    @ViewDebug.ExportedProperty(category = "drawing")
8806    public float getScaleY() {
8807        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8808    }
8809
8810    /**
8811     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8812     * the view's unscaled width. A value of 1 means that no scaling is applied.
8813     *
8814     * @param scaleY The scaling factor.
8815     * @see #getPivotX()
8816     * @see #getPivotY()
8817     *
8818     * @attr ref android.R.styleable#View_scaleY
8819     */
8820    public void setScaleY(float scaleY) {
8821        ensureTransformationInfo();
8822        final TransformationInfo info = mTransformationInfo;
8823        if (info.mScaleY != scaleY) {
8824            invalidateViewProperty(true, false);
8825            info.mScaleY = scaleY;
8826            info.mMatrixDirty = true;
8827            invalidateViewProperty(false, true);
8828            if (mDisplayList != null) {
8829                mDisplayList.setScaleY(scaleY);
8830            }
8831            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8832                // View was rejected last time it was drawn by its parent; this may have changed
8833                invalidateParentIfNeeded();
8834            }
8835        }
8836    }
8837
8838    /**
8839     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8840     * and {@link #setScaleX(float) scaled}.
8841     *
8842     * @see #getRotation()
8843     * @see #getScaleX()
8844     * @see #getScaleY()
8845     * @see #getPivotY()
8846     * @return The x location of the pivot point.
8847     *
8848     * @attr ref android.R.styleable#View_transformPivotX
8849     */
8850    @ViewDebug.ExportedProperty(category = "drawing")
8851    public float getPivotX() {
8852        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8853    }
8854
8855    /**
8856     * Sets the x location of the point around which the view is
8857     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8858     * By default, the pivot point is centered on the object.
8859     * Setting this property disables this behavior and causes the view to use only the
8860     * explicitly set pivotX and pivotY values.
8861     *
8862     * @param pivotX The x location of the pivot point.
8863     * @see #getRotation()
8864     * @see #getScaleX()
8865     * @see #getScaleY()
8866     * @see #getPivotY()
8867     *
8868     * @attr ref android.R.styleable#View_transformPivotX
8869     */
8870    public void setPivotX(float pivotX) {
8871        ensureTransformationInfo();
8872        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8873        final TransformationInfo info = mTransformationInfo;
8874        if (info.mPivotX != pivotX) {
8875            invalidateViewProperty(true, false);
8876            info.mPivotX = pivotX;
8877            info.mMatrixDirty = true;
8878            invalidateViewProperty(false, true);
8879            if (mDisplayList != null) {
8880                mDisplayList.setPivotX(pivotX);
8881            }
8882            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8883                // View was rejected last time it was drawn by its parent; this may have changed
8884                invalidateParentIfNeeded();
8885            }
8886        }
8887    }
8888
8889    /**
8890     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8891     * and {@link #setScaleY(float) scaled}.
8892     *
8893     * @see #getRotation()
8894     * @see #getScaleX()
8895     * @see #getScaleY()
8896     * @see #getPivotY()
8897     * @return The y location of the pivot point.
8898     *
8899     * @attr ref android.R.styleable#View_transformPivotY
8900     */
8901    @ViewDebug.ExportedProperty(category = "drawing")
8902    public float getPivotY() {
8903        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8904    }
8905
8906    /**
8907     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8908     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8909     * Setting this property disables this behavior and causes the view to use only the
8910     * explicitly set pivotX and pivotY values.
8911     *
8912     * @param pivotY The y location of the pivot point.
8913     * @see #getRotation()
8914     * @see #getScaleX()
8915     * @see #getScaleY()
8916     * @see #getPivotY()
8917     *
8918     * @attr ref android.R.styleable#View_transformPivotY
8919     */
8920    public void setPivotY(float pivotY) {
8921        ensureTransformationInfo();
8922        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8923        final TransformationInfo info = mTransformationInfo;
8924        if (info.mPivotY != pivotY) {
8925            invalidateViewProperty(true, false);
8926            info.mPivotY = pivotY;
8927            info.mMatrixDirty = true;
8928            invalidateViewProperty(false, true);
8929            if (mDisplayList != null) {
8930                mDisplayList.setPivotY(pivotY);
8931            }
8932            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8933                // View was rejected last time it was drawn by its parent; this may have changed
8934                invalidateParentIfNeeded();
8935            }
8936        }
8937    }
8938
8939    /**
8940     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8941     * completely transparent and 1 means the view is completely opaque.
8942     *
8943     * <p>By default this is 1.0f.
8944     * @return The opacity of the view.
8945     */
8946    @ViewDebug.ExportedProperty(category = "drawing")
8947    public float getAlpha() {
8948        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8949    }
8950
8951    /**
8952     * Returns whether this View has content which overlaps. This function, intended to be
8953     * overridden by specific View types, is an optimization when alpha is set on a view. If
8954     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8955     * and then composited it into place, which can be expensive. If the view has no overlapping
8956     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8957     * An example of overlapping rendering is a TextView with a background image, such as a
8958     * Button. An example of non-overlapping rendering is a TextView with no background, or
8959     * an ImageView with only the foreground image. The default implementation returns true;
8960     * subclasses should override if they have cases which can be optimized.
8961     *
8962     * @return true if the content in this view might overlap, false otherwise.
8963     */
8964    public boolean hasOverlappingRendering() {
8965        return true;
8966    }
8967
8968    /**
8969     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8970     * completely transparent and 1 means the view is completely opaque.</p>
8971     *
8972     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8973     * responsible for applying the opacity itself. Otherwise, calling this method is
8974     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8975     * setting a hardware layer.</p>
8976     *
8977     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8978     * performance implications. It is generally best to use the alpha property sparingly and
8979     * transiently, as in the case of fading animations.</p>
8980     *
8981     * @param alpha The opacity of the view.
8982     *
8983     * @see #setLayerType(int, android.graphics.Paint)
8984     *
8985     * @attr ref android.R.styleable#View_alpha
8986     */
8987    public void setAlpha(float alpha) {
8988        ensureTransformationInfo();
8989        if (mTransformationInfo.mAlpha != alpha) {
8990            mTransformationInfo.mAlpha = alpha;
8991            if (onSetAlpha((int) (alpha * 255))) {
8992                mPrivateFlags |= ALPHA_SET;
8993                // subclass is handling alpha - don't optimize rendering cache invalidation
8994                invalidateParentCaches();
8995                invalidate(true);
8996            } else {
8997                mPrivateFlags &= ~ALPHA_SET;
8998                invalidateViewProperty(true, false);
8999                if (mDisplayList != null) {
9000                    mDisplayList.setAlpha(alpha);
9001                }
9002            }
9003        }
9004    }
9005
9006    /**
9007     * Faster version of setAlpha() which performs the same steps except there are
9008     * no calls to invalidate(). The caller of this function should perform proper invalidation
9009     * on the parent and this object. The return value indicates whether the subclass handles
9010     * alpha (the return value for onSetAlpha()).
9011     *
9012     * @param alpha The new value for the alpha property
9013     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9014     *         the new value for the alpha property is different from the old value
9015     */
9016    boolean setAlphaNoInvalidation(float alpha) {
9017        ensureTransformationInfo();
9018        if (mTransformationInfo.mAlpha != alpha) {
9019            mTransformationInfo.mAlpha = alpha;
9020            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9021            if (subclassHandlesAlpha) {
9022                mPrivateFlags |= ALPHA_SET;
9023                return true;
9024            } else {
9025                mPrivateFlags &= ~ALPHA_SET;
9026                if (mDisplayList != null) {
9027                    mDisplayList.setAlpha(alpha);
9028                }
9029            }
9030        }
9031        return false;
9032    }
9033
9034    /**
9035     * Top position of this view relative to its parent.
9036     *
9037     * @return The top of this view, in pixels.
9038     */
9039    @ViewDebug.CapturedViewProperty
9040    public final int getTop() {
9041        return mTop;
9042    }
9043
9044    /**
9045     * Sets the top position of this view relative to its parent. This method is meant to be called
9046     * by the layout system and should not generally be called otherwise, because the property
9047     * may be changed at any time by the layout.
9048     *
9049     * @param top The top of this view, in pixels.
9050     */
9051    public final void setTop(int top) {
9052        if (top != mTop) {
9053            updateMatrix();
9054            final boolean matrixIsIdentity = mTransformationInfo == null
9055                    || mTransformationInfo.mMatrixIsIdentity;
9056            if (matrixIsIdentity) {
9057                if (mAttachInfo != null) {
9058                    int minTop;
9059                    int yLoc;
9060                    if (top < mTop) {
9061                        minTop = top;
9062                        yLoc = top - mTop;
9063                    } else {
9064                        minTop = mTop;
9065                        yLoc = 0;
9066                    }
9067                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9068                }
9069            } else {
9070                // Double-invalidation is necessary to capture view's old and new areas
9071                invalidate(true);
9072            }
9073
9074            int width = mRight - mLeft;
9075            int oldHeight = mBottom - mTop;
9076
9077            mTop = top;
9078            if (mDisplayList != null) {
9079                mDisplayList.setTop(mTop);
9080            }
9081
9082            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9083
9084            if (!matrixIsIdentity) {
9085                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9086                    // A change in dimension means an auto-centered pivot point changes, too
9087                    mTransformationInfo.mMatrixDirty = true;
9088                }
9089                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9090                invalidate(true);
9091            }
9092            mBackgroundSizeChanged = true;
9093            invalidateParentIfNeeded();
9094            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9095                // View was rejected last time it was drawn by its parent; this may have changed
9096                invalidateParentIfNeeded();
9097            }
9098        }
9099    }
9100
9101    /**
9102     * Bottom position of this view relative to its parent.
9103     *
9104     * @return The bottom of this view, in pixels.
9105     */
9106    @ViewDebug.CapturedViewProperty
9107    public final int getBottom() {
9108        return mBottom;
9109    }
9110
9111    /**
9112     * True if this view has changed since the last time being drawn.
9113     *
9114     * @return The dirty state of this view.
9115     */
9116    public boolean isDirty() {
9117        return (mPrivateFlags & DIRTY_MASK) != 0;
9118    }
9119
9120    /**
9121     * Sets the bottom position of this view relative to its parent. This method is meant to be
9122     * called by the layout system and should not generally be called otherwise, because the
9123     * property may be changed at any time by the layout.
9124     *
9125     * @param bottom The bottom of this view, in pixels.
9126     */
9127    public final void setBottom(int bottom) {
9128        if (bottom != mBottom) {
9129            updateMatrix();
9130            final boolean matrixIsIdentity = mTransformationInfo == null
9131                    || mTransformationInfo.mMatrixIsIdentity;
9132            if (matrixIsIdentity) {
9133                if (mAttachInfo != null) {
9134                    int maxBottom;
9135                    if (bottom < mBottom) {
9136                        maxBottom = mBottom;
9137                    } else {
9138                        maxBottom = bottom;
9139                    }
9140                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9141                }
9142            } else {
9143                // Double-invalidation is necessary to capture view's old and new areas
9144                invalidate(true);
9145            }
9146
9147            int width = mRight - mLeft;
9148            int oldHeight = mBottom - mTop;
9149
9150            mBottom = bottom;
9151            if (mDisplayList != null) {
9152                mDisplayList.setBottom(mBottom);
9153            }
9154
9155            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9156
9157            if (!matrixIsIdentity) {
9158                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9159                    // A change in dimension means an auto-centered pivot point changes, too
9160                    mTransformationInfo.mMatrixDirty = true;
9161                }
9162                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9163                invalidate(true);
9164            }
9165            mBackgroundSizeChanged = true;
9166            invalidateParentIfNeeded();
9167            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9168                // View was rejected last time it was drawn by its parent; this may have changed
9169                invalidateParentIfNeeded();
9170            }
9171        }
9172    }
9173
9174    /**
9175     * Left position of this view relative to its parent.
9176     *
9177     * @return The left edge of this view, in pixels.
9178     */
9179    @ViewDebug.CapturedViewProperty
9180    public final int getLeft() {
9181        return mLeft;
9182    }
9183
9184    /**
9185     * Sets the left position of this view relative to its parent. This method is meant to be called
9186     * by the layout system and should not generally be called otherwise, because the property
9187     * may be changed at any time by the layout.
9188     *
9189     * @param left The bottom of this view, in pixels.
9190     */
9191    public final void setLeft(int left) {
9192        if (left != mLeft) {
9193            updateMatrix();
9194            final boolean matrixIsIdentity = mTransformationInfo == null
9195                    || mTransformationInfo.mMatrixIsIdentity;
9196            if (matrixIsIdentity) {
9197                if (mAttachInfo != null) {
9198                    int minLeft;
9199                    int xLoc;
9200                    if (left < mLeft) {
9201                        minLeft = left;
9202                        xLoc = left - mLeft;
9203                    } else {
9204                        minLeft = mLeft;
9205                        xLoc = 0;
9206                    }
9207                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9208                }
9209            } else {
9210                // Double-invalidation is necessary to capture view's old and new areas
9211                invalidate(true);
9212            }
9213
9214            int oldWidth = mRight - mLeft;
9215            int height = mBottom - mTop;
9216
9217            mLeft = left;
9218            if (mDisplayList != null) {
9219                mDisplayList.setLeft(left);
9220            }
9221
9222            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9223
9224            if (!matrixIsIdentity) {
9225                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9226                    // A change in dimension means an auto-centered pivot point changes, too
9227                    mTransformationInfo.mMatrixDirty = true;
9228                }
9229                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9230                invalidate(true);
9231            }
9232            mBackgroundSizeChanged = true;
9233            invalidateParentIfNeeded();
9234            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9235                // View was rejected last time it was drawn by its parent; this may have changed
9236                invalidateParentIfNeeded();
9237            }
9238        }
9239    }
9240
9241    /**
9242     * Right position of this view relative to its parent.
9243     *
9244     * @return The right edge of this view, in pixels.
9245     */
9246    @ViewDebug.CapturedViewProperty
9247    public final int getRight() {
9248        return mRight;
9249    }
9250
9251    /**
9252     * Sets the right position of this view relative to its parent. This method is meant to be called
9253     * by the layout system and should not generally be called otherwise, because the property
9254     * may be changed at any time by the layout.
9255     *
9256     * @param right The bottom of this view, in pixels.
9257     */
9258    public final void setRight(int right) {
9259        if (right != mRight) {
9260            updateMatrix();
9261            final boolean matrixIsIdentity = mTransformationInfo == null
9262                    || mTransformationInfo.mMatrixIsIdentity;
9263            if (matrixIsIdentity) {
9264                if (mAttachInfo != null) {
9265                    int maxRight;
9266                    if (right < mRight) {
9267                        maxRight = mRight;
9268                    } else {
9269                        maxRight = right;
9270                    }
9271                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9272                }
9273            } else {
9274                // Double-invalidation is necessary to capture view's old and new areas
9275                invalidate(true);
9276            }
9277
9278            int oldWidth = mRight - mLeft;
9279            int height = mBottom - mTop;
9280
9281            mRight = right;
9282            if (mDisplayList != null) {
9283                mDisplayList.setRight(mRight);
9284            }
9285
9286            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9287
9288            if (!matrixIsIdentity) {
9289                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9290                    // A change in dimension means an auto-centered pivot point changes, too
9291                    mTransformationInfo.mMatrixDirty = true;
9292                }
9293                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9294                invalidate(true);
9295            }
9296            mBackgroundSizeChanged = true;
9297            invalidateParentIfNeeded();
9298            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9299                // View was rejected last time it was drawn by its parent; this may have changed
9300                invalidateParentIfNeeded();
9301            }
9302        }
9303    }
9304
9305    /**
9306     * The visual x position of this view, in pixels. This is equivalent to the
9307     * {@link #setTranslationX(float) translationX} property plus the current
9308     * {@link #getLeft() left} property.
9309     *
9310     * @return The visual x position of this view, in pixels.
9311     */
9312    @ViewDebug.ExportedProperty(category = "drawing")
9313    public float getX() {
9314        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9315    }
9316
9317    /**
9318     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9319     * {@link #setTranslationX(float) translationX} property to be the difference between
9320     * the x value passed in and the current {@link #getLeft() left} property.
9321     *
9322     * @param x The visual x position of this view, in pixels.
9323     */
9324    public void setX(float x) {
9325        setTranslationX(x - mLeft);
9326    }
9327
9328    /**
9329     * The visual y position of this view, in pixels. This is equivalent to the
9330     * {@link #setTranslationY(float) translationY} property plus the current
9331     * {@link #getTop() top} property.
9332     *
9333     * @return The visual y position of this view, in pixels.
9334     */
9335    @ViewDebug.ExportedProperty(category = "drawing")
9336    public float getY() {
9337        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9338    }
9339
9340    /**
9341     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9342     * {@link #setTranslationY(float) translationY} property to be the difference between
9343     * the y value passed in and the current {@link #getTop() top} property.
9344     *
9345     * @param y The visual y position of this view, in pixels.
9346     */
9347    public void setY(float y) {
9348        setTranslationY(y - mTop);
9349    }
9350
9351
9352    /**
9353     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9354     * This position is post-layout, in addition to wherever the object's
9355     * layout placed it.
9356     *
9357     * @return The horizontal position of this view relative to its left position, in pixels.
9358     */
9359    @ViewDebug.ExportedProperty(category = "drawing")
9360    public float getTranslationX() {
9361        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9362    }
9363
9364    /**
9365     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9366     * This effectively positions the object post-layout, in addition to wherever the object's
9367     * layout placed it.
9368     *
9369     * @param translationX The horizontal position of this view relative to its left position,
9370     * in pixels.
9371     *
9372     * @attr ref android.R.styleable#View_translationX
9373     */
9374    public void setTranslationX(float translationX) {
9375        ensureTransformationInfo();
9376        final TransformationInfo info = mTransformationInfo;
9377        if (info.mTranslationX != translationX) {
9378            // Double-invalidation is necessary to capture view's old and new areas
9379            invalidateViewProperty(true, false);
9380            info.mTranslationX = translationX;
9381            info.mMatrixDirty = true;
9382            invalidateViewProperty(false, true);
9383            if (mDisplayList != null) {
9384                mDisplayList.setTranslationX(translationX);
9385            }
9386            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9387                // View was rejected last time it was drawn by its parent; this may have changed
9388                invalidateParentIfNeeded();
9389            }
9390        }
9391    }
9392
9393    /**
9394     * The horizontal location of this view relative to its {@link #getTop() top} position.
9395     * This position is post-layout, in addition to wherever the object's
9396     * layout placed it.
9397     *
9398     * @return The vertical position of this view relative to its top position,
9399     * in pixels.
9400     */
9401    @ViewDebug.ExportedProperty(category = "drawing")
9402    public float getTranslationY() {
9403        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9404    }
9405
9406    /**
9407     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9408     * This effectively positions the object post-layout, in addition to wherever the object's
9409     * layout placed it.
9410     *
9411     * @param translationY The vertical position of this view relative to its top position,
9412     * in pixels.
9413     *
9414     * @attr ref android.R.styleable#View_translationY
9415     */
9416    public void setTranslationY(float translationY) {
9417        ensureTransformationInfo();
9418        final TransformationInfo info = mTransformationInfo;
9419        if (info.mTranslationY != translationY) {
9420            invalidateViewProperty(true, false);
9421            info.mTranslationY = translationY;
9422            info.mMatrixDirty = true;
9423            invalidateViewProperty(false, true);
9424            if (mDisplayList != null) {
9425                mDisplayList.setTranslationY(translationY);
9426            }
9427            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9428                // View was rejected last time it was drawn by its parent; this may have changed
9429                invalidateParentIfNeeded();
9430            }
9431        }
9432    }
9433
9434    /**
9435     * Hit rectangle in parent's coordinates
9436     *
9437     * @param outRect The hit rectangle of the view.
9438     */
9439    public void getHitRect(Rect outRect) {
9440        updateMatrix();
9441        final TransformationInfo info = mTransformationInfo;
9442        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9443            outRect.set(mLeft, mTop, mRight, mBottom);
9444        } else {
9445            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9446            tmpRect.set(-info.mPivotX, -info.mPivotY,
9447                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9448            info.mMatrix.mapRect(tmpRect);
9449            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9450                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9451        }
9452    }
9453
9454    /**
9455     * Determines whether the given point, in local coordinates is inside the view.
9456     */
9457    /*package*/ final boolean pointInView(float localX, float localY) {
9458        return localX >= 0 && localX < (mRight - mLeft)
9459                && localY >= 0 && localY < (mBottom - mTop);
9460    }
9461
9462    /**
9463     * Utility method to determine whether the given point, in local coordinates,
9464     * is inside the view, where the area of the view is expanded by the slop factor.
9465     * This method is called while processing touch-move events to determine if the event
9466     * is still within the view.
9467     */
9468    private boolean pointInView(float localX, float localY, float slop) {
9469        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9470                localY < ((mBottom - mTop) + slop);
9471    }
9472
9473    /**
9474     * When a view has focus and the user navigates away from it, the next view is searched for
9475     * starting from the rectangle filled in by this method.
9476     *
9477     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9478     * of the view.  However, if your view maintains some idea of internal selection,
9479     * such as a cursor, or a selected row or column, you should override this method and
9480     * fill in a more specific rectangle.
9481     *
9482     * @param r The rectangle to fill in, in this view's coordinates.
9483     */
9484    public void getFocusedRect(Rect r) {
9485        getDrawingRect(r);
9486    }
9487
9488    /**
9489     * If some part of this view is not clipped by any of its parents, then
9490     * return that area in r in global (root) coordinates. To convert r to local
9491     * coordinates (without taking possible View rotations into account), offset
9492     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9493     * If the view is completely clipped or translated out, return false.
9494     *
9495     * @param r If true is returned, r holds the global coordinates of the
9496     *        visible portion of this view.
9497     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9498     *        between this view and its root. globalOffet may be null.
9499     * @return true if r is non-empty (i.e. part of the view is visible at the
9500     *         root level.
9501     */
9502    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9503        int width = mRight - mLeft;
9504        int height = mBottom - mTop;
9505        if (width > 0 && height > 0) {
9506            r.set(0, 0, width, height);
9507            if (globalOffset != null) {
9508                globalOffset.set(-mScrollX, -mScrollY);
9509            }
9510            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9511        }
9512        return false;
9513    }
9514
9515    public final boolean getGlobalVisibleRect(Rect r) {
9516        return getGlobalVisibleRect(r, null);
9517    }
9518
9519    public final boolean getLocalVisibleRect(Rect r) {
9520        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9521        if (getGlobalVisibleRect(r, offset)) {
9522            r.offset(-offset.x, -offset.y); // make r local
9523            return true;
9524        }
9525        return false;
9526    }
9527
9528    /**
9529     * Offset this view's vertical location by the specified number of pixels.
9530     *
9531     * @param offset the number of pixels to offset the view by
9532     */
9533    public void offsetTopAndBottom(int offset) {
9534        if (offset != 0) {
9535            updateMatrix();
9536            final boolean matrixIsIdentity = mTransformationInfo == null
9537                    || mTransformationInfo.mMatrixIsIdentity;
9538            if (matrixIsIdentity) {
9539                if (mDisplayList != null) {
9540                    invalidateViewProperty(false, false);
9541                } else {
9542                    final ViewParent p = mParent;
9543                    if (p != null && mAttachInfo != null) {
9544                        final Rect r = mAttachInfo.mTmpInvalRect;
9545                        int minTop;
9546                        int maxBottom;
9547                        int yLoc;
9548                        if (offset < 0) {
9549                            minTop = mTop + offset;
9550                            maxBottom = mBottom;
9551                            yLoc = offset;
9552                        } else {
9553                            minTop = mTop;
9554                            maxBottom = mBottom + offset;
9555                            yLoc = 0;
9556                        }
9557                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9558                        p.invalidateChild(this, r);
9559                    }
9560                }
9561            } else {
9562                invalidateViewProperty(false, false);
9563            }
9564
9565            mTop += offset;
9566            mBottom += offset;
9567            if (mDisplayList != null) {
9568                mDisplayList.offsetTopBottom(offset);
9569                invalidateViewProperty(false, false);
9570            } else {
9571                if (!matrixIsIdentity) {
9572                    invalidateViewProperty(false, true);
9573                }
9574                invalidateParentIfNeeded();
9575            }
9576        }
9577    }
9578
9579    /**
9580     * Offset this view's horizontal location by the specified amount of pixels.
9581     *
9582     * @param offset the numer of pixels to offset the view by
9583     */
9584    public void offsetLeftAndRight(int offset) {
9585        if (offset != 0) {
9586            updateMatrix();
9587            final boolean matrixIsIdentity = mTransformationInfo == null
9588                    || mTransformationInfo.mMatrixIsIdentity;
9589            if (matrixIsIdentity) {
9590                if (mDisplayList != null) {
9591                    invalidateViewProperty(false, false);
9592                } else {
9593                    final ViewParent p = mParent;
9594                    if (p != null && mAttachInfo != null) {
9595                        final Rect r = mAttachInfo.mTmpInvalRect;
9596                        int minLeft;
9597                        int maxRight;
9598                        if (offset < 0) {
9599                            minLeft = mLeft + offset;
9600                            maxRight = mRight;
9601                        } else {
9602                            minLeft = mLeft;
9603                            maxRight = mRight + offset;
9604                        }
9605                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9606                        p.invalidateChild(this, r);
9607                    }
9608                }
9609            } else {
9610                invalidateViewProperty(false, false);
9611            }
9612
9613            mLeft += offset;
9614            mRight += offset;
9615            if (mDisplayList != null) {
9616                mDisplayList.offsetLeftRight(offset);
9617                invalidateViewProperty(false, false);
9618            } else {
9619                if (!matrixIsIdentity) {
9620                    invalidateViewProperty(false, true);
9621                }
9622                invalidateParentIfNeeded();
9623            }
9624        }
9625    }
9626
9627    /**
9628     * Get the LayoutParams associated with this view. All views should have
9629     * layout parameters. These supply parameters to the <i>parent</i> of this
9630     * view specifying how it should be arranged. There are many subclasses of
9631     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9632     * of ViewGroup that are responsible for arranging their children.
9633     *
9634     * This method may return null if this View is not attached to a parent
9635     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9636     * was not invoked successfully. When a View is attached to a parent
9637     * ViewGroup, this method must not return null.
9638     *
9639     * @return The LayoutParams associated with this view, or null if no
9640     *         parameters have been set yet
9641     */
9642    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9643    public ViewGroup.LayoutParams getLayoutParams() {
9644        return mLayoutParams;
9645    }
9646
9647    /**
9648     * Set the layout parameters associated with this view. These supply
9649     * parameters to the <i>parent</i> of this view specifying how it should be
9650     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9651     * correspond to the different subclasses of ViewGroup that are responsible
9652     * for arranging their children.
9653     *
9654     * @param params The layout parameters for this view, cannot be null
9655     */
9656    public void setLayoutParams(ViewGroup.LayoutParams params) {
9657        if (params == null) {
9658            throw new NullPointerException("Layout parameters cannot be null");
9659        }
9660        mLayoutParams = params;
9661        if (mParent instanceof ViewGroup) {
9662            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9663        }
9664        requestLayout();
9665    }
9666
9667    /**
9668     * Set the scrolled position of your view. This will cause a call to
9669     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9670     * invalidated.
9671     * @param x the x position to scroll to
9672     * @param y the y position to scroll to
9673     */
9674    public void scrollTo(int x, int y) {
9675        if (mScrollX != x || mScrollY != y) {
9676            int oldX = mScrollX;
9677            int oldY = mScrollY;
9678            mScrollX = x;
9679            mScrollY = y;
9680            invalidateParentCaches();
9681            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9682            if (!awakenScrollBars()) {
9683                postInvalidateOnAnimation();
9684            }
9685        }
9686    }
9687
9688    /**
9689     * Move the scrolled position of your view. This will cause a call to
9690     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9691     * invalidated.
9692     * @param x the amount of pixels to scroll by horizontally
9693     * @param y the amount of pixels to scroll by vertically
9694     */
9695    public void scrollBy(int x, int y) {
9696        scrollTo(mScrollX + x, mScrollY + y);
9697    }
9698
9699    /**
9700     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9701     * animation to fade the scrollbars out after a default delay. If a subclass
9702     * provides animated scrolling, the start delay should equal the duration
9703     * of the scrolling animation.</p>
9704     *
9705     * <p>The animation starts only if at least one of the scrollbars is
9706     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9707     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9708     * this method returns true, and false otherwise. If the animation is
9709     * started, this method calls {@link #invalidate()}; in that case the
9710     * caller should not call {@link #invalidate()}.</p>
9711     *
9712     * <p>This method should be invoked every time a subclass directly updates
9713     * the scroll parameters.</p>
9714     *
9715     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9716     * and {@link #scrollTo(int, int)}.</p>
9717     *
9718     * @return true if the animation is played, false otherwise
9719     *
9720     * @see #awakenScrollBars(int)
9721     * @see #scrollBy(int, int)
9722     * @see #scrollTo(int, int)
9723     * @see #isHorizontalScrollBarEnabled()
9724     * @see #isVerticalScrollBarEnabled()
9725     * @see #setHorizontalScrollBarEnabled(boolean)
9726     * @see #setVerticalScrollBarEnabled(boolean)
9727     */
9728    protected boolean awakenScrollBars() {
9729        return mScrollCache != null &&
9730                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9731    }
9732
9733    /**
9734     * Trigger the scrollbars to draw.
9735     * This method differs from awakenScrollBars() only in its default duration.
9736     * initialAwakenScrollBars() will show the scroll bars for longer than
9737     * usual to give the user more of a chance to notice them.
9738     *
9739     * @return true if the animation is played, false otherwise.
9740     */
9741    private boolean initialAwakenScrollBars() {
9742        return mScrollCache != null &&
9743                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9744    }
9745
9746    /**
9747     * <p>
9748     * Trigger the scrollbars to draw. When invoked this method starts an
9749     * animation to fade the scrollbars out after a fixed delay. If a subclass
9750     * provides animated scrolling, the start delay should equal the duration of
9751     * the scrolling animation.
9752     * </p>
9753     *
9754     * <p>
9755     * The animation starts only if at least one of the scrollbars is enabled,
9756     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9757     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9758     * this method returns true, and false otherwise. If the animation is
9759     * started, this method calls {@link #invalidate()}; in that case the caller
9760     * should not call {@link #invalidate()}.
9761     * </p>
9762     *
9763     * <p>
9764     * This method should be invoked everytime a subclass directly updates the
9765     * scroll parameters.
9766     * </p>
9767     *
9768     * @param startDelay the delay, in milliseconds, after which the animation
9769     *        should start; when the delay is 0, the animation starts
9770     *        immediately
9771     * @return true if the animation is played, false otherwise
9772     *
9773     * @see #scrollBy(int, int)
9774     * @see #scrollTo(int, int)
9775     * @see #isHorizontalScrollBarEnabled()
9776     * @see #isVerticalScrollBarEnabled()
9777     * @see #setHorizontalScrollBarEnabled(boolean)
9778     * @see #setVerticalScrollBarEnabled(boolean)
9779     */
9780    protected boolean awakenScrollBars(int startDelay) {
9781        return awakenScrollBars(startDelay, true);
9782    }
9783
9784    /**
9785     * <p>
9786     * Trigger the scrollbars to draw. When invoked this method starts an
9787     * animation to fade the scrollbars out after a fixed delay. If a subclass
9788     * provides animated scrolling, the start delay should equal the duration of
9789     * the scrolling animation.
9790     * </p>
9791     *
9792     * <p>
9793     * The animation starts only if at least one of the scrollbars is enabled,
9794     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9795     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9796     * this method returns true, and false otherwise. If the animation is
9797     * started, this method calls {@link #invalidate()} if the invalidate parameter
9798     * is set to true; in that case the caller
9799     * should not call {@link #invalidate()}.
9800     * </p>
9801     *
9802     * <p>
9803     * This method should be invoked everytime a subclass directly updates the
9804     * scroll parameters.
9805     * </p>
9806     *
9807     * @param startDelay the delay, in milliseconds, after which the animation
9808     *        should start; when the delay is 0, the animation starts
9809     *        immediately
9810     *
9811     * @param invalidate Wheter this method should call invalidate
9812     *
9813     * @return true if the animation is played, false otherwise
9814     *
9815     * @see #scrollBy(int, int)
9816     * @see #scrollTo(int, int)
9817     * @see #isHorizontalScrollBarEnabled()
9818     * @see #isVerticalScrollBarEnabled()
9819     * @see #setHorizontalScrollBarEnabled(boolean)
9820     * @see #setVerticalScrollBarEnabled(boolean)
9821     */
9822    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9823        final ScrollabilityCache scrollCache = mScrollCache;
9824
9825        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9826            return false;
9827        }
9828
9829        if (scrollCache.scrollBar == null) {
9830            scrollCache.scrollBar = new ScrollBarDrawable();
9831        }
9832
9833        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9834
9835            if (invalidate) {
9836                // Invalidate to show the scrollbars
9837                postInvalidateOnAnimation();
9838            }
9839
9840            if (scrollCache.state == ScrollabilityCache.OFF) {
9841                // FIXME: this is copied from WindowManagerService.
9842                // We should get this value from the system when it
9843                // is possible to do so.
9844                final int KEY_REPEAT_FIRST_DELAY = 750;
9845                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9846            }
9847
9848            // Tell mScrollCache when we should start fading. This may
9849            // extend the fade start time if one was already scheduled
9850            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9851            scrollCache.fadeStartTime = fadeStartTime;
9852            scrollCache.state = ScrollabilityCache.ON;
9853
9854            // Schedule our fader to run, unscheduling any old ones first
9855            if (mAttachInfo != null) {
9856                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9857                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9858            }
9859
9860            return true;
9861        }
9862
9863        return false;
9864    }
9865
9866    /**
9867     * Do not invalidate views which are not visible and which are not running an animation. They
9868     * will not get drawn and they should not set dirty flags as if they will be drawn
9869     */
9870    private boolean skipInvalidate() {
9871        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9872                (!(mParent instanceof ViewGroup) ||
9873                        !((ViewGroup) mParent).isViewTransitioning(this));
9874    }
9875    /**
9876     * Mark the area defined by dirty as needing to be drawn. If the view is
9877     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9878     * in the future. This must be called from a UI thread. To call from a non-UI
9879     * thread, call {@link #postInvalidate()}.
9880     *
9881     * WARNING: This method is destructive to dirty.
9882     * @param dirty the rectangle representing the bounds of the dirty region
9883     */
9884    public void invalidate(Rect dirty) {
9885        if (skipInvalidate()) {
9886            return;
9887        }
9888        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9889                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9890                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9891            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9892            mPrivateFlags |= INVALIDATED;
9893            mPrivateFlags |= DIRTY;
9894            final ViewParent p = mParent;
9895            final AttachInfo ai = mAttachInfo;
9896            //noinspection PointlessBooleanExpression,ConstantConditions
9897            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9898                if (p != null && ai != null && ai.mHardwareAccelerated) {
9899                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9900                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9901                    p.invalidateChild(this, null);
9902                    return;
9903                }
9904            }
9905            if (p != null && ai != null) {
9906                final int scrollX = mScrollX;
9907                final int scrollY = mScrollY;
9908                final Rect r = ai.mTmpInvalRect;
9909                r.set(dirty.left - scrollX, dirty.top - scrollY,
9910                        dirty.right - scrollX, dirty.bottom - scrollY);
9911                mParent.invalidateChild(this, r);
9912            }
9913        }
9914    }
9915
9916    /**
9917     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9918     * The coordinates of the dirty rect are relative to the view.
9919     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9920     * will be called at some point in the future. This must be called from
9921     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9922     * @param l the left position of the dirty region
9923     * @param t the top position of the dirty region
9924     * @param r the right position of the dirty region
9925     * @param b the bottom position of the dirty region
9926     */
9927    public void invalidate(int l, int t, int r, int b) {
9928        if (skipInvalidate()) {
9929            return;
9930        }
9931        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9932                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9933                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9934            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9935            mPrivateFlags |= INVALIDATED;
9936            mPrivateFlags |= DIRTY;
9937            final ViewParent p = mParent;
9938            final AttachInfo ai = mAttachInfo;
9939            //noinspection PointlessBooleanExpression,ConstantConditions
9940            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9941                if (p != null && ai != null && ai.mHardwareAccelerated) {
9942                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9943                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9944                    p.invalidateChild(this, null);
9945                    return;
9946                }
9947            }
9948            if (p != null && ai != null && l < r && t < b) {
9949                final int scrollX = mScrollX;
9950                final int scrollY = mScrollY;
9951                final Rect tmpr = ai.mTmpInvalRect;
9952                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9953                p.invalidateChild(this, tmpr);
9954            }
9955        }
9956    }
9957
9958    /**
9959     * Invalidate the whole view. If the view is visible,
9960     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9961     * the future. This must be called from a UI thread. To call from a non-UI thread,
9962     * call {@link #postInvalidate()}.
9963     */
9964    public void invalidate() {
9965        invalidate(true);
9966    }
9967
9968    /**
9969     * This is where the invalidate() work actually happens. A full invalidate()
9970     * causes the drawing cache to be invalidated, but this function can be called with
9971     * invalidateCache set to false to skip that invalidation step for cases that do not
9972     * need it (for example, a component that remains at the same dimensions with the same
9973     * content).
9974     *
9975     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9976     * well. This is usually true for a full invalidate, but may be set to false if the
9977     * View's contents or dimensions have not changed.
9978     */
9979    void invalidate(boolean invalidateCache) {
9980        if (skipInvalidate()) {
9981            return;
9982        }
9983        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9984                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9985                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9986            mLastIsOpaque = isOpaque();
9987            mPrivateFlags &= ~DRAWN;
9988            mPrivateFlags |= DIRTY;
9989            if (invalidateCache) {
9990                mPrivateFlags |= INVALIDATED;
9991                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9992            }
9993            final AttachInfo ai = mAttachInfo;
9994            final ViewParent p = mParent;
9995            //noinspection PointlessBooleanExpression,ConstantConditions
9996            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9997                if (p != null && ai != null && ai.mHardwareAccelerated) {
9998                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9999                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10000                    p.invalidateChild(this, null);
10001                    return;
10002                }
10003            }
10004
10005            if (p != null && ai != null) {
10006                final Rect r = ai.mTmpInvalRect;
10007                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10008                // Don't call invalidate -- we don't want to internally scroll
10009                // our own bounds
10010                p.invalidateChild(this, r);
10011            }
10012        }
10013    }
10014
10015    /**
10016     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10017     * set any flags or handle all of the cases handled by the default invalidation methods.
10018     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10019     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10020     * walk up the hierarchy, transforming the dirty rect as necessary.
10021     *
10022     * The method also handles normal invalidation logic if display list properties are not
10023     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10024     * backup approach, to handle these cases used in the various property-setting methods.
10025     *
10026     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10027     * are not being used in this view
10028     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10029     * list properties are not being used in this view
10030     */
10031    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10032        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10033            if (invalidateParent) {
10034                invalidateParentCaches();
10035            }
10036            if (forceRedraw) {
10037                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10038            }
10039            invalidate(false);
10040        } else {
10041            final AttachInfo ai = mAttachInfo;
10042            final ViewParent p = mParent;
10043            if (p != null && ai != null) {
10044                final Rect r = ai.mTmpInvalRect;
10045                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10046                if (mParent instanceof ViewGroup) {
10047                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10048                } else {
10049                    mParent.invalidateChild(this, r);
10050                }
10051            }
10052        }
10053    }
10054
10055    /**
10056     * Utility method to transform a given Rect by the current matrix of this view.
10057     */
10058    void transformRect(final Rect rect) {
10059        if (!getMatrix().isIdentity()) {
10060            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10061            boundingRect.set(rect);
10062            getMatrix().mapRect(boundingRect);
10063            rect.set((int) (boundingRect.left - 0.5f),
10064                    (int) (boundingRect.top - 0.5f),
10065                    (int) (boundingRect.right + 0.5f),
10066                    (int) (boundingRect.bottom + 0.5f));
10067        }
10068    }
10069
10070    /**
10071     * Used to indicate that the parent of this view should clear its caches. This functionality
10072     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10073     * which is necessary when various parent-managed properties of the view change, such as
10074     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10075     * clears the parent caches and does not causes an invalidate event.
10076     *
10077     * @hide
10078     */
10079    protected void invalidateParentCaches() {
10080        if (mParent instanceof View) {
10081            ((View) mParent).mPrivateFlags |= INVALIDATED;
10082        }
10083    }
10084
10085    /**
10086     * Used to indicate that the parent of this view should be invalidated. This functionality
10087     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10088     * which is necessary when various parent-managed properties of the view change, such as
10089     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10090     * an invalidation event to the parent.
10091     *
10092     * @hide
10093     */
10094    protected void invalidateParentIfNeeded() {
10095        if (isHardwareAccelerated() && mParent instanceof View) {
10096            ((View) mParent).invalidate(true);
10097        }
10098    }
10099
10100    /**
10101     * Indicates whether this View is opaque. An opaque View guarantees that it will
10102     * draw all the pixels overlapping its bounds using a fully opaque color.
10103     *
10104     * Subclasses of View should override this method whenever possible to indicate
10105     * whether an instance is opaque. Opaque Views are treated in a special way by
10106     * the View hierarchy, possibly allowing it to perform optimizations during
10107     * invalidate/draw passes.
10108     *
10109     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10110     */
10111    @ViewDebug.ExportedProperty(category = "drawing")
10112    public boolean isOpaque() {
10113        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10114                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10115                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10116    }
10117
10118    /**
10119     * @hide
10120     */
10121    protected void computeOpaqueFlags() {
10122        // Opaque if:
10123        //   - Has a background
10124        //   - Background is opaque
10125        //   - Doesn't have scrollbars or scrollbars are inside overlay
10126
10127        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10128            mPrivateFlags |= OPAQUE_BACKGROUND;
10129        } else {
10130            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10131        }
10132
10133        final int flags = mViewFlags;
10134        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10135                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10136            mPrivateFlags |= OPAQUE_SCROLLBARS;
10137        } else {
10138            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10139        }
10140    }
10141
10142    /**
10143     * @hide
10144     */
10145    protected boolean hasOpaqueScrollbars() {
10146        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10147    }
10148
10149    /**
10150     * @return A handler associated with the thread running the View. This
10151     * handler can be used to pump events in the UI events queue.
10152     */
10153    public Handler getHandler() {
10154        if (mAttachInfo != null) {
10155            return mAttachInfo.mHandler;
10156        }
10157        return null;
10158    }
10159
10160    /**
10161     * Gets the view root associated with the View.
10162     * @return The view root, or null if none.
10163     * @hide
10164     */
10165    public ViewRootImpl getViewRootImpl() {
10166        if (mAttachInfo != null) {
10167            return mAttachInfo.mViewRootImpl;
10168        }
10169        return null;
10170    }
10171
10172    /**
10173     * <p>Causes the Runnable to be added to the message queue.
10174     * The runnable will be run on the user interface thread.</p>
10175     *
10176     * <p>This method can be invoked from outside of the UI thread
10177     * only when this View is attached to a window.</p>
10178     *
10179     * @param action The Runnable that will be executed.
10180     *
10181     * @return Returns true if the Runnable was successfully placed in to the
10182     *         message queue.  Returns false on failure, usually because the
10183     *         looper processing the message queue is exiting.
10184     *
10185     * @see #postDelayed
10186     * @see #removeCallbacks
10187     */
10188    public boolean post(Runnable action) {
10189        final AttachInfo attachInfo = mAttachInfo;
10190        if (attachInfo != null) {
10191            return attachInfo.mHandler.post(action);
10192        }
10193        // Assume that post will succeed later
10194        ViewRootImpl.getRunQueue().post(action);
10195        return true;
10196    }
10197
10198    /**
10199     * <p>Causes the Runnable to be added to the message queue, to be run
10200     * after the specified amount of time elapses.
10201     * The runnable will be run on the user interface thread.</p>
10202     *
10203     * <p>This method can be invoked from outside of the UI thread
10204     * only when this View is attached to a window.</p>
10205     *
10206     * @param action The Runnable that will be executed.
10207     * @param delayMillis The delay (in milliseconds) until the Runnable
10208     *        will be executed.
10209     *
10210     * @return true if the Runnable was successfully placed in to the
10211     *         message queue.  Returns false on failure, usually because the
10212     *         looper processing the message queue is exiting.  Note that a
10213     *         result of true does not mean the Runnable will be processed --
10214     *         if the looper is quit before the delivery time of the message
10215     *         occurs then the message will be dropped.
10216     *
10217     * @see #post
10218     * @see #removeCallbacks
10219     */
10220    public boolean postDelayed(Runnable action, long delayMillis) {
10221        final AttachInfo attachInfo = mAttachInfo;
10222        if (attachInfo != null) {
10223            return attachInfo.mHandler.postDelayed(action, delayMillis);
10224        }
10225        // Assume that post will succeed later
10226        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10227        return true;
10228    }
10229
10230    /**
10231     * <p>Causes the Runnable to execute on the next animation time step.
10232     * The runnable will be run on the user interface thread.</p>
10233     *
10234     * <p>This method can be invoked from outside of the UI thread
10235     * only when this View is attached to a window.</p>
10236     *
10237     * @param action The Runnable that will be executed.
10238     *
10239     * @see #postOnAnimationDelayed
10240     * @see #removeCallbacks
10241     */
10242    public void postOnAnimation(Runnable action) {
10243        final AttachInfo attachInfo = mAttachInfo;
10244        if (attachInfo != null) {
10245            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10246                    Choreographer.CALLBACK_ANIMATION, action, null);
10247        } else {
10248            // Assume that post will succeed later
10249            ViewRootImpl.getRunQueue().post(action);
10250        }
10251    }
10252
10253    /**
10254     * <p>Causes the Runnable to execute on the next animation time step,
10255     * after the specified amount of time elapses.
10256     * The runnable will be run on the user interface thread.</p>
10257     *
10258     * <p>This method can be invoked from outside of the UI thread
10259     * only when this View is attached to a window.</p>
10260     *
10261     * @param action The Runnable that will be executed.
10262     * @param delayMillis The delay (in milliseconds) until the Runnable
10263     *        will be executed.
10264     *
10265     * @see #postOnAnimation
10266     * @see #removeCallbacks
10267     */
10268    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10269        final AttachInfo attachInfo = mAttachInfo;
10270        if (attachInfo != null) {
10271            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10272                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10273        } else {
10274            // Assume that post will succeed later
10275            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10276        }
10277    }
10278
10279    /**
10280     * <p>Removes the specified Runnable from the message queue.</p>
10281     *
10282     * <p>This method can be invoked from outside of the UI thread
10283     * only when this View is attached to a window.</p>
10284     *
10285     * @param action The Runnable to remove from the message handling queue
10286     *
10287     * @return true if this view could ask the Handler to remove the Runnable,
10288     *         false otherwise. When the returned value is true, the Runnable
10289     *         may or may not have been actually removed from the message queue
10290     *         (for instance, if the Runnable was not in the queue already.)
10291     *
10292     * @see #post
10293     * @see #postDelayed
10294     * @see #postOnAnimation
10295     * @see #postOnAnimationDelayed
10296     */
10297    public boolean removeCallbacks(Runnable action) {
10298        if (action != null) {
10299            final AttachInfo attachInfo = mAttachInfo;
10300            if (attachInfo != null) {
10301                attachInfo.mHandler.removeCallbacks(action);
10302                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10303                        Choreographer.CALLBACK_ANIMATION, action, null);
10304            } else {
10305                // Assume that post will succeed later
10306                ViewRootImpl.getRunQueue().removeCallbacks(action);
10307            }
10308        }
10309        return true;
10310    }
10311
10312    /**
10313     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10314     * Use this to invalidate the View from a non-UI thread.</p>
10315     *
10316     * <p>This method can be invoked from outside of the UI thread
10317     * only when this View is attached to a window.</p>
10318     *
10319     * @see #invalidate()
10320     * @see #postInvalidateDelayed(long)
10321     */
10322    public void postInvalidate() {
10323        postInvalidateDelayed(0);
10324    }
10325
10326    /**
10327     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10328     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10329     *
10330     * <p>This method can be invoked from outside of the UI thread
10331     * only when this View is attached to a window.</p>
10332     *
10333     * @param left The left coordinate of the rectangle to invalidate.
10334     * @param top The top coordinate of the rectangle to invalidate.
10335     * @param right The right coordinate of the rectangle to invalidate.
10336     * @param bottom The bottom coordinate of the rectangle to invalidate.
10337     *
10338     * @see #invalidate(int, int, int, int)
10339     * @see #invalidate(Rect)
10340     * @see #postInvalidateDelayed(long, int, int, int, int)
10341     */
10342    public void postInvalidate(int left, int top, int right, int bottom) {
10343        postInvalidateDelayed(0, left, top, right, bottom);
10344    }
10345
10346    /**
10347     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10348     * loop. Waits for the specified amount of time.</p>
10349     *
10350     * <p>This method can be invoked from outside of the UI thread
10351     * only when this View is attached to a window.</p>
10352     *
10353     * @param delayMilliseconds the duration in milliseconds to delay the
10354     *         invalidation by
10355     *
10356     * @see #invalidate()
10357     * @see #postInvalidate()
10358     */
10359    public void postInvalidateDelayed(long delayMilliseconds) {
10360        // We try only with the AttachInfo because there's no point in invalidating
10361        // if we are not attached to our window
10362        final AttachInfo attachInfo = mAttachInfo;
10363        if (attachInfo != null) {
10364            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10365        }
10366    }
10367
10368    /**
10369     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10370     * through the event loop. Waits for the specified amount of time.</p>
10371     *
10372     * <p>This method can be invoked from outside of the UI thread
10373     * only when this View is attached to a window.</p>
10374     *
10375     * @param delayMilliseconds the duration in milliseconds to delay the
10376     *         invalidation by
10377     * @param left The left coordinate of the rectangle to invalidate.
10378     * @param top The top coordinate of the rectangle to invalidate.
10379     * @param right The right coordinate of the rectangle to invalidate.
10380     * @param bottom The bottom coordinate of the rectangle to invalidate.
10381     *
10382     * @see #invalidate(int, int, int, int)
10383     * @see #invalidate(Rect)
10384     * @see #postInvalidate(int, int, int, int)
10385     */
10386    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10387            int right, int bottom) {
10388
10389        // We try only with the AttachInfo because there's no point in invalidating
10390        // if we are not attached to our window
10391        final AttachInfo attachInfo = mAttachInfo;
10392        if (attachInfo != null) {
10393            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10394            info.target = this;
10395            info.left = left;
10396            info.top = top;
10397            info.right = right;
10398            info.bottom = bottom;
10399
10400            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10401        }
10402    }
10403
10404    /**
10405     * <p>Cause an invalidate to happen on the next animation time step, typically the
10406     * next display frame.</p>
10407     *
10408     * <p>This method can be invoked from outside of the UI thread
10409     * only when this View is attached to a window.</p>
10410     *
10411     * @see #invalidate()
10412     */
10413    public void postInvalidateOnAnimation() {
10414        // We try only with the AttachInfo because there's no point in invalidating
10415        // if we are not attached to our window
10416        final AttachInfo attachInfo = mAttachInfo;
10417        if (attachInfo != null) {
10418            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10419        }
10420    }
10421
10422    /**
10423     * <p>Cause an invalidate of the specified area to happen on the next animation
10424     * time step, typically the next display frame.</p>
10425     *
10426     * <p>This method can be invoked from outside of the UI thread
10427     * only when this View is attached to a window.</p>
10428     *
10429     * @param left The left coordinate of the rectangle to invalidate.
10430     * @param top The top coordinate of the rectangle to invalidate.
10431     * @param right The right coordinate of the rectangle to invalidate.
10432     * @param bottom The bottom coordinate of the rectangle to invalidate.
10433     *
10434     * @see #invalidate(int, int, int, int)
10435     * @see #invalidate(Rect)
10436     */
10437    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10438        // We try only with the AttachInfo because there's no point in invalidating
10439        // if we are not attached to our window
10440        final AttachInfo attachInfo = mAttachInfo;
10441        if (attachInfo != null) {
10442            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10443            info.target = this;
10444            info.left = left;
10445            info.top = top;
10446            info.right = right;
10447            info.bottom = bottom;
10448
10449            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10450        }
10451    }
10452
10453    /**
10454     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10455     * This event is sent at most once every
10456     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10457     */
10458    private void postSendViewScrolledAccessibilityEventCallback() {
10459        if (mSendViewScrolledAccessibilityEvent == null) {
10460            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10461        }
10462        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10463            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10464            postDelayed(mSendViewScrolledAccessibilityEvent,
10465                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10466        }
10467    }
10468
10469    /**
10470     * Called by a parent to request that a child update its values for mScrollX
10471     * and mScrollY if necessary. This will typically be done if the child is
10472     * animating a scroll using a {@link android.widget.Scroller Scroller}
10473     * object.
10474     */
10475    public void computeScroll() {
10476    }
10477
10478    /**
10479     * <p>Indicate whether the horizontal edges are faded when the view is
10480     * scrolled horizontally.</p>
10481     *
10482     * @return true if the horizontal edges should are faded on scroll, false
10483     *         otherwise
10484     *
10485     * @see #setHorizontalFadingEdgeEnabled(boolean)
10486     *
10487     * @attr ref android.R.styleable#View_requiresFadingEdge
10488     */
10489    public boolean isHorizontalFadingEdgeEnabled() {
10490        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10491    }
10492
10493    /**
10494     * <p>Define whether the horizontal edges should be faded when this view
10495     * is scrolled horizontally.</p>
10496     *
10497     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10498     *                                    be faded when the view is scrolled
10499     *                                    horizontally
10500     *
10501     * @see #isHorizontalFadingEdgeEnabled()
10502     *
10503     * @attr ref android.R.styleable#View_requiresFadingEdge
10504     */
10505    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10506        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10507            if (horizontalFadingEdgeEnabled) {
10508                initScrollCache();
10509            }
10510
10511            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10512        }
10513    }
10514
10515    /**
10516     * <p>Indicate whether the vertical edges are faded when the view is
10517     * scrolled horizontally.</p>
10518     *
10519     * @return true if the vertical edges should are faded on scroll, false
10520     *         otherwise
10521     *
10522     * @see #setVerticalFadingEdgeEnabled(boolean)
10523     *
10524     * @attr ref android.R.styleable#View_requiresFadingEdge
10525     */
10526    public boolean isVerticalFadingEdgeEnabled() {
10527        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10528    }
10529
10530    /**
10531     * <p>Define whether the vertical edges should be faded when this view
10532     * is scrolled vertically.</p>
10533     *
10534     * @param verticalFadingEdgeEnabled true if the vertical edges should
10535     *                                  be faded when the view is scrolled
10536     *                                  vertically
10537     *
10538     * @see #isVerticalFadingEdgeEnabled()
10539     *
10540     * @attr ref android.R.styleable#View_requiresFadingEdge
10541     */
10542    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10543        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10544            if (verticalFadingEdgeEnabled) {
10545                initScrollCache();
10546            }
10547
10548            mViewFlags ^= FADING_EDGE_VERTICAL;
10549        }
10550    }
10551
10552    /**
10553     * Returns the strength, or intensity, of the top faded edge. The strength is
10554     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10555     * returns 0.0 or 1.0 but no value in between.
10556     *
10557     * Subclasses should override this method to provide a smoother fade transition
10558     * when scrolling occurs.
10559     *
10560     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10561     */
10562    protected float getTopFadingEdgeStrength() {
10563        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10564    }
10565
10566    /**
10567     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10568     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10569     * returns 0.0 or 1.0 but no value in between.
10570     *
10571     * Subclasses should override this method to provide a smoother fade transition
10572     * when scrolling occurs.
10573     *
10574     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10575     */
10576    protected float getBottomFadingEdgeStrength() {
10577        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10578                computeVerticalScrollRange() ? 1.0f : 0.0f;
10579    }
10580
10581    /**
10582     * Returns the strength, or intensity, of the left faded edge. The strength is
10583     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10584     * returns 0.0 or 1.0 but no value in between.
10585     *
10586     * Subclasses should override this method to provide a smoother fade transition
10587     * when scrolling occurs.
10588     *
10589     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10590     */
10591    protected float getLeftFadingEdgeStrength() {
10592        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10593    }
10594
10595    /**
10596     * Returns the strength, or intensity, of the right faded edge. The strength is
10597     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10598     * returns 0.0 or 1.0 but no value in between.
10599     *
10600     * Subclasses should override this method to provide a smoother fade transition
10601     * when scrolling occurs.
10602     *
10603     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10604     */
10605    protected float getRightFadingEdgeStrength() {
10606        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10607                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10608    }
10609
10610    /**
10611     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10612     * scrollbar is not drawn by default.</p>
10613     *
10614     * @return true if the horizontal scrollbar should be painted, false
10615     *         otherwise
10616     *
10617     * @see #setHorizontalScrollBarEnabled(boolean)
10618     */
10619    public boolean isHorizontalScrollBarEnabled() {
10620        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10621    }
10622
10623    /**
10624     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10625     * scrollbar is not drawn by default.</p>
10626     *
10627     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10628     *                                   be painted
10629     *
10630     * @see #isHorizontalScrollBarEnabled()
10631     */
10632    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10633        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10634            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10635            computeOpaqueFlags();
10636            resolvePadding();
10637        }
10638    }
10639
10640    /**
10641     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10642     * scrollbar is not drawn by default.</p>
10643     *
10644     * @return true if the vertical scrollbar should be painted, false
10645     *         otherwise
10646     *
10647     * @see #setVerticalScrollBarEnabled(boolean)
10648     */
10649    public boolean isVerticalScrollBarEnabled() {
10650        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10651    }
10652
10653    /**
10654     * <p>Define whether the vertical scrollbar should be drawn or not. The
10655     * scrollbar is not drawn by default.</p>
10656     *
10657     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10658     *                                 be painted
10659     *
10660     * @see #isVerticalScrollBarEnabled()
10661     */
10662    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10663        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10664            mViewFlags ^= SCROLLBARS_VERTICAL;
10665            computeOpaqueFlags();
10666            resolvePadding();
10667        }
10668    }
10669
10670    /**
10671     * @hide
10672     */
10673    protected void recomputePadding() {
10674        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10675    }
10676
10677    /**
10678     * Define whether scrollbars will fade when the view is not scrolling.
10679     *
10680     * @param fadeScrollbars wheter to enable fading
10681     *
10682     * @attr ref android.R.styleable#View_fadeScrollbars
10683     */
10684    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10685        initScrollCache();
10686        final ScrollabilityCache scrollabilityCache = mScrollCache;
10687        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10688        if (fadeScrollbars) {
10689            scrollabilityCache.state = ScrollabilityCache.OFF;
10690        } else {
10691            scrollabilityCache.state = ScrollabilityCache.ON;
10692        }
10693    }
10694
10695    /**
10696     *
10697     * Returns true if scrollbars will fade when this view is not scrolling
10698     *
10699     * @return true if scrollbar fading is enabled
10700     *
10701     * @attr ref android.R.styleable#View_fadeScrollbars
10702     */
10703    public boolean isScrollbarFadingEnabled() {
10704        return mScrollCache != null && mScrollCache.fadeScrollBars;
10705    }
10706
10707    /**
10708     *
10709     * Returns the delay before scrollbars fade.
10710     *
10711     * @return the delay before scrollbars fade
10712     *
10713     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10714     */
10715    public int getScrollBarDefaultDelayBeforeFade() {
10716        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10717                mScrollCache.scrollBarDefaultDelayBeforeFade;
10718    }
10719
10720    /**
10721     * Define the delay before scrollbars fade.
10722     *
10723     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10724     *
10725     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10726     */
10727    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10728        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10729    }
10730
10731    /**
10732     *
10733     * Returns the scrollbar fade duration.
10734     *
10735     * @return the scrollbar fade duration
10736     *
10737     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10738     */
10739    public int getScrollBarFadeDuration() {
10740        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10741                mScrollCache.scrollBarFadeDuration;
10742    }
10743
10744    /**
10745     * Define the scrollbar fade duration.
10746     *
10747     * @param scrollBarFadeDuration - the scrollbar fade duration
10748     *
10749     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10750     */
10751    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10752        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10753    }
10754
10755    /**
10756     *
10757     * Returns the scrollbar size.
10758     *
10759     * @return the scrollbar size
10760     *
10761     * @attr ref android.R.styleable#View_scrollbarSize
10762     */
10763    public int getScrollBarSize() {
10764        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10765                mScrollCache.scrollBarSize;
10766    }
10767
10768    /**
10769     * Define the scrollbar size.
10770     *
10771     * @param scrollBarSize - the scrollbar size
10772     *
10773     * @attr ref android.R.styleable#View_scrollbarSize
10774     */
10775    public void setScrollBarSize(int scrollBarSize) {
10776        getScrollCache().scrollBarSize = scrollBarSize;
10777    }
10778
10779    /**
10780     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10781     * inset. When inset, they add to the padding of the view. And the scrollbars
10782     * can be drawn inside the padding area or on the edge of the view. For example,
10783     * if a view has a background drawable and you want to draw the scrollbars
10784     * inside the padding specified by the drawable, you can use
10785     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10786     * appear at the edge of the view, ignoring the padding, then you can use
10787     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10788     * @param style the style of the scrollbars. Should be one of
10789     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10790     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10791     * @see #SCROLLBARS_INSIDE_OVERLAY
10792     * @see #SCROLLBARS_INSIDE_INSET
10793     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10794     * @see #SCROLLBARS_OUTSIDE_INSET
10795     *
10796     * @attr ref android.R.styleable#View_scrollbarStyle
10797     */
10798    public void setScrollBarStyle(int style) {
10799        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10800            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10801            computeOpaqueFlags();
10802            resolvePadding();
10803        }
10804    }
10805
10806    /**
10807     * <p>Returns the current scrollbar style.</p>
10808     * @return the current scrollbar style
10809     * @see #SCROLLBARS_INSIDE_OVERLAY
10810     * @see #SCROLLBARS_INSIDE_INSET
10811     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10812     * @see #SCROLLBARS_OUTSIDE_INSET
10813     *
10814     * @attr ref android.R.styleable#View_scrollbarStyle
10815     */
10816    @ViewDebug.ExportedProperty(mapping = {
10817            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10818            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10819            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10820            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10821    })
10822    public int getScrollBarStyle() {
10823        return mViewFlags & SCROLLBARS_STYLE_MASK;
10824    }
10825
10826    /**
10827     * <p>Compute the horizontal range that the horizontal scrollbar
10828     * represents.</p>
10829     *
10830     * <p>The range is expressed in arbitrary units that must be the same as the
10831     * units used by {@link #computeHorizontalScrollExtent()} and
10832     * {@link #computeHorizontalScrollOffset()}.</p>
10833     *
10834     * <p>The default range is the drawing width of this view.</p>
10835     *
10836     * @return the total horizontal range represented by the horizontal
10837     *         scrollbar
10838     *
10839     * @see #computeHorizontalScrollExtent()
10840     * @see #computeHorizontalScrollOffset()
10841     * @see android.widget.ScrollBarDrawable
10842     */
10843    protected int computeHorizontalScrollRange() {
10844        return getWidth();
10845    }
10846
10847    /**
10848     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10849     * within the horizontal range. This value is used to compute the position
10850     * of the thumb within the scrollbar's track.</p>
10851     *
10852     * <p>The range is expressed in arbitrary units that must be the same as the
10853     * units used by {@link #computeHorizontalScrollRange()} and
10854     * {@link #computeHorizontalScrollExtent()}.</p>
10855     *
10856     * <p>The default offset is the scroll offset of this view.</p>
10857     *
10858     * @return the horizontal offset of the scrollbar's thumb
10859     *
10860     * @see #computeHorizontalScrollRange()
10861     * @see #computeHorizontalScrollExtent()
10862     * @see android.widget.ScrollBarDrawable
10863     */
10864    protected int computeHorizontalScrollOffset() {
10865        return mScrollX;
10866    }
10867
10868    /**
10869     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10870     * within the horizontal range. This value is used to compute the length
10871     * of the thumb within the scrollbar's track.</p>
10872     *
10873     * <p>The range is expressed in arbitrary units that must be the same as the
10874     * units used by {@link #computeHorizontalScrollRange()} and
10875     * {@link #computeHorizontalScrollOffset()}.</p>
10876     *
10877     * <p>The default extent is the drawing width of this view.</p>
10878     *
10879     * @return the horizontal extent of the scrollbar's thumb
10880     *
10881     * @see #computeHorizontalScrollRange()
10882     * @see #computeHorizontalScrollOffset()
10883     * @see android.widget.ScrollBarDrawable
10884     */
10885    protected int computeHorizontalScrollExtent() {
10886        return getWidth();
10887    }
10888
10889    /**
10890     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10891     *
10892     * <p>The range is expressed in arbitrary units that must be the same as the
10893     * units used by {@link #computeVerticalScrollExtent()} and
10894     * {@link #computeVerticalScrollOffset()}.</p>
10895     *
10896     * @return the total vertical range represented by the vertical scrollbar
10897     *
10898     * <p>The default range is the drawing height of this view.</p>
10899     *
10900     * @see #computeVerticalScrollExtent()
10901     * @see #computeVerticalScrollOffset()
10902     * @see android.widget.ScrollBarDrawable
10903     */
10904    protected int computeVerticalScrollRange() {
10905        return getHeight();
10906    }
10907
10908    /**
10909     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10910     * within the horizontal range. This value is used to compute the position
10911     * of the thumb within the scrollbar's track.</p>
10912     *
10913     * <p>The range is expressed in arbitrary units that must be the same as the
10914     * units used by {@link #computeVerticalScrollRange()} and
10915     * {@link #computeVerticalScrollExtent()}.</p>
10916     *
10917     * <p>The default offset is the scroll offset of this view.</p>
10918     *
10919     * @return the vertical offset of the scrollbar's thumb
10920     *
10921     * @see #computeVerticalScrollRange()
10922     * @see #computeVerticalScrollExtent()
10923     * @see android.widget.ScrollBarDrawable
10924     */
10925    protected int computeVerticalScrollOffset() {
10926        return mScrollY;
10927    }
10928
10929    /**
10930     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10931     * within the vertical range. This value is used to compute the length
10932     * of the thumb within the scrollbar's track.</p>
10933     *
10934     * <p>The range is expressed in arbitrary units that must be the same as the
10935     * units used by {@link #computeVerticalScrollRange()} and
10936     * {@link #computeVerticalScrollOffset()}.</p>
10937     *
10938     * <p>The default extent is the drawing height of this view.</p>
10939     *
10940     * @return the vertical extent of the scrollbar's thumb
10941     *
10942     * @see #computeVerticalScrollRange()
10943     * @see #computeVerticalScrollOffset()
10944     * @see android.widget.ScrollBarDrawable
10945     */
10946    protected int computeVerticalScrollExtent() {
10947        return getHeight();
10948    }
10949
10950    /**
10951     * Check if this view can be scrolled horizontally in a certain direction.
10952     *
10953     * @param direction Negative to check scrolling left, positive to check scrolling right.
10954     * @return true if this view can be scrolled in the specified direction, false otherwise.
10955     */
10956    public boolean canScrollHorizontally(int direction) {
10957        final int offset = computeHorizontalScrollOffset();
10958        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10959        if (range == 0) return false;
10960        if (direction < 0) {
10961            return offset > 0;
10962        } else {
10963            return offset < range - 1;
10964        }
10965    }
10966
10967    /**
10968     * Check if this view can be scrolled vertically in a certain direction.
10969     *
10970     * @param direction Negative to check scrolling up, positive to check scrolling down.
10971     * @return true if this view can be scrolled in the specified direction, false otherwise.
10972     */
10973    public boolean canScrollVertically(int direction) {
10974        final int offset = computeVerticalScrollOffset();
10975        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10976        if (range == 0) return false;
10977        if (direction < 0) {
10978            return offset > 0;
10979        } else {
10980            return offset < range - 1;
10981        }
10982    }
10983
10984    /**
10985     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10986     * scrollbars are painted only if they have been awakened first.</p>
10987     *
10988     * @param canvas the canvas on which to draw the scrollbars
10989     *
10990     * @see #awakenScrollBars(int)
10991     */
10992    protected final void onDrawScrollBars(Canvas canvas) {
10993        // scrollbars are drawn only when the animation is running
10994        final ScrollabilityCache cache = mScrollCache;
10995        if (cache != null) {
10996
10997            int state = cache.state;
10998
10999            if (state == ScrollabilityCache.OFF) {
11000                return;
11001            }
11002
11003            boolean invalidate = false;
11004
11005            if (state == ScrollabilityCache.FADING) {
11006                // We're fading -- get our fade interpolation
11007                if (cache.interpolatorValues == null) {
11008                    cache.interpolatorValues = new float[1];
11009                }
11010
11011                float[] values = cache.interpolatorValues;
11012
11013                // Stops the animation if we're done
11014                if (cache.scrollBarInterpolator.timeToValues(values) ==
11015                        Interpolator.Result.FREEZE_END) {
11016                    cache.state = ScrollabilityCache.OFF;
11017                } else {
11018                    cache.scrollBar.setAlpha(Math.round(values[0]));
11019                }
11020
11021                // This will make the scroll bars inval themselves after
11022                // drawing. We only want this when we're fading so that
11023                // we prevent excessive redraws
11024                invalidate = true;
11025            } else {
11026                // We're just on -- but we may have been fading before so
11027                // reset alpha
11028                cache.scrollBar.setAlpha(255);
11029            }
11030
11031
11032            final int viewFlags = mViewFlags;
11033
11034            final boolean drawHorizontalScrollBar =
11035                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11036            final boolean drawVerticalScrollBar =
11037                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11038                && !isVerticalScrollBarHidden();
11039
11040            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11041                final int width = mRight - mLeft;
11042                final int height = mBottom - mTop;
11043
11044                final ScrollBarDrawable scrollBar = cache.scrollBar;
11045
11046                final int scrollX = mScrollX;
11047                final int scrollY = mScrollY;
11048                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11049
11050                int left, top, right, bottom;
11051
11052                if (drawHorizontalScrollBar) {
11053                    int size = scrollBar.getSize(false);
11054                    if (size <= 0) {
11055                        size = cache.scrollBarSize;
11056                    }
11057
11058                    scrollBar.setParameters(computeHorizontalScrollRange(),
11059                                            computeHorizontalScrollOffset(),
11060                                            computeHorizontalScrollExtent(), false);
11061                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11062                            getVerticalScrollbarWidth() : 0;
11063                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11064                    left = scrollX + (mPaddingLeft & inside);
11065                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11066                    bottom = top + size;
11067                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11068                    if (invalidate) {
11069                        invalidate(left, top, right, bottom);
11070                    }
11071                }
11072
11073                if (drawVerticalScrollBar) {
11074                    int size = scrollBar.getSize(true);
11075                    if (size <= 0) {
11076                        size = cache.scrollBarSize;
11077                    }
11078
11079                    scrollBar.setParameters(computeVerticalScrollRange(),
11080                                            computeVerticalScrollOffset(),
11081                                            computeVerticalScrollExtent(), true);
11082                    switch (mVerticalScrollbarPosition) {
11083                        default:
11084                        case SCROLLBAR_POSITION_DEFAULT:
11085                        case SCROLLBAR_POSITION_RIGHT:
11086                            left = scrollX + width - size - (mUserPaddingRight & inside);
11087                            break;
11088                        case SCROLLBAR_POSITION_LEFT:
11089                            left = scrollX + (mUserPaddingLeft & inside);
11090                            break;
11091                    }
11092                    top = scrollY + (mPaddingTop & inside);
11093                    right = left + size;
11094                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11095                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11096                    if (invalidate) {
11097                        invalidate(left, top, right, bottom);
11098                    }
11099                }
11100            }
11101        }
11102    }
11103
11104    /**
11105     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11106     * FastScroller is visible.
11107     * @return whether to temporarily hide the vertical scrollbar
11108     * @hide
11109     */
11110    protected boolean isVerticalScrollBarHidden() {
11111        return false;
11112    }
11113
11114    /**
11115     * <p>Draw the horizontal scrollbar if
11116     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11117     *
11118     * @param canvas the canvas on which to draw the scrollbar
11119     * @param scrollBar the scrollbar's drawable
11120     *
11121     * @see #isHorizontalScrollBarEnabled()
11122     * @see #computeHorizontalScrollRange()
11123     * @see #computeHorizontalScrollExtent()
11124     * @see #computeHorizontalScrollOffset()
11125     * @see android.widget.ScrollBarDrawable
11126     * @hide
11127     */
11128    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11129            int l, int t, int r, int b) {
11130        scrollBar.setBounds(l, t, r, b);
11131        scrollBar.draw(canvas);
11132    }
11133
11134    /**
11135     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11136     * returns true.</p>
11137     *
11138     * @param canvas the canvas on which to draw the scrollbar
11139     * @param scrollBar the scrollbar's drawable
11140     *
11141     * @see #isVerticalScrollBarEnabled()
11142     * @see #computeVerticalScrollRange()
11143     * @see #computeVerticalScrollExtent()
11144     * @see #computeVerticalScrollOffset()
11145     * @see android.widget.ScrollBarDrawable
11146     * @hide
11147     */
11148    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11149            int l, int t, int r, int b) {
11150        scrollBar.setBounds(l, t, r, b);
11151        scrollBar.draw(canvas);
11152    }
11153
11154    /**
11155     * Implement this to do your drawing.
11156     *
11157     * @param canvas the canvas on which the background will be drawn
11158     */
11159    protected void onDraw(Canvas canvas) {
11160    }
11161
11162    /*
11163     * Caller is responsible for calling requestLayout if necessary.
11164     * (This allows addViewInLayout to not request a new layout.)
11165     */
11166    void assignParent(ViewParent parent) {
11167        if (mParent == null) {
11168            mParent = parent;
11169        } else if (parent == null) {
11170            mParent = null;
11171        } else {
11172            throw new RuntimeException("view " + this + " being added, but"
11173                    + " it already has a parent");
11174        }
11175    }
11176
11177    /**
11178     * This is called when the view is attached to a window.  At this point it
11179     * has a Surface and will start drawing.  Note that this function is
11180     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11181     * however it may be called any time before the first onDraw -- including
11182     * before or after {@link #onMeasure(int, int)}.
11183     *
11184     * @see #onDetachedFromWindow()
11185     */
11186    protected void onAttachedToWindow() {
11187        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11188            mParent.requestTransparentRegion(this);
11189        }
11190
11191        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11192            initialAwakenScrollBars();
11193            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11194        }
11195
11196        jumpDrawablesToCurrentState();
11197
11198        // Order is important here: LayoutDirection MUST be resolved before Padding
11199        // and TextDirection
11200        resolveLayoutDirection();
11201        resolvePadding();
11202        resolveTextDirection();
11203        resolveTextAlignment();
11204
11205        clearAccessibilityFocus();
11206        if (isFocused()) {
11207            InputMethodManager imm = InputMethodManager.peekInstance();
11208            imm.focusIn(this);
11209        }
11210
11211        if (mAttachInfo != null && mDisplayList != null) {
11212            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11213        }
11214    }
11215
11216    /**
11217     * @see #onScreenStateChanged(int)
11218     */
11219    void dispatchScreenStateChanged(int screenState) {
11220        onScreenStateChanged(screenState);
11221    }
11222
11223    /**
11224     * This method is called whenever the state of the screen this view is
11225     * attached to changes. A state change will usually occurs when the screen
11226     * turns on or off (whether it happens automatically or the user does it
11227     * manually.)
11228     *
11229     * @param screenState The new state of the screen. Can be either
11230     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11231     */
11232    public void onScreenStateChanged(int screenState) {
11233    }
11234
11235    /**
11236     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11237     */
11238    private boolean hasRtlSupport() {
11239        return mContext.getApplicationInfo().hasRtlSupport();
11240    }
11241
11242    /**
11243     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11244     * that the parent directionality can and will be resolved before its children.
11245     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11246     */
11247    public void resolveLayoutDirection() {
11248        // Clear any previous layout direction resolution
11249        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11250
11251        if (hasRtlSupport()) {
11252            // Set resolved depending on layout direction
11253            switch (getLayoutDirection()) {
11254                case LAYOUT_DIRECTION_INHERIT:
11255                    // If this is root view, no need to look at parent's layout dir.
11256                    if (canResolveLayoutDirection()) {
11257                        ViewGroup viewGroup = ((ViewGroup) mParent);
11258
11259                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11260                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11261                        }
11262                    } else {
11263                        // Nothing to do, LTR by default
11264                    }
11265                    break;
11266                case LAYOUT_DIRECTION_RTL:
11267                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11268                    break;
11269                case LAYOUT_DIRECTION_LOCALE:
11270                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11271                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11272                    }
11273                    break;
11274                default:
11275                    // Nothing to do, LTR by default
11276            }
11277        }
11278
11279        // Set to resolved
11280        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11281        onResolvedLayoutDirectionChanged();
11282        // Resolve padding
11283        resolvePadding();
11284    }
11285
11286    /**
11287     * Called when layout direction has been resolved.
11288     *
11289     * The default implementation does nothing.
11290     */
11291    public void onResolvedLayoutDirectionChanged() {
11292    }
11293
11294    /**
11295     * Resolve padding depending on layout direction.
11296     */
11297    public void resolvePadding() {
11298        // If the user specified the absolute padding (either with android:padding or
11299        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11300        // use the default padding or the padding from the background drawable
11301        // (stored at this point in mPadding*)
11302        int resolvedLayoutDirection = getResolvedLayoutDirection();
11303        switch (resolvedLayoutDirection) {
11304            case LAYOUT_DIRECTION_RTL:
11305                // Start user padding override Right user padding. Otherwise, if Right user
11306                // padding is not defined, use the default Right padding. If Right user padding
11307                // is defined, just use it.
11308                if (mUserPaddingStart >= 0) {
11309                    mUserPaddingRight = mUserPaddingStart;
11310                } else if (mUserPaddingRight < 0) {
11311                    mUserPaddingRight = mPaddingRight;
11312                }
11313                if (mUserPaddingEnd >= 0) {
11314                    mUserPaddingLeft = mUserPaddingEnd;
11315                } else if (mUserPaddingLeft < 0) {
11316                    mUserPaddingLeft = mPaddingLeft;
11317                }
11318                break;
11319            case LAYOUT_DIRECTION_LTR:
11320            default:
11321                // Start user padding override Left user padding. Otherwise, if Left user
11322                // padding is not defined, use the default left padding. If Left user padding
11323                // is defined, just use it.
11324                if (mUserPaddingStart >= 0) {
11325                    mUserPaddingLeft = mUserPaddingStart;
11326                } else if (mUserPaddingLeft < 0) {
11327                    mUserPaddingLeft = mPaddingLeft;
11328                }
11329                if (mUserPaddingEnd >= 0) {
11330                    mUserPaddingRight = mUserPaddingEnd;
11331                } else if (mUserPaddingRight < 0) {
11332                    mUserPaddingRight = mPaddingRight;
11333                }
11334        }
11335
11336        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11337
11338        if(isPaddingRelative()) {
11339            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11340        } else {
11341            recomputePadding();
11342        }
11343        onPaddingChanged(resolvedLayoutDirection);
11344    }
11345
11346    /**
11347     * Resolve padding depending on the layout direction. Subclasses that care about
11348     * padding resolution should override this method. The default implementation does
11349     * nothing.
11350     *
11351     * @param layoutDirection the direction of the layout
11352     *
11353     * @see {@link #LAYOUT_DIRECTION_LTR}
11354     * @see {@link #LAYOUT_DIRECTION_RTL}
11355     */
11356    public void onPaddingChanged(int layoutDirection) {
11357    }
11358
11359    /**
11360     * Check if layout direction resolution can be done.
11361     *
11362     * @return true if layout direction resolution can be done otherwise return false.
11363     */
11364    public boolean canResolveLayoutDirection() {
11365        switch (getLayoutDirection()) {
11366            case LAYOUT_DIRECTION_INHERIT:
11367                return (mParent != null) && (mParent instanceof ViewGroup);
11368            default:
11369                return true;
11370        }
11371    }
11372
11373    /**
11374     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11375     * when reset is done.
11376     */
11377    public void resetResolvedLayoutDirection() {
11378        // Reset the current resolved bits
11379        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11380        onResolvedLayoutDirectionReset();
11381        // Reset also the text direction
11382        resetResolvedTextDirection();
11383    }
11384
11385    /**
11386     * Called during reset of resolved layout direction.
11387     *
11388     * Subclasses need to override this method to clear cached information that depends on the
11389     * resolved layout direction, or to inform child views that inherit their layout direction.
11390     *
11391     * The default implementation does nothing.
11392     */
11393    public void onResolvedLayoutDirectionReset() {
11394    }
11395
11396    /**
11397     * Check if a Locale uses an RTL script.
11398     *
11399     * @param locale Locale to check
11400     * @return true if the Locale uses an RTL script.
11401     */
11402    protected static boolean isLayoutDirectionRtl(Locale locale) {
11403        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11404    }
11405
11406    /**
11407     * This is called when the view is detached from a window.  At this point it
11408     * no longer has a surface for drawing.
11409     *
11410     * @see #onAttachedToWindow()
11411     */
11412    protected void onDetachedFromWindow() {
11413        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11414
11415        removeUnsetPressCallback();
11416        removeLongPressCallback();
11417        removePerformClickCallback();
11418        removeSendViewScrolledAccessibilityEventCallback();
11419
11420        destroyDrawingCache();
11421
11422        destroyLayer(false);
11423
11424        if (mAttachInfo != null) {
11425            if (mDisplayList != null) {
11426                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11427            }
11428            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11429        } else {
11430            if (mDisplayList != null) {
11431                // Should never happen
11432                mDisplayList.invalidate();
11433            }
11434        }
11435
11436        mCurrentAnimation = null;
11437
11438        resetResolvedLayoutDirection();
11439        resetResolvedTextAlignment();
11440        resetAccessibilityStateChanged();
11441    }
11442
11443    /**
11444     * @return The number of times this view has been attached to a window
11445     */
11446    protected int getWindowAttachCount() {
11447        return mWindowAttachCount;
11448    }
11449
11450    /**
11451     * Retrieve a unique token identifying the window this view is attached to.
11452     * @return Return the window's token for use in
11453     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11454     */
11455    public IBinder getWindowToken() {
11456        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11457    }
11458
11459    /**
11460     * Retrieve a unique token identifying the top-level "real" window of
11461     * the window that this view is attached to.  That is, this is like
11462     * {@link #getWindowToken}, except if the window this view in is a panel
11463     * window (attached to another containing window), then the token of
11464     * the containing window is returned instead.
11465     *
11466     * @return Returns the associated window token, either
11467     * {@link #getWindowToken()} or the containing window's token.
11468     */
11469    public IBinder getApplicationWindowToken() {
11470        AttachInfo ai = mAttachInfo;
11471        if (ai != null) {
11472            IBinder appWindowToken = ai.mPanelParentWindowToken;
11473            if (appWindowToken == null) {
11474                appWindowToken = ai.mWindowToken;
11475            }
11476            return appWindowToken;
11477        }
11478        return null;
11479    }
11480
11481    /**
11482     * Retrieve private session object this view hierarchy is using to
11483     * communicate with the window manager.
11484     * @return the session object to communicate with the window manager
11485     */
11486    /*package*/ IWindowSession getWindowSession() {
11487        return mAttachInfo != null ? mAttachInfo.mSession : null;
11488    }
11489
11490    /**
11491     * @param info the {@link android.view.View.AttachInfo} to associated with
11492     *        this view
11493     */
11494    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11495        //System.out.println("Attached! " + this);
11496        mAttachInfo = info;
11497        mWindowAttachCount++;
11498        // We will need to evaluate the drawable state at least once.
11499        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11500        if (mFloatingTreeObserver != null) {
11501            info.mTreeObserver.merge(mFloatingTreeObserver);
11502            mFloatingTreeObserver = null;
11503        }
11504        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11505            mAttachInfo.mScrollContainers.add(this);
11506            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11507        }
11508        performCollectViewAttributes(mAttachInfo, visibility);
11509        onAttachedToWindow();
11510
11511        ListenerInfo li = mListenerInfo;
11512        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11513                li != null ? li.mOnAttachStateChangeListeners : null;
11514        if (listeners != null && listeners.size() > 0) {
11515            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11516            // perform the dispatching. The iterator is a safe guard against listeners that
11517            // could mutate the list by calling the various add/remove methods. This prevents
11518            // the array from being modified while we iterate it.
11519            for (OnAttachStateChangeListener listener : listeners) {
11520                listener.onViewAttachedToWindow(this);
11521            }
11522        }
11523
11524        int vis = info.mWindowVisibility;
11525        if (vis != GONE) {
11526            onWindowVisibilityChanged(vis);
11527        }
11528        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11529            // If nobody has evaluated the drawable state yet, then do it now.
11530            refreshDrawableState();
11531        }
11532    }
11533
11534    void dispatchDetachedFromWindow() {
11535        AttachInfo info = mAttachInfo;
11536        if (info != null) {
11537            int vis = info.mWindowVisibility;
11538            if (vis != GONE) {
11539                onWindowVisibilityChanged(GONE);
11540            }
11541        }
11542
11543        onDetachedFromWindow();
11544
11545        ListenerInfo li = mListenerInfo;
11546        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11547                li != null ? li.mOnAttachStateChangeListeners : null;
11548        if (listeners != null && listeners.size() > 0) {
11549            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11550            // perform the dispatching. The iterator is a safe guard against listeners that
11551            // could mutate the list by calling the various add/remove methods. This prevents
11552            // the array from being modified while we iterate it.
11553            for (OnAttachStateChangeListener listener : listeners) {
11554                listener.onViewDetachedFromWindow(this);
11555            }
11556        }
11557
11558        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11559            mAttachInfo.mScrollContainers.remove(this);
11560            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11561        }
11562
11563        mAttachInfo = null;
11564    }
11565
11566    /**
11567     * Store this view hierarchy's frozen state into the given container.
11568     *
11569     * @param container The SparseArray in which to save the view's state.
11570     *
11571     * @see #restoreHierarchyState(android.util.SparseArray)
11572     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11573     * @see #onSaveInstanceState()
11574     */
11575    public void saveHierarchyState(SparseArray<Parcelable> container) {
11576        dispatchSaveInstanceState(container);
11577    }
11578
11579    /**
11580     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11581     * this view and its children. May be overridden to modify how freezing happens to a
11582     * view's children; for example, some views may want to not store state for their children.
11583     *
11584     * @param container The SparseArray in which to save the view's state.
11585     *
11586     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11587     * @see #saveHierarchyState(android.util.SparseArray)
11588     * @see #onSaveInstanceState()
11589     */
11590    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11591        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11592            mPrivateFlags &= ~SAVE_STATE_CALLED;
11593            Parcelable state = onSaveInstanceState();
11594            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11595                throw new IllegalStateException(
11596                        "Derived class did not call super.onSaveInstanceState()");
11597            }
11598            if (state != null) {
11599                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11600                // + ": " + state);
11601                container.put(mID, state);
11602            }
11603        }
11604    }
11605
11606    /**
11607     * Hook allowing a view to generate a representation of its internal state
11608     * that can later be used to create a new instance with that same state.
11609     * This state should only contain information that is not persistent or can
11610     * not be reconstructed later. For example, you will never store your
11611     * current position on screen because that will be computed again when a
11612     * new instance of the view is placed in its view hierarchy.
11613     * <p>
11614     * Some examples of things you may store here: the current cursor position
11615     * in a text view (but usually not the text itself since that is stored in a
11616     * content provider or other persistent storage), the currently selected
11617     * item in a list view.
11618     *
11619     * @return Returns a Parcelable object containing the view's current dynamic
11620     *         state, or null if there is nothing interesting to save. The
11621     *         default implementation returns null.
11622     * @see #onRestoreInstanceState(android.os.Parcelable)
11623     * @see #saveHierarchyState(android.util.SparseArray)
11624     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11625     * @see #setSaveEnabled(boolean)
11626     */
11627    protected Parcelable onSaveInstanceState() {
11628        mPrivateFlags |= SAVE_STATE_CALLED;
11629        return BaseSavedState.EMPTY_STATE;
11630    }
11631
11632    /**
11633     * Restore this view hierarchy's frozen state from the given container.
11634     *
11635     * @param container The SparseArray which holds previously frozen states.
11636     *
11637     * @see #saveHierarchyState(android.util.SparseArray)
11638     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11639     * @see #onRestoreInstanceState(android.os.Parcelable)
11640     */
11641    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11642        dispatchRestoreInstanceState(container);
11643    }
11644
11645    /**
11646     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11647     * state for this view and its children. May be overridden to modify how restoring
11648     * happens to a view's children; for example, some views may want to not store state
11649     * for their children.
11650     *
11651     * @param container The SparseArray which holds previously saved state.
11652     *
11653     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11654     * @see #restoreHierarchyState(android.util.SparseArray)
11655     * @see #onRestoreInstanceState(android.os.Parcelable)
11656     */
11657    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11658        if (mID != NO_ID) {
11659            Parcelable state = container.get(mID);
11660            if (state != null) {
11661                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11662                // + ": " + state);
11663                mPrivateFlags &= ~SAVE_STATE_CALLED;
11664                onRestoreInstanceState(state);
11665                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11666                    throw new IllegalStateException(
11667                            "Derived class did not call super.onRestoreInstanceState()");
11668                }
11669            }
11670        }
11671    }
11672
11673    /**
11674     * Hook allowing a view to re-apply a representation of its internal state that had previously
11675     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11676     * null state.
11677     *
11678     * @param state The frozen state that had previously been returned by
11679     *        {@link #onSaveInstanceState}.
11680     *
11681     * @see #onSaveInstanceState()
11682     * @see #restoreHierarchyState(android.util.SparseArray)
11683     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11684     */
11685    protected void onRestoreInstanceState(Parcelable state) {
11686        mPrivateFlags |= SAVE_STATE_CALLED;
11687        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11688            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11689                    + "received " + state.getClass().toString() + " instead. This usually happens "
11690                    + "when two views of different type have the same id in the same hierarchy. "
11691                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11692                    + "other views do not use the same id.");
11693        }
11694    }
11695
11696    /**
11697     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11698     *
11699     * @return the drawing start time in milliseconds
11700     */
11701    public long getDrawingTime() {
11702        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11703    }
11704
11705    /**
11706     * <p>Enables or disables the duplication of the parent's state into this view. When
11707     * duplication is enabled, this view gets its drawable state from its parent rather
11708     * than from its own internal properties.</p>
11709     *
11710     * <p>Note: in the current implementation, setting this property to true after the
11711     * view was added to a ViewGroup might have no effect at all. This property should
11712     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11713     *
11714     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11715     * property is enabled, an exception will be thrown.</p>
11716     *
11717     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11718     * parent, these states should not be affected by this method.</p>
11719     *
11720     * @param enabled True to enable duplication of the parent's drawable state, false
11721     *                to disable it.
11722     *
11723     * @see #getDrawableState()
11724     * @see #isDuplicateParentStateEnabled()
11725     */
11726    public void setDuplicateParentStateEnabled(boolean enabled) {
11727        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11728    }
11729
11730    /**
11731     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11732     *
11733     * @return True if this view's drawable state is duplicated from the parent,
11734     *         false otherwise
11735     *
11736     * @see #getDrawableState()
11737     * @see #setDuplicateParentStateEnabled(boolean)
11738     */
11739    public boolean isDuplicateParentStateEnabled() {
11740        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11741    }
11742
11743    /**
11744     * <p>Specifies the type of layer backing this view. The layer can be
11745     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11746     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11747     *
11748     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11749     * instance that controls how the layer is composed on screen. The following
11750     * properties of the paint are taken into account when composing the layer:</p>
11751     * <ul>
11752     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11753     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11754     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11755     * </ul>
11756     *
11757     * <p>If this view has an alpha value set to < 1.0 by calling
11758     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11759     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11760     * equivalent to setting a hardware layer on this view and providing a paint with
11761     * the desired alpha value.<p>
11762     *
11763     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11764     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11765     * for more information on when and how to use layers.</p>
11766     *
11767     * @param layerType The ype of layer to use with this view, must be one of
11768     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11769     *        {@link #LAYER_TYPE_HARDWARE}
11770     * @param paint The paint used to compose the layer. This argument is optional
11771     *        and can be null. It is ignored when the layer type is
11772     *        {@link #LAYER_TYPE_NONE}
11773     *
11774     * @see #getLayerType()
11775     * @see #LAYER_TYPE_NONE
11776     * @see #LAYER_TYPE_SOFTWARE
11777     * @see #LAYER_TYPE_HARDWARE
11778     * @see #setAlpha(float)
11779     *
11780     * @attr ref android.R.styleable#View_layerType
11781     */
11782    public void setLayerType(int layerType, Paint paint) {
11783        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11784            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11785                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11786        }
11787
11788        if (layerType == mLayerType) {
11789            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11790                mLayerPaint = paint == null ? new Paint() : paint;
11791                invalidateParentCaches();
11792                invalidate(true);
11793            }
11794            return;
11795        }
11796
11797        // Destroy any previous software drawing cache if needed
11798        switch (mLayerType) {
11799            case LAYER_TYPE_HARDWARE:
11800                destroyLayer(false);
11801                // fall through - non-accelerated views may use software layer mechanism instead
11802            case LAYER_TYPE_SOFTWARE:
11803                destroyDrawingCache();
11804                break;
11805            default:
11806                break;
11807        }
11808
11809        mLayerType = layerType;
11810        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11811        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11812        mLocalDirtyRect = layerDisabled ? null : new Rect();
11813
11814        invalidateParentCaches();
11815        invalidate(true);
11816    }
11817
11818    /**
11819     * Indicates whether this view has a static layer. A view with layer type
11820     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11821     * dynamic.
11822     */
11823    boolean hasStaticLayer() {
11824        return true;
11825    }
11826
11827    /**
11828     * Indicates what type of layer is currently associated with this view. By default
11829     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11830     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11831     * for more information on the different types of layers.
11832     *
11833     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11834     *         {@link #LAYER_TYPE_HARDWARE}
11835     *
11836     * @see #setLayerType(int, android.graphics.Paint)
11837     * @see #buildLayer()
11838     * @see #LAYER_TYPE_NONE
11839     * @see #LAYER_TYPE_SOFTWARE
11840     * @see #LAYER_TYPE_HARDWARE
11841     */
11842    public int getLayerType() {
11843        return mLayerType;
11844    }
11845
11846    /**
11847     * Forces this view's layer to be created and this view to be rendered
11848     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11849     * invoking this method will have no effect.
11850     *
11851     * This method can for instance be used to render a view into its layer before
11852     * starting an animation. If this view is complex, rendering into the layer
11853     * before starting the animation will avoid skipping frames.
11854     *
11855     * @throws IllegalStateException If this view is not attached to a window
11856     *
11857     * @see #setLayerType(int, android.graphics.Paint)
11858     */
11859    public void buildLayer() {
11860        if (mLayerType == LAYER_TYPE_NONE) return;
11861
11862        if (mAttachInfo == null) {
11863            throw new IllegalStateException("This view must be attached to a window first");
11864        }
11865
11866        switch (mLayerType) {
11867            case LAYER_TYPE_HARDWARE:
11868                if (mAttachInfo.mHardwareRenderer != null &&
11869                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11870                        mAttachInfo.mHardwareRenderer.validate()) {
11871                    getHardwareLayer();
11872                }
11873                break;
11874            case LAYER_TYPE_SOFTWARE:
11875                buildDrawingCache(true);
11876                break;
11877        }
11878    }
11879
11880    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11881    void flushLayer() {
11882        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11883            mHardwareLayer.flush();
11884        }
11885    }
11886
11887    /**
11888     * <p>Returns a hardware layer that can be used to draw this view again
11889     * without executing its draw method.</p>
11890     *
11891     * @return A HardwareLayer ready to render, or null if an error occurred.
11892     */
11893    HardwareLayer getHardwareLayer() {
11894        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11895                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11896            return null;
11897        }
11898
11899        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11900
11901        final int width = mRight - mLeft;
11902        final int height = mBottom - mTop;
11903
11904        if (width == 0 || height == 0) {
11905            return null;
11906        }
11907
11908        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11909            if (mHardwareLayer == null) {
11910                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11911                        width, height, isOpaque());
11912                mLocalDirtyRect.set(0, 0, width, height);
11913            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11914                mHardwareLayer.resize(width, height);
11915                mLocalDirtyRect.set(0, 0, width, height);
11916            }
11917
11918            // The layer is not valid if the underlying GPU resources cannot be allocated
11919            if (!mHardwareLayer.isValid()) {
11920                return null;
11921            }
11922
11923            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11924            mLocalDirtyRect.setEmpty();
11925        }
11926
11927        return mHardwareLayer;
11928    }
11929
11930    /**
11931     * Destroys this View's hardware layer if possible.
11932     *
11933     * @return True if the layer was destroyed, false otherwise.
11934     *
11935     * @see #setLayerType(int, android.graphics.Paint)
11936     * @see #LAYER_TYPE_HARDWARE
11937     */
11938    boolean destroyLayer(boolean valid) {
11939        if (mHardwareLayer != null) {
11940            AttachInfo info = mAttachInfo;
11941            if (info != null && info.mHardwareRenderer != null &&
11942                    info.mHardwareRenderer.isEnabled() &&
11943                    (valid || info.mHardwareRenderer.validate())) {
11944                mHardwareLayer.destroy();
11945                mHardwareLayer = null;
11946
11947                invalidate(true);
11948                invalidateParentCaches();
11949            }
11950            return true;
11951        }
11952        return false;
11953    }
11954
11955    /**
11956     * Destroys all hardware rendering resources. This method is invoked
11957     * when the system needs to reclaim resources. Upon execution of this
11958     * method, you should free any OpenGL resources created by the view.
11959     *
11960     * Note: you <strong>must</strong> call
11961     * <code>super.destroyHardwareResources()</code> when overriding
11962     * this method.
11963     *
11964     * @hide
11965     */
11966    protected void destroyHardwareResources() {
11967        destroyLayer(true);
11968    }
11969
11970    /**
11971     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11972     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11973     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11974     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11975     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11976     * null.</p>
11977     *
11978     * <p>Enabling the drawing cache is similar to
11979     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11980     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11981     * drawing cache has no effect on rendering because the system uses a different mechanism
11982     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11983     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11984     * for information on how to enable software and hardware layers.</p>
11985     *
11986     * <p>This API can be used to manually generate
11987     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11988     * {@link #getDrawingCache()}.</p>
11989     *
11990     * @param enabled true to enable the drawing cache, false otherwise
11991     *
11992     * @see #isDrawingCacheEnabled()
11993     * @see #getDrawingCache()
11994     * @see #buildDrawingCache()
11995     * @see #setLayerType(int, android.graphics.Paint)
11996     */
11997    public void setDrawingCacheEnabled(boolean enabled) {
11998        mCachingFailed = false;
11999        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12000    }
12001
12002    /**
12003     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12004     *
12005     * @return true if the drawing cache is enabled
12006     *
12007     * @see #setDrawingCacheEnabled(boolean)
12008     * @see #getDrawingCache()
12009     */
12010    @ViewDebug.ExportedProperty(category = "drawing")
12011    public boolean isDrawingCacheEnabled() {
12012        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12013    }
12014
12015    /**
12016     * Debugging utility which recursively outputs the dirty state of a view and its
12017     * descendants.
12018     *
12019     * @hide
12020     */
12021    @SuppressWarnings({"UnusedDeclaration"})
12022    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12023        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12024                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12025                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12026                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12027        if (clear) {
12028            mPrivateFlags &= clearMask;
12029        }
12030        if (this instanceof ViewGroup) {
12031            ViewGroup parent = (ViewGroup) this;
12032            final int count = parent.getChildCount();
12033            for (int i = 0; i < count; i++) {
12034                final View child = parent.getChildAt(i);
12035                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12036            }
12037        }
12038    }
12039
12040    /**
12041     * This method is used by ViewGroup to cause its children to restore or recreate their
12042     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12043     * to recreate its own display list, which would happen if it went through the normal
12044     * draw/dispatchDraw mechanisms.
12045     *
12046     * @hide
12047     */
12048    protected void dispatchGetDisplayList() {}
12049
12050    /**
12051     * A view that is not attached or hardware accelerated cannot create a display list.
12052     * This method checks these conditions and returns the appropriate result.
12053     *
12054     * @return true if view has the ability to create a display list, false otherwise.
12055     *
12056     * @hide
12057     */
12058    public boolean canHaveDisplayList() {
12059        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12060    }
12061
12062    /**
12063     * @return The HardwareRenderer associated with that view or null if hardware rendering
12064     * is not supported or this this has not been attached to a window.
12065     *
12066     * @hide
12067     */
12068    public HardwareRenderer getHardwareRenderer() {
12069        if (mAttachInfo != null) {
12070            return mAttachInfo.mHardwareRenderer;
12071        }
12072        return null;
12073    }
12074
12075    /**
12076     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12077     * Otherwise, the same display list will be returned (after having been rendered into
12078     * along the way, depending on the invalidation state of the view).
12079     *
12080     * @param displayList The previous version of this displayList, could be null.
12081     * @param isLayer Whether the requester of the display list is a layer. If so,
12082     * the view will avoid creating a layer inside the resulting display list.
12083     * @return A new or reused DisplayList object.
12084     */
12085    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12086        if (!canHaveDisplayList()) {
12087            return null;
12088        }
12089
12090        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12091                displayList == null || !displayList.isValid() ||
12092                (!isLayer && mRecreateDisplayList))) {
12093            // Don't need to recreate the display list, just need to tell our
12094            // children to restore/recreate theirs
12095            if (displayList != null && displayList.isValid() &&
12096                    !isLayer && !mRecreateDisplayList) {
12097                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12098                mPrivateFlags &= ~DIRTY_MASK;
12099                dispatchGetDisplayList();
12100
12101                return displayList;
12102            }
12103
12104            if (!isLayer) {
12105                // If we got here, we're recreating it. Mark it as such to ensure that
12106                // we copy in child display lists into ours in drawChild()
12107                mRecreateDisplayList = true;
12108            }
12109            if (displayList == null) {
12110                final String name = getClass().getSimpleName();
12111                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12112                // If we're creating a new display list, make sure our parent gets invalidated
12113                // since they will need to recreate their display list to account for this
12114                // new child display list.
12115                invalidateParentCaches();
12116            }
12117
12118            boolean caching = false;
12119            final HardwareCanvas canvas = displayList.start();
12120            int width = mRight - mLeft;
12121            int height = mBottom - mTop;
12122
12123            try {
12124                canvas.setViewport(width, height);
12125                // The dirty rect should always be null for a display list
12126                canvas.onPreDraw(null);
12127                int layerType = (
12128                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12129                        getLayerType() : LAYER_TYPE_NONE;
12130                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12131                    if (layerType == LAYER_TYPE_HARDWARE) {
12132                        final HardwareLayer layer = getHardwareLayer();
12133                        if (layer != null && layer.isValid()) {
12134                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12135                        } else {
12136                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12137                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12138                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12139                        }
12140                        caching = true;
12141                    } else {
12142                        buildDrawingCache(true);
12143                        Bitmap cache = getDrawingCache(true);
12144                        if (cache != null) {
12145                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12146                            caching = true;
12147                        }
12148                    }
12149                } else {
12150
12151                    computeScroll();
12152
12153                    canvas.translate(-mScrollX, -mScrollY);
12154                    if (!isLayer) {
12155                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12156                        mPrivateFlags &= ~DIRTY_MASK;
12157                    }
12158
12159                    // Fast path for layouts with no backgrounds
12160                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12161                        dispatchDraw(canvas);
12162                    } else {
12163                        draw(canvas);
12164                    }
12165                }
12166            } finally {
12167                canvas.onPostDraw();
12168
12169                displayList.end();
12170                displayList.setCaching(caching);
12171                if (isLayer) {
12172                    displayList.setLeftTopRightBottom(0, 0, width, height);
12173                } else {
12174                    setDisplayListProperties(displayList);
12175                }
12176            }
12177        } else if (!isLayer) {
12178            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12179            mPrivateFlags &= ~DIRTY_MASK;
12180        }
12181
12182        return displayList;
12183    }
12184
12185    /**
12186     * Get the DisplayList for the HardwareLayer
12187     *
12188     * @param layer The HardwareLayer whose DisplayList we want
12189     * @return A DisplayList fopr the specified HardwareLayer
12190     */
12191    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12192        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12193        layer.setDisplayList(displayList);
12194        return displayList;
12195    }
12196
12197
12198    /**
12199     * <p>Returns a display list that can be used to draw this view again
12200     * without executing its draw method.</p>
12201     *
12202     * @return A DisplayList ready to replay, or null if caching is not enabled.
12203     *
12204     * @hide
12205     */
12206    public DisplayList getDisplayList() {
12207        mDisplayList = getDisplayList(mDisplayList, false);
12208        return mDisplayList;
12209    }
12210
12211    /**
12212     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12213     *
12214     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12215     *
12216     * @see #getDrawingCache(boolean)
12217     */
12218    public Bitmap getDrawingCache() {
12219        return getDrawingCache(false);
12220    }
12221
12222    /**
12223     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12224     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12225     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12226     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12227     * request the drawing cache by calling this method and draw it on screen if the
12228     * returned bitmap is not null.</p>
12229     *
12230     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12231     * this method will create a bitmap of the same size as this view. Because this bitmap
12232     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12233     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12234     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12235     * size than the view. This implies that your application must be able to handle this
12236     * size.</p>
12237     *
12238     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12239     *        the current density of the screen when the application is in compatibility
12240     *        mode.
12241     *
12242     * @return A bitmap representing this view or null if cache is disabled.
12243     *
12244     * @see #setDrawingCacheEnabled(boolean)
12245     * @see #isDrawingCacheEnabled()
12246     * @see #buildDrawingCache(boolean)
12247     * @see #destroyDrawingCache()
12248     */
12249    public Bitmap getDrawingCache(boolean autoScale) {
12250        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12251            return null;
12252        }
12253        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12254            buildDrawingCache(autoScale);
12255        }
12256        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12257    }
12258
12259    /**
12260     * <p>Frees the resources used by the drawing cache. If you call
12261     * {@link #buildDrawingCache()} manually without calling
12262     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12263     * should cleanup the cache with this method afterwards.</p>
12264     *
12265     * @see #setDrawingCacheEnabled(boolean)
12266     * @see #buildDrawingCache()
12267     * @see #getDrawingCache()
12268     */
12269    public void destroyDrawingCache() {
12270        if (mDrawingCache != null) {
12271            mDrawingCache.recycle();
12272            mDrawingCache = null;
12273        }
12274        if (mUnscaledDrawingCache != null) {
12275            mUnscaledDrawingCache.recycle();
12276            mUnscaledDrawingCache = null;
12277        }
12278    }
12279
12280    /**
12281     * Setting a solid background color for the drawing cache's bitmaps will improve
12282     * performance and memory usage. Note, though that this should only be used if this
12283     * view will always be drawn on top of a solid color.
12284     *
12285     * @param color The background color to use for the drawing cache's bitmap
12286     *
12287     * @see #setDrawingCacheEnabled(boolean)
12288     * @see #buildDrawingCache()
12289     * @see #getDrawingCache()
12290     */
12291    public void setDrawingCacheBackgroundColor(int color) {
12292        if (color != mDrawingCacheBackgroundColor) {
12293            mDrawingCacheBackgroundColor = color;
12294            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12295        }
12296    }
12297
12298    /**
12299     * @see #setDrawingCacheBackgroundColor(int)
12300     *
12301     * @return The background color to used for the drawing cache's bitmap
12302     */
12303    public int getDrawingCacheBackgroundColor() {
12304        return mDrawingCacheBackgroundColor;
12305    }
12306
12307    /**
12308     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12309     *
12310     * @see #buildDrawingCache(boolean)
12311     */
12312    public void buildDrawingCache() {
12313        buildDrawingCache(false);
12314    }
12315
12316    /**
12317     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12318     *
12319     * <p>If you call {@link #buildDrawingCache()} manually without calling
12320     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12321     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12322     *
12323     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12324     * this method will create a bitmap of the same size as this view. Because this bitmap
12325     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12326     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12327     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12328     * size than the view. This implies that your application must be able to handle this
12329     * size.</p>
12330     *
12331     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12332     * you do not need the drawing cache bitmap, calling this method will increase memory
12333     * usage and cause the view to be rendered in software once, thus negatively impacting
12334     * performance.</p>
12335     *
12336     * @see #getDrawingCache()
12337     * @see #destroyDrawingCache()
12338     */
12339    public void buildDrawingCache(boolean autoScale) {
12340        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12341                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12342            mCachingFailed = false;
12343
12344            int width = mRight - mLeft;
12345            int height = mBottom - mTop;
12346
12347            final AttachInfo attachInfo = mAttachInfo;
12348            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12349
12350            if (autoScale && scalingRequired) {
12351                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12352                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12353            }
12354
12355            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12356            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12357            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12358
12359            if (width <= 0 || height <= 0 ||
12360                     // Projected bitmap size in bytes
12361                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12362                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12363                destroyDrawingCache();
12364                mCachingFailed = true;
12365                return;
12366            }
12367
12368            boolean clear = true;
12369            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12370
12371            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12372                Bitmap.Config quality;
12373                if (!opaque) {
12374                    // Never pick ARGB_4444 because it looks awful
12375                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12376                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12377                        case DRAWING_CACHE_QUALITY_AUTO:
12378                            quality = Bitmap.Config.ARGB_8888;
12379                            break;
12380                        case DRAWING_CACHE_QUALITY_LOW:
12381                            quality = Bitmap.Config.ARGB_8888;
12382                            break;
12383                        case DRAWING_CACHE_QUALITY_HIGH:
12384                            quality = Bitmap.Config.ARGB_8888;
12385                            break;
12386                        default:
12387                            quality = Bitmap.Config.ARGB_8888;
12388                            break;
12389                    }
12390                } else {
12391                    // Optimization for translucent windows
12392                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12393                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12394                }
12395
12396                // Try to cleanup memory
12397                if (bitmap != null) bitmap.recycle();
12398
12399                try {
12400                    bitmap = Bitmap.createBitmap(width, height, quality);
12401                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12402                    if (autoScale) {
12403                        mDrawingCache = bitmap;
12404                    } else {
12405                        mUnscaledDrawingCache = bitmap;
12406                    }
12407                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12408                } catch (OutOfMemoryError e) {
12409                    // If there is not enough memory to create the bitmap cache, just
12410                    // ignore the issue as bitmap caches are not required to draw the
12411                    // view hierarchy
12412                    if (autoScale) {
12413                        mDrawingCache = null;
12414                    } else {
12415                        mUnscaledDrawingCache = null;
12416                    }
12417                    mCachingFailed = true;
12418                    return;
12419                }
12420
12421                clear = drawingCacheBackgroundColor != 0;
12422            }
12423
12424            Canvas canvas;
12425            if (attachInfo != null) {
12426                canvas = attachInfo.mCanvas;
12427                if (canvas == null) {
12428                    canvas = new Canvas();
12429                }
12430                canvas.setBitmap(bitmap);
12431                // Temporarily clobber the cached Canvas in case one of our children
12432                // is also using a drawing cache. Without this, the children would
12433                // steal the canvas by attaching their own bitmap to it and bad, bad
12434                // thing would happen (invisible views, corrupted drawings, etc.)
12435                attachInfo.mCanvas = null;
12436            } else {
12437                // This case should hopefully never or seldom happen
12438                canvas = new Canvas(bitmap);
12439            }
12440
12441            if (clear) {
12442                bitmap.eraseColor(drawingCacheBackgroundColor);
12443            }
12444
12445            computeScroll();
12446            final int restoreCount = canvas.save();
12447
12448            if (autoScale && scalingRequired) {
12449                final float scale = attachInfo.mApplicationScale;
12450                canvas.scale(scale, scale);
12451            }
12452
12453            canvas.translate(-mScrollX, -mScrollY);
12454
12455            mPrivateFlags |= DRAWN;
12456            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12457                    mLayerType != LAYER_TYPE_NONE) {
12458                mPrivateFlags |= DRAWING_CACHE_VALID;
12459            }
12460
12461            // Fast path for layouts with no backgrounds
12462            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12463                mPrivateFlags &= ~DIRTY_MASK;
12464                dispatchDraw(canvas);
12465            } else {
12466                draw(canvas);
12467            }
12468
12469            canvas.restoreToCount(restoreCount);
12470            canvas.setBitmap(null);
12471
12472            if (attachInfo != null) {
12473                // Restore the cached Canvas for our siblings
12474                attachInfo.mCanvas = canvas;
12475            }
12476        }
12477    }
12478
12479    /**
12480     * Create a snapshot of the view into a bitmap.  We should probably make
12481     * some form of this public, but should think about the API.
12482     */
12483    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12484        int width = mRight - mLeft;
12485        int height = mBottom - mTop;
12486
12487        final AttachInfo attachInfo = mAttachInfo;
12488        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12489        width = (int) ((width * scale) + 0.5f);
12490        height = (int) ((height * scale) + 0.5f);
12491
12492        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12493        if (bitmap == null) {
12494            throw new OutOfMemoryError();
12495        }
12496
12497        Resources resources = getResources();
12498        if (resources != null) {
12499            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12500        }
12501
12502        Canvas canvas;
12503        if (attachInfo != null) {
12504            canvas = attachInfo.mCanvas;
12505            if (canvas == null) {
12506                canvas = new Canvas();
12507            }
12508            canvas.setBitmap(bitmap);
12509            // Temporarily clobber the cached Canvas in case one of our children
12510            // is also using a drawing cache. Without this, the children would
12511            // steal the canvas by attaching their own bitmap to it and bad, bad
12512            // things would happen (invisible views, corrupted drawings, etc.)
12513            attachInfo.mCanvas = null;
12514        } else {
12515            // This case should hopefully never or seldom happen
12516            canvas = new Canvas(bitmap);
12517        }
12518
12519        if ((backgroundColor & 0xff000000) != 0) {
12520            bitmap.eraseColor(backgroundColor);
12521        }
12522
12523        computeScroll();
12524        final int restoreCount = canvas.save();
12525        canvas.scale(scale, scale);
12526        canvas.translate(-mScrollX, -mScrollY);
12527
12528        // Temporarily remove the dirty mask
12529        int flags = mPrivateFlags;
12530        mPrivateFlags &= ~DIRTY_MASK;
12531
12532        // Fast path for layouts with no backgrounds
12533        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12534            dispatchDraw(canvas);
12535        } else {
12536            draw(canvas);
12537        }
12538
12539        mPrivateFlags = flags;
12540
12541        canvas.restoreToCount(restoreCount);
12542        canvas.setBitmap(null);
12543
12544        if (attachInfo != null) {
12545            // Restore the cached Canvas for our siblings
12546            attachInfo.mCanvas = canvas;
12547        }
12548
12549        return bitmap;
12550    }
12551
12552    /**
12553     * Indicates whether this View is currently in edit mode. A View is usually
12554     * in edit mode when displayed within a developer tool. For instance, if
12555     * this View is being drawn by a visual user interface builder, this method
12556     * should return true.
12557     *
12558     * Subclasses should check the return value of this method to provide
12559     * different behaviors if their normal behavior might interfere with the
12560     * host environment. For instance: the class spawns a thread in its
12561     * constructor, the drawing code relies on device-specific features, etc.
12562     *
12563     * This method is usually checked in the drawing code of custom widgets.
12564     *
12565     * @return True if this View is in edit mode, false otherwise.
12566     */
12567    public boolean isInEditMode() {
12568        return false;
12569    }
12570
12571    /**
12572     * If the View draws content inside its padding and enables fading edges,
12573     * it needs to support padding offsets. Padding offsets are added to the
12574     * fading edges to extend the length of the fade so that it covers pixels
12575     * drawn inside the padding.
12576     *
12577     * Subclasses of this class should override this method if they need
12578     * to draw content inside the padding.
12579     *
12580     * @return True if padding offset must be applied, false otherwise.
12581     *
12582     * @see #getLeftPaddingOffset()
12583     * @see #getRightPaddingOffset()
12584     * @see #getTopPaddingOffset()
12585     * @see #getBottomPaddingOffset()
12586     *
12587     * @since CURRENT
12588     */
12589    protected boolean isPaddingOffsetRequired() {
12590        return false;
12591    }
12592
12593    /**
12594     * Amount by which to extend the left fading region. Called only when
12595     * {@link #isPaddingOffsetRequired()} returns true.
12596     *
12597     * @return The left padding offset in pixels.
12598     *
12599     * @see #isPaddingOffsetRequired()
12600     *
12601     * @since CURRENT
12602     */
12603    protected int getLeftPaddingOffset() {
12604        return 0;
12605    }
12606
12607    /**
12608     * Amount by which to extend the right fading region. Called only when
12609     * {@link #isPaddingOffsetRequired()} returns true.
12610     *
12611     * @return The right padding offset in pixels.
12612     *
12613     * @see #isPaddingOffsetRequired()
12614     *
12615     * @since CURRENT
12616     */
12617    protected int getRightPaddingOffset() {
12618        return 0;
12619    }
12620
12621    /**
12622     * Amount by which to extend the top fading region. Called only when
12623     * {@link #isPaddingOffsetRequired()} returns true.
12624     *
12625     * @return The top padding offset in pixels.
12626     *
12627     * @see #isPaddingOffsetRequired()
12628     *
12629     * @since CURRENT
12630     */
12631    protected int getTopPaddingOffset() {
12632        return 0;
12633    }
12634
12635    /**
12636     * Amount by which to extend the bottom fading region. Called only when
12637     * {@link #isPaddingOffsetRequired()} returns true.
12638     *
12639     * @return The bottom padding offset in pixels.
12640     *
12641     * @see #isPaddingOffsetRequired()
12642     *
12643     * @since CURRENT
12644     */
12645    protected int getBottomPaddingOffset() {
12646        return 0;
12647    }
12648
12649    /**
12650     * @hide
12651     * @param offsetRequired
12652     */
12653    protected int getFadeTop(boolean offsetRequired) {
12654        int top = mPaddingTop;
12655        if (offsetRequired) top += getTopPaddingOffset();
12656        return top;
12657    }
12658
12659    /**
12660     * @hide
12661     * @param offsetRequired
12662     */
12663    protected int getFadeHeight(boolean offsetRequired) {
12664        int padding = mPaddingTop;
12665        if (offsetRequired) padding += getTopPaddingOffset();
12666        return mBottom - mTop - mPaddingBottom - padding;
12667    }
12668
12669    /**
12670     * <p>Indicates whether this view is attached to a hardware accelerated
12671     * window or not.</p>
12672     *
12673     * <p>Even if this method returns true, it does not mean that every call
12674     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12675     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12676     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12677     * window is hardware accelerated,
12678     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12679     * return false, and this method will return true.</p>
12680     *
12681     * @return True if the view is attached to a window and the window is
12682     *         hardware accelerated; false in any other case.
12683     */
12684    public boolean isHardwareAccelerated() {
12685        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12686    }
12687
12688    /**
12689     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12690     * case of an active Animation being run on the view.
12691     */
12692    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12693            Animation a, boolean scalingRequired) {
12694        Transformation invalidationTransform;
12695        final int flags = parent.mGroupFlags;
12696        final boolean initialized = a.isInitialized();
12697        if (!initialized) {
12698            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12699            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12700            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12701            onAnimationStart();
12702        }
12703
12704        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12705        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12706            if (parent.mInvalidationTransformation == null) {
12707                parent.mInvalidationTransformation = new Transformation();
12708            }
12709            invalidationTransform = parent.mInvalidationTransformation;
12710            a.getTransformation(drawingTime, invalidationTransform, 1f);
12711        } else {
12712            invalidationTransform = parent.mChildTransformation;
12713        }
12714
12715        if (more) {
12716            if (!a.willChangeBounds()) {
12717                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12718                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12719                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12720                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12721                    // The child need to draw an animation, potentially offscreen, so
12722                    // make sure we do not cancel invalidate requests
12723                    parent.mPrivateFlags |= DRAW_ANIMATION;
12724                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12725                }
12726            } else {
12727                if (parent.mInvalidateRegion == null) {
12728                    parent.mInvalidateRegion = new RectF();
12729                }
12730                final RectF region = parent.mInvalidateRegion;
12731                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12732                        invalidationTransform);
12733
12734                // The child need to draw an animation, potentially offscreen, so
12735                // make sure we do not cancel invalidate requests
12736                parent.mPrivateFlags |= DRAW_ANIMATION;
12737
12738                final int left = mLeft + (int) region.left;
12739                final int top = mTop + (int) region.top;
12740                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12741                        top + (int) (region.height() + .5f));
12742            }
12743        }
12744        return more;
12745    }
12746
12747    /**
12748     * This method is called by getDisplayList() when a display list is created or re-rendered.
12749     * It sets or resets the current value of all properties on that display list (resetting is
12750     * necessary when a display list is being re-created, because we need to make sure that
12751     * previously-set transform values
12752     */
12753    void setDisplayListProperties(DisplayList displayList) {
12754        if (displayList != null) {
12755            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12756            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12757            if (mParent instanceof ViewGroup) {
12758                displayList.setClipChildren(
12759                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12760            }
12761            float alpha = 1;
12762            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12763                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12764                ViewGroup parentVG = (ViewGroup) mParent;
12765                final boolean hasTransform =
12766                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12767                if (hasTransform) {
12768                    Transformation transform = parentVG.mChildTransformation;
12769                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12770                    if (transformType != Transformation.TYPE_IDENTITY) {
12771                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12772                            alpha = transform.getAlpha();
12773                        }
12774                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12775                            displayList.setStaticMatrix(transform.getMatrix());
12776                        }
12777                    }
12778                }
12779            }
12780            if (mTransformationInfo != null) {
12781                alpha *= mTransformationInfo.mAlpha;
12782                if (alpha < 1) {
12783                    final int multipliedAlpha = (int) (255 * alpha);
12784                    if (onSetAlpha(multipliedAlpha)) {
12785                        alpha = 1;
12786                    }
12787                }
12788                displayList.setTransformationInfo(alpha,
12789                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12790                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12791                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12792                        mTransformationInfo.mScaleY);
12793                if (mTransformationInfo.mCamera == null) {
12794                    mTransformationInfo.mCamera = new Camera();
12795                    mTransformationInfo.matrix3D = new Matrix();
12796                }
12797                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12798                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12799                    displayList.setPivotX(getPivotX());
12800                    displayList.setPivotY(getPivotY());
12801                }
12802            } else if (alpha < 1) {
12803                displayList.setAlpha(alpha);
12804            }
12805        }
12806    }
12807
12808    /**
12809     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12810     * This draw() method is an implementation detail and is not intended to be overridden or
12811     * to be called from anywhere else other than ViewGroup.drawChild().
12812     */
12813    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12814        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12815        boolean more = false;
12816        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12817        final int flags = parent.mGroupFlags;
12818
12819        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12820            parent.mChildTransformation.clear();
12821            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12822        }
12823
12824        Transformation transformToApply = null;
12825        boolean concatMatrix = false;
12826
12827        boolean scalingRequired = false;
12828        boolean caching;
12829        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12830
12831        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12832        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12833                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12834            caching = true;
12835            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12836            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12837        } else {
12838            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12839        }
12840
12841        final Animation a = getAnimation();
12842        if (a != null) {
12843            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12844            concatMatrix = a.willChangeTransformationMatrix();
12845            if (concatMatrix) {
12846                mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM;
12847            }
12848            transformToApply = parent.mChildTransformation;
12849        } else {
12850            if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12851                    mDisplayList != null) {
12852                // No longer animating: clear out old animation matrix
12853                mDisplayList.setAnimationMatrix(null);
12854                mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12855            }
12856            if (!useDisplayListProperties &&
12857                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12858                final boolean hasTransform =
12859                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12860                if (hasTransform) {
12861                    final int transformType = parent.mChildTransformation.getTransformationType();
12862                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12863                            parent.mChildTransformation : null;
12864                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12865                }
12866            }
12867        }
12868
12869        concatMatrix |= !childHasIdentityMatrix;
12870
12871        // Sets the flag as early as possible to allow draw() implementations
12872        // to call invalidate() successfully when doing animations
12873        mPrivateFlags |= DRAWN;
12874
12875        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12876                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12877            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12878            return more;
12879        }
12880        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12881
12882        if (hardwareAccelerated) {
12883            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12884            // retain the flag's value temporarily in the mRecreateDisplayList flag
12885            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12886            mPrivateFlags &= ~INVALIDATED;
12887        }
12888
12889        computeScroll();
12890
12891        final int sx = mScrollX;
12892        final int sy = mScrollY;
12893
12894        DisplayList displayList = null;
12895        Bitmap cache = null;
12896        boolean hasDisplayList = false;
12897        if (caching) {
12898            if (!hardwareAccelerated) {
12899                if (layerType != LAYER_TYPE_NONE) {
12900                    layerType = LAYER_TYPE_SOFTWARE;
12901                    buildDrawingCache(true);
12902                }
12903                cache = getDrawingCache(true);
12904            } else {
12905                switch (layerType) {
12906                    case LAYER_TYPE_SOFTWARE:
12907                        if (useDisplayListProperties) {
12908                            hasDisplayList = canHaveDisplayList();
12909                        } else {
12910                            buildDrawingCache(true);
12911                            cache = getDrawingCache(true);
12912                        }
12913                        break;
12914                    case LAYER_TYPE_HARDWARE:
12915                        if (useDisplayListProperties) {
12916                            hasDisplayList = canHaveDisplayList();
12917                        }
12918                        break;
12919                    case LAYER_TYPE_NONE:
12920                        // Delay getting the display list until animation-driven alpha values are
12921                        // set up and possibly passed on to the view
12922                        hasDisplayList = canHaveDisplayList();
12923                        break;
12924                }
12925            }
12926        }
12927        useDisplayListProperties &= hasDisplayList;
12928        if (useDisplayListProperties) {
12929            displayList = getDisplayList();
12930            if (!displayList.isValid()) {
12931                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12932                // to getDisplayList(), the display list will be marked invalid and we should not
12933                // try to use it again.
12934                displayList = null;
12935                hasDisplayList = false;
12936                useDisplayListProperties = false;
12937            }
12938        }
12939
12940        final boolean hasNoCache = cache == null || hasDisplayList;
12941        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12942                layerType != LAYER_TYPE_HARDWARE;
12943
12944        int restoreTo = -1;
12945        if (!useDisplayListProperties || transformToApply != null) {
12946            restoreTo = canvas.save();
12947        }
12948        if (offsetForScroll) {
12949            canvas.translate(mLeft - sx, mTop - sy);
12950        } else {
12951            if (!useDisplayListProperties) {
12952                canvas.translate(mLeft, mTop);
12953            }
12954            if (scalingRequired) {
12955                if (useDisplayListProperties) {
12956                    // TODO: Might not need this if we put everything inside the DL
12957                    restoreTo = canvas.save();
12958                }
12959                // mAttachInfo cannot be null, otherwise scalingRequired == false
12960                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12961                canvas.scale(scale, scale);
12962            }
12963        }
12964
12965        float alpha = useDisplayListProperties ? 1 : getAlpha();
12966        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12967            if (transformToApply != null || !childHasIdentityMatrix) {
12968                int transX = 0;
12969                int transY = 0;
12970
12971                if (offsetForScroll) {
12972                    transX = -sx;
12973                    transY = -sy;
12974                }
12975
12976                if (transformToApply != null) {
12977                    if (concatMatrix) {
12978                        if (useDisplayListProperties) {
12979                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12980                        } else {
12981                            // Undo the scroll translation, apply the transformation matrix,
12982                            // then redo the scroll translate to get the correct result.
12983                            canvas.translate(-transX, -transY);
12984                            canvas.concat(transformToApply.getMatrix());
12985                            canvas.translate(transX, transY);
12986                        }
12987                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12988                    }
12989
12990                    float transformAlpha = transformToApply.getAlpha();
12991                    if (transformAlpha < 1) {
12992                        alpha *= transformToApply.getAlpha();
12993                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12994                    }
12995                }
12996
12997                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12998                    canvas.translate(-transX, -transY);
12999                    canvas.concat(getMatrix());
13000                    canvas.translate(transX, transY);
13001                }
13002            }
13003
13004            if (alpha < 1) {
13005                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13006                if (hasNoCache) {
13007                    final int multipliedAlpha = (int) (255 * alpha);
13008                    if (!onSetAlpha(multipliedAlpha)) {
13009                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13010                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13011                                layerType != LAYER_TYPE_NONE) {
13012                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13013                        }
13014                        if (useDisplayListProperties) {
13015                            displayList.setAlpha(alpha * getAlpha());
13016                        } else  if (layerType == LAYER_TYPE_NONE) {
13017                            final int scrollX = hasDisplayList ? 0 : sx;
13018                            final int scrollY = hasDisplayList ? 0 : sy;
13019                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13020                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13021                        }
13022                    } else {
13023                        // Alpha is handled by the child directly, clobber the layer's alpha
13024                        mPrivateFlags |= ALPHA_SET;
13025                    }
13026                }
13027            }
13028        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13029            onSetAlpha(255);
13030            mPrivateFlags &= ~ALPHA_SET;
13031        }
13032
13033        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13034                !useDisplayListProperties) {
13035            if (offsetForScroll) {
13036                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13037            } else {
13038                if (!scalingRequired || cache == null) {
13039                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13040                } else {
13041                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13042                }
13043            }
13044        }
13045
13046        if (!useDisplayListProperties && hasDisplayList) {
13047            displayList = getDisplayList();
13048            if (!displayList.isValid()) {
13049                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13050                // to getDisplayList(), the display list will be marked invalid and we should not
13051                // try to use it again.
13052                displayList = null;
13053                hasDisplayList = false;
13054            }
13055        }
13056
13057        if (hasNoCache) {
13058            boolean layerRendered = false;
13059            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13060                final HardwareLayer layer = getHardwareLayer();
13061                if (layer != null && layer.isValid()) {
13062                    mLayerPaint.setAlpha((int) (alpha * 255));
13063                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13064                    layerRendered = true;
13065                } else {
13066                    final int scrollX = hasDisplayList ? 0 : sx;
13067                    final int scrollY = hasDisplayList ? 0 : sy;
13068                    canvas.saveLayer(scrollX, scrollY,
13069                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13070                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13071                }
13072            }
13073
13074            if (!layerRendered) {
13075                if (!hasDisplayList) {
13076                    // Fast path for layouts with no backgrounds
13077                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13078                        mPrivateFlags &= ~DIRTY_MASK;
13079                        dispatchDraw(canvas);
13080                    } else {
13081                        draw(canvas);
13082                    }
13083                } else {
13084                    mPrivateFlags &= ~DIRTY_MASK;
13085                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13086                }
13087            }
13088        } else if (cache != null) {
13089            mPrivateFlags &= ~DIRTY_MASK;
13090            Paint cachePaint;
13091
13092            if (layerType == LAYER_TYPE_NONE) {
13093                cachePaint = parent.mCachePaint;
13094                if (cachePaint == null) {
13095                    cachePaint = new Paint();
13096                    cachePaint.setDither(false);
13097                    parent.mCachePaint = cachePaint;
13098                }
13099                if (alpha < 1) {
13100                    cachePaint.setAlpha((int) (alpha * 255));
13101                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13102                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13103                    cachePaint.setAlpha(255);
13104                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13105                }
13106            } else {
13107                cachePaint = mLayerPaint;
13108                cachePaint.setAlpha((int) (alpha * 255));
13109            }
13110            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13111        }
13112
13113        if (restoreTo >= 0) {
13114            canvas.restoreToCount(restoreTo);
13115        }
13116
13117        if (a != null && !more) {
13118            if (!hardwareAccelerated && !a.getFillAfter()) {
13119                onSetAlpha(255);
13120            }
13121            parent.finishAnimatingView(this, a);
13122        }
13123
13124        if (more && hardwareAccelerated) {
13125            // invalidation is the trigger to recreate display lists, so if we're using
13126            // display lists to render, force an invalidate to allow the animation to
13127            // continue drawing another frame
13128            parent.invalidate(true);
13129            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13130                // alpha animations should cause the child to recreate its display list
13131                invalidate(true);
13132            }
13133        }
13134
13135        mRecreateDisplayList = false;
13136
13137        return more;
13138    }
13139
13140    /**
13141     * Manually render this view (and all of its children) to the given Canvas.
13142     * The view must have already done a full layout before this function is
13143     * called.  When implementing a view, implement
13144     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13145     * If you do need to override this method, call the superclass version.
13146     *
13147     * @param canvas The Canvas to which the View is rendered.
13148     */
13149    public void draw(Canvas canvas) {
13150        final int privateFlags = mPrivateFlags;
13151        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13152                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13153        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13154
13155        /*
13156         * Draw traversal performs several drawing steps which must be executed
13157         * in the appropriate order:
13158         *
13159         *      1. Draw the background
13160         *      2. If necessary, save the canvas' layers to prepare for fading
13161         *      3. Draw view's content
13162         *      4. Draw children
13163         *      5. If necessary, draw the fading edges and restore layers
13164         *      6. Draw decorations (scrollbars for instance)
13165         */
13166
13167        // Step 1, draw the background, if needed
13168        int saveCount;
13169
13170        if (!dirtyOpaque) {
13171            final Drawable background = mBackground;
13172            if (background != null) {
13173                final int scrollX = mScrollX;
13174                final int scrollY = mScrollY;
13175
13176                if (mBackgroundSizeChanged) {
13177                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13178                    mBackgroundSizeChanged = false;
13179                }
13180
13181                if ((scrollX | scrollY) == 0) {
13182                    background.draw(canvas);
13183                } else {
13184                    canvas.translate(scrollX, scrollY);
13185                    background.draw(canvas);
13186                    canvas.translate(-scrollX, -scrollY);
13187                }
13188            }
13189        }
13190
13191        // skip step 2 & 5 if possible (common case)
13192        final int viewFlags = mViewFlags;
13193        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13194        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13195        if (!verticalEdges && !horizontalEdges) {
13196            // Step 3, draw the content
13197            if (!dirtyOpaque) onDraw(canvas);
13198
13199            // Step 4, draw the children
13200            dispatchDraw(canvas);
13201
13202            // Step 6, draw decorations (scrollbars)
13203            onDrawScrollBars(canvas);
13204
13205            // we're done...
13206            return;
13207        }
13208
13209        /*
13210         * Here we do the full fledged routine...
13211         * (this is an uncommon case where speed matters less,
13212         * this is why we repeat some of the tests that have been
13213         * done above)
13214         */
13215
13216        boolean drawTop = false;
13217        boolean drawBottom = false;
13218        boolean drawLeft = false;
13219        boolean drawRight = false;
13220
13221        float topFadeStrength = 0.0f;
13222        float bottomFadeStrength = 0.0f;
13223        float leftFadeStrength = 0.0f;
13224        float rightFadeStrength = 0.0f;
13225
13226        // Step 2, save the canvas' layers
13227        int paddingLeft = mPaddingLeft;
13228
13229        final boolean offsetRequired = isPaddingOffsetRequired();
13230        if (offsetRequired) {
13231            paddingLeft += getLeftPaddingOffset();
13232        }
13233
13234        int left = mScrollX + paddingLeft;
13235        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13236        int top = mScrollY + getFadeTop(offsetRequired);
13237        int bottom = top + getFadeHeight(offsetRequired);
13238
13239        if (offsetRequired) {
13240            right += getRightPaddingOffset();
13241            bottom += getBottomPaddingOffset();
13242        }
13243
13244        final ScrollabilityCache scrollabilityCache = mScrollCache;
13245        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13246        int length = (int) fadeHeight;
13247
13248        // clip the fade length if top and bottom fades overlap
13249        // overlapping fades produce odd-looking artifacts
13250        if (verticalEdges && (top + length > bottom - length)) {
13251            length = (bottom - top) / 2;
13252        }
13253
13254        // also clip horizontal fades if necessary
13255        if (horizontalEdges && (left + length > right - length)) {
13256            length = (right - left) / 2;
13257        }
13258
13259        if (verticalEdges) {
13260            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13261            drawTop = topFadeStrength * fadeHeight > 1.0f;
13262            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13263            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13264        }
13265
13266        if (horizontalEdges) {
13267            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13268            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13269            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13270            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13271        }
13272
13273        saveCount = canvas.getSaveCount();
13274
13275        int solidColor = getSolidColor();
13276        if (solidColor == 0) {
13277            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13278
13279            if (drawTop) {
13280                canvas.saveLayer(left, top, right, top + length, null, flags);
13281            }
13282
13283            if (drawBottom) {
13284                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13285            }
13286
13287            if (drawLeft) {
13288                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13289            }
13290
13291            if (drawRight) {
13292                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13293            }
13294        } else {
13295            scrollabilityCache.setFadeColor(solidColor);
13296        }
13297
13298        // Step 3, draw the content
13299        if (!dirtyOpaque) onDraw(canvas);
13300
13301        // Step 4, draw the children
13302        dispatchDraw(canvas);
13303
13304        // Step 5, draw the fade effect and restore layers
13305        final Paint p = scrollabilityCache.paint;
13306        final Matrix matrix = scrollabilityCache.matrix;
13307        final Shader fade = scrollabilityCache.shader;
13308
13309        if (drawTop) {
13310            matrix.setScale(1, fadeHeight * topFadeStrength);
13311            matrix.postTranslate(left, top);
13312            fade.setLocalMatrix(matrix);
13313            canvas.drawRect(left, top, right, top + length, p);
13314        }
13315
13316        if (drawBottom) {
13317            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13318            matrix.postRotate(180);
13319            matrix.postTranslate(left, bottom);
13320            fade.setLocalMatrix(matrix);
13321            canvas.drawRect(left, bottom - length, right, bottom, p);
13322        }
13323
13324        if (drawLeft) {
13325            matrix.setScale(1, fadeHeight * leftFadeStrength);
13326            matrix.postRotate(-90);
13327            matrix.postTranslate(left, top);
13328            fade.setLocalMatrix(matrix);
13329            canvas.drawRect(left, top, left + length, bottom, p);
13330        }
13331
13332        if (drawRight) {
13333            matrix.setScale(1, fadeHeight * rightFadeStrength);
13334            matrix.postRotate(90);
13335            matrix.postTranslate(right, top);
13336            fade.setLocalMatrix(matrix);
13337            canvas.drawRect(right - length, top, right, bottom, p);
13338        }
13339
13340        canvas.restoreToCount(saveCount);
13341
13342        // Step 6, draw decorations (scrollbars)
13343        onDrawScrollBars(canvas);
13344    }
13345
13346    /**
13347     * Override this if your view is known to always be drawn on top of a solid color background,
13348     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13349     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13350     * should be set to 0xFF.
13351     *
13352     * @see #setVerticalFadingEdgeEnabled(boolean)
13353     * @see #setHorizontalFadingEdgeEnabled(boolean)
13354     *
13355     * @return The known solid color background for this view, or 0 if the color may vary
13356     */
13357    @ViewDebug.ExportedProperty(category = "drawing")
13358    public int getSolidColor() {
13359        return 0;
13360    }
13361
13362    /**
13363     * Build a human readable string representation of the specified view flags.
13364     *
13365     * @param flags the view flags to convert to a string
13366     * @return a String representing the supplied flags
13367     */
13368    private static String printFlags(int flags) {
13369        String output = "";
13370        int numFlags = 0;
13371        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13372            output += "TAKES_FOCUS";
13373            numFlags++;
13374        }
13375
13376        switch (flags & VISIBILITY_MASK) {
13377        case INVISIBLE:
13378            if (numFlags > 0) {
13379                output += " ";
13380            }
13381            output += "INVISIBLE";
13382            // USELESS HERE numFlags++;
13383            break;
13384        case GONE:
13385            if (numFlags > 0) {
13386                output += " ";
13387            }
13388            output += "GONE";
13389            // USELESS HERE numFlags++;
13390            break;
13391        default:
13392            break;
13393        }
13394        return output;
13395    }
13396
13397    /**
13398     * Build a human readable string representation of the specified private
13399     * view flags.
13400     *
13401     * @param privateFlags the private view flags to convert to a string
13402     * @return a String representing the supplied flags
13403     */
13404    private static String printPrivateFlags(int privateFlags) {
13405        String output = "";
13406        int numFlags = 0;
13407
13408        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13409            output += "WANTS_FOCUS";
13410            numFlags++;
13411        }
13412
13413        if ((privateFlags & FOCUSED) == FOCUSED) {
13414            if (numFlags > 0) {
13415                output += " ";
13416            }
13417            output += "FOCUSED";
13418            numFlags++;
13419        }
13420
13421        if ((privateFlags & SELECTED) == SELECTED) {
13422            if (numFlags > 0) {
13423                output += " ";
13424            }
13425            output += "SELECTED";
13426            numFlags++;
13427        }
13428
13429        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13430            if (numFlags > 0) {
13431                output += " ";
13432            }
13433            output += "IS_ROOT_NAMESPACE";
13434            numFlags++;
13435        }
13436
13437        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13438            if (numFlags > 0) {
13439                output += " ";
13440            }
13441            output += "HAS_BOUNDS";
13442            numFlags++;
13443        }
13444
13445        if ((privateFlags & DRAWN) == DRAWN) {
13446            if (numFlags > 0) {
13447                output += " ";
13448            }
13449            output += "DRAWN";
13450            // USELESS HERE numFlags++;
13451        }
13452        return output;
13453    }
13454
13455    /**
13456     * <p>Indicates whether or not this view's layout will be requested during
13457     * the next hierarchy layout pass.</p>
13458     *
13459     * @return true if the layout will be forced during next layout pass
13460     */
13461    public boolean isLayoutRequested() {
13462        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13463    }
13464
13465    /**
13466     * Assign a size and position to a view and all of its
13467     * descendants
13468     *
13469     * <p>This is the second phase of the layout mechanism.
13470     * (The first is measuring). In this phase, each parent calls
13471     * layout on all of its children to position them.
13472     * This is typically done using the child measurements
13473     * that were stored in the measure pass().</p>
13474     *
13475     * <p>Derived classes should not override this method.
13476     * Derived classes with children should override
13477     * onLayout. In that method, they should
13478     * call layout on each of their children.</p>
13479     *
13480     * @param l Left position, relative to parent
13481     * @param t Top position, relative to parent
13482     * @param r Right position, relative to parent
13483     * @param b Bottom position, relative to parent
13484     */
13485    @SuppressWarnings({"unchecked"})
13486    public void layout(int l, int t, int r, int b) {
13487        int oldL = mLeft;
13488        int oldT = mTop;
13489        int oldB = mBottom;
13490        int oldR = mRight;
13491        boolean changed = setFrame(l, t, r, b);
13492        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13493            onLayout(changed, l, t, r, b);
13494            mPrivateFlags &= ~LAYOUT_REQUIRED;
13495
13496            ListenerInfo li = mListenerInfo;
13497            if (li != null && li.mOnLayoutChangeListeners != null) {
13498                ArrayList<OnLayoutChangeListener> listenersCopy =
13499                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13500                int numListeners = listenersCopy.size();
13501                for (int i = 0; i < numListeners; ++i) {
13502                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13503                }
13504            }
13505        }
13506        mPrivateFlags &= ~FORCE_LAYOUT;
13507    }
13508
13509    /**
13510     * Called from layout when this view should
13511     * assign a size and position to each of its children.
13512     *
13513     * Derived classes with children should override
13514     * this method and call layout on each of
13515     * their children.
13516     * @param changed This is a new size or position for this view
13517     * @param left Left position, relative to parent
13518     * @param top Top position, relative to parent
13519     * @param right Right position, relative to parent
13520     * @param bottom Bottom position, relative to parent
13521     */
13522    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13523    }
13524
13525    /**
13526     * Assign a size and position to this view.
13527     *
13528     * This is called from layout.
13529     *
13530     * @param left Left position, relative to parent
13531     * @param top Top position, relative to parent
13532     * @param right Right position, relative to parent
13533     * @param bottom Bottom position, relative to parent
13534     * @return true if the new size and position are different than the
13535     *         previous ones
13536     * {@hide}
13537     */
13538    protected boolean setFrame(int left, int top, int right, int bottom) {
13539        boolean changed = false;
13540
13541        if (DBG) {
13542            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13543                    + right + "," + bottom + ")");
13544        }
13545
13546        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13547            changed = true;
13548
13549            // Remember our drawn bit
13550            int drawn = mPrivateFlags & DRAWN;
13551
13552            int oldWidth = mRight - mLeft;
13553            int oldHeight = mBottom - mTop;
13554            int newWidth = right - left;
13555            int newHeight = bottom - top;
13556            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13557
13558            // Invalidate our old position
13559            invalidate(sizeChanged);
13560
13561            mLeft = left;
13562            mTop = top;
13563            mRight = right;
13564            mBottom = bottom;
13565            if (mDisplayList != null) {
13566                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13567            }
13568
13569            mPrivateFlags |= HAS_BOUNDS;
13570
13571
13572            if (sizeChanged) {
13573                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13574                    // A change in dimension means an auto-centered pivot point changes, too
13575                    if (mTransformationInfo != null) {
13576                        mTransformationInfo.mMatrixDirty = true;
13577                    }
13578                }
13579                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13580            }
13581
13582            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13583                // If we are visible, force the DRAWN bit to on so that
13584                // this invalidate will go through (at least to our parent).
13585                // This is because someone may have invalidated this view
13586                // before this call to setFrame came in, thereby clearing
13587                // the DRAWN bit.
13588                mPrivateFlags |= DRAWN;
13589                invalidate(sizeChanged);
13590                // parent display list may need to be recreated based on a change in the bounds
13591                // of any child
13592                invalidateParentCaches();
13593            }
13594
13595            // Reset drawn bit to original value (invalidate turns it off)
13596            mPrivateFlags |= drawn;
13597
13598            mBackgroundSizeChanged = true;
13599        }
13600        return changed;
13601    }
13602
13603    /**
13604     * Finalize inflating a view from XML.  This is called as the last phase
13605     * of inflation, after all child views have been added.
13606     *
13607     * <p>Even if the subclass overrides onFinishInflate, they should always be
13608     * sure to call the super method, so that we get called.
13609     */
13610    protected void onFinishInflate() {
13611    }
13612
13613    /**
13614     * Returns the resources associated with this view.
13615     *
13616     * @return Resources object.
13617     */
13618    public Resources getResources() {
13619        return mResources;
13620    }
13621
13622    /**
13623     * Invalidates the specified Drawable.
13624     *
13625     * @param drawable the drawable to invalidate
13626     */
13627    public void invalidateDrawable(Drawable drawable) {
13628        if (verifyDrawable(drawable)) {
13629            final Rect dirty = drawable.getBounds();
13630            final int scrollX = mScrollX;
13631            final int scrollY = mScrollY;
13632
13633            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13634                    dirty.right + scrollX, dirty.bottom + scrollY);
13635        }
13636    }
13637
13638    /**
13639     * Schedules an action on a drawable to occur at a specified time.
13640     *
13641     * @param who the recipient of the action
13642     * @param what the action to run on the drawable
13643     * @param when the time at which the action must occur. Uses the
13644     *        {@link SystemClock#uptimeMillis} timebase.
13645     */
13646    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13647        if (verifyDrawable(who) && what != null) {
13648            final long delay = when - SystemClock.uptimeMillis();
13649            if (mAttachInfo != null) {
13650                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13651                        Choreographer.CALLBACK_ANIMATION, what, who,
13652                        Choreographer.subtractFrameDelay(delay));
13653            } else {
13654                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13655            }
13656        }
13657    }
13658
13659    /**
13660     * Cancels a scheduled action on a drawable.
13661     *
13662     * @param who the recipient of the action
13663     * @param what the action to cancel
13664     */
13665    public void unscheduleDrawable(Drawable who, Runnable what) {
13666        if (verifyDrawable(who) && what != null) {
13667            if (mAttachInfo != null) {
13668                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13669                        Choreographer.CALLBACK_ANIMATION, what, who);
13670            } else {
13671                ViewRootImpl.getRunQueue().removeCallbacks(what);
13672            }
13673        }
13674    }
13675
13676    /**
13677     * Unschedule any events associated with the given Drawable.  This can be
13678     * used when selecting a new Drawable into a view, so that the previous
13679     * one is completely unscheduled.
13680     *
13681     * @param who The Drawable to unschedule.
13682     *
13683     * @see #drawableStateChanged
13684     */
13685    public void unscheduleDrawable(Drawable who) {
13686        if (mAttachInfo != null && who != null) {
13687            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13688                    Choreographer.CALLBACK_ANIMATION, null, who);
13689        }
13690    }
13691
13692    /**
13693    * Return the layout direction of a given Drawable.
13694    *
13695    * @param who the Drawable to query
13696    */
13697    public int getResolvedLayoutDirection(Drawable who) {
13698        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13699    }
13700
13701    /**
13702     * If your view subclass is displaying its own Drawable objects, it should
13703     * override this function and return true for any Drawable it is
13704     * displaying.  This allows animations for those drawables to be
13705     * scheduled.
13706     *
13707     * <p>Be sure to call through to the super class when overriding this
13708     * function.
13709     *
13710     * @param who The Drawable to verify.  Return true if it is one you are
13711     *            displaying, else return the result of calling through to the
13712     *            super class.
13713     *
13714     * @return boolean If true than the Drawable is being displayed in the
13715     *         view; else false and it is not allowed to animate.
13716     *
13717     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13718     * @see #drawableStateChanged()
13719     */
13720    protected boolean verifyDrawable(Drawable who) {
13721        return who == mBackground;
13722    }
13723
13724    /**
13725     * This function is called whenever the state of the view changes in such
13726     * a way that it impacts the state of drawables being shown.
13727     *
13728     * <p>Be sure to call through to the superclass when overriding this
13729     * function.
13730     *
13731     * @see Drawable#setState(int[])
13732     */
13733    protected void drawableStateChanged() {
13734        Drawable d = mBackground;
13735        if (d != null && d.isStateful()) {
13736            d.setState(getDrawableState());
13737        }
13738    }
13739
13740    /**
13741     * Call this to force a view to update its drawable state. This will cause
13742     * drawableStateChanged to be called on this view. Views that are interested
13743     * in the new state should call getDrawableState.
13744     *
13745     * @see #drawableStateChanged
13746     * @see #getDrawableState
13747     */
13748    public void refreshDrawableState() {
13749        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13750        drawableStateChanged();
13751
13752        ViewParent parent = mParent;
13753        if (parent != null) {
13754            parent.childDrawableStateChanged(this);
13755        }
13756    }
13757
13758    /**
13759     * Return an array of resource IDs of the drawable states representing the
13760     * current state of the view.
13761     *
13762     * @return The current drawable state
13763     *
13764     * @see Drawable#setState(int[])
13765     * @see #drawableStateChanged()
13766     * @see #onCreateDrawableState(int)
13767     */
13768    public final int[] getDrawableState() {
13769        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13770            return mDrawableState;
13771        } else {
13772            mDrawableState = onCreateDrawableState(0);
13773            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13774            return mDrawableState;
13775        }
13776    }
13777
13778    /**
13779     * Generate the new {@link android.graphics.drawable.Drawable} state for
13780     * this view. This is called by the view
13781     * system when the cached Drawable state is determined to be invalid.  To
13782     * retrieve the current state, you should use {@link #getDrawableState}.
13783     *
13784     * @param extraSpace if non-zero, this is the number of extra entries you
13785     * would like in the returned array in which you can place your own
13786     * states.
13787     *
13788     * @return Returns an array holding the current {@link Drawable} state of
13789     * the view.
13790     *
13791     * @see #mergeDrawableStates(int[], int[])
13792     */
13793    protected int[] onCreateDrawableState(int extraSpace) {
13794        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13795                mParent instanceof View) {
13796            return ((View) mParent).onCreateDrawableState(extraSpace);
13797        }
13798
13799        int[] drawableState;
13800
13801        int privateFlags = mPrivateFlags;
13802
13803        int viewStateIndex = 0;
13804        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13805        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13806        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13807        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13808        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13809        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13810        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13811                HardwareRenderer.isAvailable()) {
13812            // This is set if HW acceleration is requested, even if the current
13813            // process doesn't allow it.  This is just to allow app preview
13814            // windows to better match their app.
13815            viewStateIndex |= VIEW_STATE_ACCELERATED;
13816        }
13817        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13818
13819        final int privateFlags2 = mPrivateFlags2;
13820        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13821        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13822
13823        drawableState = VIEW_STATE_SETS[viewStateIndex];
13824
13825        //noinspection ConstantIfStatement
13826        if (false) {
13827            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13828            Log.i("View", toString()
13829                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13830                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13831                    + " fo=" + hasFocus()
13832                    + " sl=" + ((privateFlags & SELECTED) != 0)
13833                    + " wf=" + hasWindowFocus()
13834                    + ": " + Arrays.toString(drawableState));
13835        }
13836
13837        if (extraSpace == 0) {
13838            return drawableState;
13839        }
13840
13841        final int[] fullState;
13842        if (drawableState != null) {
13843            fullState = new int[drawableState.length + extraSpace];
13844            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13845        } else {
13846            fullState = new int[extraSpace];
13847        }
13848
13849        return fullState;
13850    }
13851
13852    /**
13853     * Merge your own state values in <var>additionalState</var> into the base
13854     * state values <var>baseState</var> that were returned by
13855     * {@link #onCreateDrawableState(int)}.
13856     *
13857     * @param baseState The base state values returned by
13858     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13859     * own additional state values.
13860     *
13861     * @param additionalState The additional state values you would like
13862     * added to <var>baseState</var>; this array is not modified.
13863     *
13864     * @return As a convenience, the <var>baseState</var> array you originally
13865     * passed into the function is returned.
13866     *
13867     * @see #onCreateDrawableState(int)
13868     */
13869    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13870        final int N = baseState.length;
13871        int i = N - 1;
13872        while (i >= 0 && baseState[i] == 0) {
13873            i--;
13874        }
13875        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13876        return baseState;
13877    }
13878
13879    /**
13880     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13881     * on all Drawable objects associated with this view.
13882     */
13883    public void jumpDrawablesToCurrentState() {
13884        if (mBackground != null) {
13885            mBackground.jumpToCurrentState();
13886        }
13887    }
13888
13889    /**
13890     * Sets the background color for this view.
13891     * @param color the color of the background
13892     */
13893    @RemotableViewMethod
13894    public void setBackgroundColor(int color) {
13895        if (mBackground instanceof ColorDrawable) {
13896            ((ColorDrawable) mBackground).setColor(color);
13897        } else {
13898            setBackground(new ColorDrawable(color));
13899        }
13900    }
13901
13902    /**
13903     * Set the background to a given resource. The resource should refer to
13904     * a Drawable object or 0 to remove the background.
13905     * @param resid The identifier of the resource.
13906     *
13907     * @attr ref android.R.styleable#View_background
13908     */
13909    @RemotableViewMethod
13910    public void setBackgroundResource(int resid) {
13911        if (resid != 0 && resid == mBackgroundResource) {
13912            return;
13913        }
13914
13915        Drawable d= null;
13916        if (resid != 0) {
13917            d = mResources.getDrawable(resid);
13918        }
13919        setBackground(d);
13920
13921        mBackgroundResource = resid;
13922    }
13923
13924    /**
13925     * Set the background to a given Drawable, or remove the background. If the
13926     * background has padding, this View's padding is set to the background's
13927     * padding. However, when a background is removed, this View's padding isn't
13928     * touched. If setting the padding is desired, please use
13929     * {@link #setPadding(int, int, int, int)}.
13930     *
13931     * @param background The Drawable to use as the background, or null to remove the
13932     *        background
13933     */
13934    public void setBackground(Drawable background) {
13935        //noinspection deprecation
13936        setBackgroundDrawable(background);
13937    }
13938
13939    /**
13940     * @deprecated use {@link #setBackground(Drawable)} instead
13941     */
13942    @Deprecated
13943    public void setBackgroundDrawable(Drawable background) {
13944        if (background == mBackground) {
13945            return;
13946        }
13947
13948        boolean requestLayout = false;
13949
13950        mBackgroundResource = 0;
13951
13952        /*
13953         * Regardless of whether we're setting a new background or not, we want
13954         * to clear the previous drawable.
13955         */
13956        if (mBackground != null) {
13957            mBackground.setCallback(null);
13958            unscheduleDrawable(mBackground);
13959        }
13960
13961        if (background != null) {
13962            Rect padding = sThreadLocal.get();
13963            if (padding == null) {
13964                padding = new Rect();
13965                sThreadLocal.set(padding);
13966            }
13967            if (background.getPadding(padding)) {
13968                switch (background.getResolvedLayoutDirectionSelf()) {
13969                    case LAYOUT_DIRECTION_RTL:
13970                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13971                        break;
13972                    case LAYOUT_DIRECTION_LTR:
13973                    default:
13974                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13975                }
13976            }
13977
13978            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13979            // if it has a different minimum size, we should layout again
13980            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13981                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13982                requestLayout = true;
13983            }
13984
13985            background.setCallback(this);
13986            if (background.isStateful()) {
13987                background.setState(getDrawableState());
13988            }
13989            background.setVisible(getVisibility() == VISIBLE, false);
13990            mBackground = background;
13991
13992            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13993                mPrivateFlags &= ~SKIP_DRAW;
13994                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13995                requestLayout = true;
13996            }
13997        } else {
13998            /* Remove the background */
13999            mBackground = null;
14000
14001            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14002                /*
14003                 * This view ONLY drew the background before and we're removing
14004                 * the background, so now it won't draw anything
14005                 * (hence we SKIP_DRAW)
14006                 */
14007                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14008                mPrivateFlags |= SKIP_DRAW;
14009            }
14010
14011            /*
14012             * When the background is set, we try to apply its padding to this
14013             * View. When the background is removed, we don't touch this View's
14014             * padding. This is noted in the Javadocs. Hence, we don't need to
14015             * requestLayout(), the invalidate() below is sufficient.
14016             */
14017
14018            // The old background's minimum size could have affected this
14019            // View's layout, so let's requestLayout
14020            requestLayout = true;
14021        }
14022
14023        computeOpaqueFlags();
14024
14025        if (requestLayout) {
14026            requestLayout();
14027        }
14028
14029        mBackgroundSizeChanged = true;
14030        invalidate(true);
14031    }
14032
14033    /**
14034     * Gets the background drawable
14035     *
14036     * @return The drawable used as the background for this view, if any.
14037     *
14038     * @see #setBackground(Drawable)
14039     *
14040     * @attr ref android.R.styleable#View_background
14041     */
14042    public Drawable getBackground() {
14043        return mBackground;
14044    }
14045
14046    /**
14047     * Sets the padding. The view may add on the space required to display
14048     * the scrollbars, depending on the style and visibility of the scrollbars.
14049     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14050     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14051     * from the values set in this call.
14052     *
14053     * @attr ref android.R.styleable#View_padding
14054     * @attr ref android.R.styleable#View_paddingBottom
14055     * @attr ref android.R.styleable#View_paddingLeft
14056     * @attr ref android.R.styleable#View_paddingRight
14057     * @attr ref android.R.styleable#View_paddingTop
14058     * @param left the left padding in pixels
14059     * @param top the top padding in pixels
14060     * @param right the right padding in pixels
14061     * @param bottom the bottom padding in pixels
14062     */
14063    public void setPadding(int left, int top, int right, int bottom) {
14064        mUserPaddingStart = -1;
14065        mUserPaddingEnd = -1;
14066        mUserPaddingRelative = false;
14067
14068        internalSetPadding(left, top, right, bottom);
14069    }
14070
14071    private void internalSetPadding(int left, int top, int right, int bottom) {
14072        mUserPaddingLeft = left;
14073        mUserPaddingRight = right;
14074        mUserPaddingBottom = bottom;
14075
14076        final int viewFlags = mViewFlags;
14077        boolean changed = false;
14078
14079        // Common case is there are no scroll bars.
14080        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14081            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14082                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14083                        ? 0 : getVerticalScrollbarWidth();
14084                switch (mVerticalScrollbarPosition) {
14085                    case SCROLLBAR_POSITION_DEFAULT:
14086                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14087                            left += offset;
14088                        } else {
14089                            right += offset;
14090                        }
14091                        break;
14092                    case SCROLLBAR_POSITION_RIGHT:
14093                        right += offset;
14094                        break;
14095                    case SCROLLBAR_POSITION_LEFT:
14096                        left += offset;
14097                        break;
14098                }
14099            }
14100            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14101                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14102                        ? 0 : getHorizontalScrollbarHeight();
14103            }
14104        }
14105
14106        if (mPaddingLeft != left) {
14107            changed = true;
14108            mPaddingLeft = left;
14109        }
14110        if (mPaddingTop != top) {
14111            changed = true;
14112            mPaddingTop = top;
14113        }
14114        if (mPaddingRight != right) {
14115            changed = true;
14116            mPaddingRight = right;
14117        }
14118        if (mPaddingBottom != bottom) {
14119            changed = true;
14120            mPaddingBottom = bottom;
14121        }
14122
14123        if (changed) {
14124            requestLayout();
14125        }
14126    }
14127
14128    /**
14129     * Sets the relative padding. The view may add on the space required to display
14130     * the scrollbars, depending on the style and visibility of the scrollbars.
14131     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14132     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14133     * from the values set in this call.
14134     *
14135     * @attr ref android.R.styleable#View_padding
14136     * @attr ref android.R.styleable#View_paddingBottom
14137     * @attr ref android.R.styleable#View_paddingStart
14138     * @attr ref android.R.styleable#View_paddingEnd
14139     * @attr ref android.R.styleable#View_paddingTop
14140     * @param start the start padding in pixels
14141     * @param top the top padding in pixels
14142     * @param end the end padding in pixels
14143     * @param bottom the bottom padding in pixels
14144     */
14145    public void setPaddingRelative(int start, int top, int end, int bottom) {
14146        mUserPaddingStart = start;
14147        mUserPaddingEnd = end;
14148        mUserPaddingRelative = true;
14149
14150        switch(getResolvedLayoutDirection()) {
14151            case LAYOUT_DIRECTION_RTL:
14152                internalSetPadding(end, top, start, bottom);
14153                break;
14154            case LAYOUT_DIRECTION_LTR:
14155            default:
14156                internalSetPadding(start, top, end, bottom);
14157        }
14158    }
14159
14160    /**
14161     * Returns the top padding of this view.
14162     *
14163     * @return the top padding in pixels
14164     */
14165    public int getPaddingTop() {
14166        return mPaddingTop;
14167    }
14168
14169    /**
14170     * Returns the bottom padding of this view. If there are inset and enabled
14171     * scrollbars, this value may include the space required to display the
14172     * scrollbars as well.
14173     *
14174     * @return the bottom padding in pixels
14175     */
14176    public int getPaddingBottom() {
14177        return mPaddingBottom;
14178    }
14179
14180    /**
14181     * Returns the left padding of this view. If there are inset and enabled
14182     * scrollbars, this value may include the space required to display the
14183     * scrollbars as well.
14184     *
14185     * @return the left padding in pixels
14186     */
14187    public int getPaddingLeft() {
14188        return mPaddingLeft;
14189    }
14190
14191    /**
14192     * Returns the start padding of this view depending on its resolved layout direction.
14193     * If there are inset and enabled scrollbars, this value may include the space
14194     * required to display the scrollbars as well.
14195     *
14196     * @return the start padding in pixels
14197     */
14198    public int getPaddingStart() {
14199        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14200                mPaddingRight : mPaddingLeft;
14201    }
14202
14203    /**
14204     * Returns the right padding of this view. If there are inset and enabled
14205     * scrollbars, this value may include the space required to display the
14206     * scrollbars as well.
14207     *
14208     * @return the right padding in pixels
14209     */
14210    public int getPaddingRight() {
14211        return mPaddingRight;
14212    }
14213
14214    /**
14215     * Returns the end padding of this view depending on its resolved layout direction.
14216     * If there are inset and enabled scrollbars, this value may include the space
14217     * required to display the scrollbars as well.
14218     *
14219     * @return the end padding in pixels
14220     */
14221    public int getPaddingEnd() {
14222        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14223                mPaddingLeft : mPaddingRight;
14224    }
14225
14226    /**
14227     * Return if the padding as been set thru relative values
14228     * {@link #setPaddingRelative(int, int, int, int)} or thru
14229     * @attr ref android.R.styleable#View_paddingStart or
14230     * @attr ref android.R.styleable#View_paddingEnd
14231     *
14232     * @return true if the padding is relative or false if it is not.
14233     */
14234    public boolean isPaddingRelative() {
14235        return mUserPaddingRelative;
14236    }
14237
14238    /**
14239     * @hide
14240     */
14241    public Insets getOpticalInsets() {
14242        if (mLayoutInsets == null) {
14243            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14244        }
14245        return mLayoutInsets;
14246    }
14247
14248    /**
14249     * @hide
14250     */
14251    public void setLayoutInsets(Insets layoutInsets) {
14252        mLayoutInsets = layoutInsets;
14253    }
14254
14255    /**
14256     * Changes the selection state of this view. A view can be selected or not.
14257     * Note that selection is not the same as focus. Views are typically
14258     * selected in the context of an AdapterView like ListView or GridView;
14259     * the selected view is the view that is highlighted.
14260     *
14261     * @param selected true if the view must be selected, false otherwise
14262     */
14263    public void setSelected(boolean selected) {
14264        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14265            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14266            if (!selected) resetPressedState();
14267            invalidate(true);
14268            refreshDrawableState();
14269            dispatchSetSelected(selected);
14270            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14271                notifyAccessibilityStateChanged();
14272            }
14273        }
14274    }
14275
14276    /**
14277     * Dispatch setSelected to all of this View's children.
14278     *
14279     * @see #setSelected(boolean)
14280     *
14281     * @param selected The new selected state
14282     */
14283    protected void dispatchSetSelected(boolean selected) {
14284    }
14285
14286    /**
14287     * Indicates the selection state of this view.
14288     *
14289     * @return true if the view is selected, false otherwise
14290     */
14291    @ViewDebug.ExportedProperty
14292    public boolean isSelected() {
14293        return (mPrivateFlags & SELECTED) != 0;
14294    }
14295
14296    /**
14297     * Changes the activated state of this view. A view can be activated or not.
14298     * Note that activation is not the same as selection.  Selection is
14299     * a transient property, representing the view (hierarchy) the user is
14300     * currently interacting with.  Activation is a longer-term state that the
14301     * user can move views in and out of.  For example, in a list view with
14302     * single or multiple selection enabled, the views in the current selection
14303     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14304     * here.)  The activated state is propagated down to children of the view it
14305     * is set on.
14306     *
14307     * @param activated true if the view must be activated, false otherwise
14308     */
14309    public void setActivated(boolean activated) {
14310        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14311            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14312            invalidate(true);
14313            refreshDrawableState();
14314            dispatchSetActivated(activated);
14315        }
14316    }
14317
14318    /**
14319     * Dispatch setActivated to all of this View's children.
14320     *
14321     * @see #setActivated(boolean)
14322     *
14323     * @param activated The new activated state
14324     */
14325    protected void dispatchSetActivated(boolean activated) {
14326    }
14327
14328    /**
14329     * Indicates the activation state of this view.
14330     *
14331     * @return true if the view is activated, false otherwise
14332     */
14333    @ViewDebug.ExportedProperty
14334    public boolean isActivated() {
14335        return (mPrivateFlags & ACTIVATED) != 0;
14336    }
14337
14338    /**
14339     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14340     * observer can be used to get notifications when global events, like
14341     * layout, happen.
14342     *
14343     * The returned ViewTreeObserver observer is not guaranteed to remain
14344     * valid for the lifetime of this View. If the caller of this method keeps
14345     * a long-lived reference to ViewTreeObserver, it should always check for
14346     * the return value of {@link ViewTreeObserver#isAlive()}.
14347     *
14348     * @return The ViewTreeObserver for this view's hierarchy.
14349     */
14350    public ViewTreeObserver getViewTreeObserver() {
14351        if (mAttachInfo != null) {
14352            return mAttachInfo.mTreeObserver;
14353        }
14354        if (mFloatingTreeObserver == null) {
14355            mFloatingTreeObserver = new ViewTreeObserver();
14356        }
14357        return mFloatingTreeObserver;
14358    }
14359
14360    /**
14361     * <p>Finds the topmost view in the current view hierarchy.</p>
14362     *
14363     * @return the topmost view containing this view
14364     */
14365    public View getRootView() {
14366        if (mAttachInfo != null) {
14367            final View v = mAttachInfo.mRootView;
14368            if (v != null) {
14369                return v;
14370            }
14371        }
14372
14373        View parent = this;
14374
14375        while (parent.mParent != null && parent.mParent instanceof View) {
14376            parent = (View) parent.mParent;
14377        }
14378
14379        return parent;
14380    }
14381
14382    /**
14383     * <p>Computes the coordinates of this view on the screen. The argument
14384     * must be an array of two integers. After the method returns, the array
14385     * contains the x and y location in that order.</p>
14386     *
14387     * @param location an array of two integers in which to hold the coordinates
14388     */
14389    public void getLocationOnScreen(int[] location) {
14390        getLocationInWindow(location);
14391
14392        final AttachInfo info = mAttachInfo;
14393        if (info != null) {
14394            location[0] += info.mWindowLeft;
14395            location[1] += info.mWindowTop;
14396        }
14397    }
14398
14399    /**
14400     * <p>Computes the coordinates of this view in its window. The argument
14401     * must be an array of two integers. After the method returns, the array
14402     * contains the x and y location in that order.</p>
14403     *
14404     * @param location an array of two integers in which to hold the coordinates
14405     */
14406    public void getLocationInWindow(int[] location) {
14407        if (location == null || location.length < 2) {
14408            throw new IllegalArgumentException("location must be an array of two integers");
14409        }
14410
14411        if (mAttachInfo == null) {
14412            // When the view is not attached to a window, this method does not make sense
14413            location[0] = location[1] = 0;
14414            return;
14415        }
14416
14417        float[] position = mAttachInfo.mTmpTransformLocation;
14418        position[0] = position[1] = 0.0f;
14419
14420        if (!hasIdentityMatrix()) {
14421            getMatrix().mapPoints(position);
14422        }
14423
14424        position[0] += mLeft;
14425        position[1] += mTop;
14426
14427        ViewParent viewParent = mParent;
14428        while (viewParent instanceof View) {
14429            final View view = (View) viewParent;
14430
14431            position[0] -= view.mScrollX;
14432            position[1] -= view.mScrollY;
14433
14434            if (!view.hasIdentityMatrix()) {
14435                view.getMatrix().mapPoints(position);
14436            }
14437
14438            position[0] += view.mLeft;
14439            position[1] += view.mTop;
14440
14441            viewParent = view.mParent;
14442         }
14443
14444        if (viewParent instanceof ViewRootImpl) {
14445            // *cough*
14446            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14447            position[1] -= vr.mCurScrollY;
14448        }
14449
14450        location[0] = (int) (position[0] + 0.5f);
14451        location[1] = (int) (position[1] + 0.5f);
14452    }
14453
14454    /**
14455     * {@hide}
14456     * @param id the id of the view to be found
14457     * @return the view of the specified id, null if cannot be found
14458     */
14459    protected View findViewTraversal(int id) {
14460        if (id == mID) {
14461            return this;
14462        }
14463        return null;
14464    }
14465
14466    /**
14467     * {@hide}
14468     * @param tag the tag of the view to be found
14469     * @return the view of specified tag, null if cannot be found
14470     */
14471    protected View findViewWithTagTraversal(Object tag) {
14472        if (tag != null && tag.equals(mTag)) {
14473            return this;
14474        }
14475        return null;
14476    }
14477
14478    /**
14479     * {@hide}
14480     * @param predicate The predicate to evaluate.
14481     * @param childToSkip If not null, ignores this child during the recursive traversal.
14482     * @return The first view that matches the predicate or null.
14483     */
14484    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14485        if (predicate.apply(this)) {
14486            return this;
14487        }
14488        return null;
14489    }
14490
14491    /**
14492     * Look for a child view with the given id.  If this view has the given
14493     * id, return this view.
14494     *
14495     * @param id The id to search for.
14496     * @return The view that has the given id in the hierarchy or null
14497     */
14498    public final View findViewById(int id) {
14499        if (id < 0) {
14500            return null;
14501        }
14502        return findViewTraversal(id);
14503    }
14504
14505    /**
14506     * Finds a view by its unuque and stable accessibility id.
14507     *
14508     * @param accessibilityId The searched accessibility id.
14509     * @return The found view.
14510     */
14511    final View findViewByAccessibilityId(int accessibilityId) {
14512        if (accessibilityId < 0) {
14513            return null;
14514        }
14515        return findViewByAccessibilityIdTraversal(accessibilityId);
14516    }
14517
14518    /**
14519     * Performs the traversal to find a view by its unuque and stable accessibility id.
14520     *
14521     * <strong>Note:</strong>This method does not stop at the root namespace
14522     * boundary since the user can touch the screen at an arbitrary location
14523     * potentially crossing the root namespace bounday which will send an
14524     * accessibility event to accessibility services and they should be able
14525     * to obtain the event source. Also accessibility ids are guaranteed to be
14526     * unique in the window.
14527     *
14528     * @param accessibilityId The accessibility id.
14529     * @return The found view.
14530     */
14531    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14532        if (getAccessibilityViewId() == accessibilityId) {
14533            return this;
14534        }
14535        return null;
14536    }
14537
14538    /**
14539     * Look for a child view with the given tag.  If this view has the given
14540     * tag, return this view.
14541     *
14542     * @param tag The tag to search for, using "tag.equals(getTag())".
14543     * @return The View that has the given tag in the hierarchy or null
14544     */
14545    public final View findViewWithTag(Object tag) {
14546        if (tag == null) {
14547            return null;
14548        }
14549        return findViewWithTagTraversal(tag);
14550    }
14551
14552    /**
14553     * {@hide}
14554     * Look for a child view that matches the specified predicate.
14555     * If this view matches the predicate, return this view.
14556     *
14557     * @param predicate The predicate to evaluate.
14558     * @return The first view that matches the predicate or null.
14559     */
14560    public final View findViewByPredicate(Predicate<View> predicate) {
14561        return findViewByPredicateTraversal(predicate, null);
14562    }
14563
14564    /**
14565     * {@hide}
14566     * Look for a child view that matches the specified predicate,
14567     * starting with the specified view and its descendents and then
14568     * recusively searching the ancestors and siblings of that view
14569     * until this view is reached.
14570     *
14571     * This method is useful in cases where the predicate does not match
14572     * a single unique view (perhaps multiple views use the same id)
14573     * and we are trying to find the view that is "closest" in scope to the
14574     * starting view.
14575     *
14576     * @param start The view to start from.
14577     * @param predicate The predicate to evaluate.
14578     * @return The first view that matches the predicate or null.
14579     */
14580    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14581        View childToSkip = null;
14582        for (;;) {
14583            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14584            if (view != null || start == this) {
14585                return view;
14586            }
14587
14588            ViewParent parent = start.getParent();
14589            if (parent == null || !(parent instanceof View)) {
14590                return null;
14591            }
14592
14593            childToSkip = start;
14594            start = (View) parent;
14595        }
14596    }
14597
14598    /**
14599     * Sets the identifier for this view. The identifier does not have to be
14600     * unique in this view's hierarchy. The identifier should be a positive
14601     * number.
14602     *
14603     * @see #NO_ID
14604     * @see #getId()
14605     * @see #findViewById(int)
14606     *
14607     * @param id a number used to identify the view
14608     *
14609     * @attr ref android.R.styleable#View_id
14610     */
14611    public void setId(int id) {
14612        mID = id;
14613    }
14614
14615    /**
14616     * {@hide}
14617     *
14618     * @param isRoot true if the view belongs to the root namespace, false
14619     *        otherwise
14620     */
14621    public void setIsRootNamespace(boolean isRoot) {
14622        if (isRoot) {
14623            mPrivateFlags |= IS_ROOT_NAMESPACE;
14624        } else {
14625            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14626        }
14627    }
14628
14629    /**
14630     * {@hide}
14631     *
14632     * @return true if the view belongs to the root namespace, false otherwise
14633     */
14634    public boolean isRootNamespace() {
14635        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14636    }
14637
14638    /**
14639     * Returns this view's identifier.
14640     *
14641     * @return a positive integer used to identify the view or {@link #NO_ID}
14642     *         if the view has no ID
14643     *
14644     * @see #setId(int)
14645     * @see #findViewById(int)
14646     * @attr ref android.R.styleable#View_id
14647     */
14648    @ViewDebug.CapturedViewProperty
14649    public int getId() {
14650        return mID;
14651    }
14652
14653    /**
14654     * Returns this view's tag.
14655     *
14656     * @return the Object stored in this view as a tag
14657     *
14658     * @see #setTag(Object)
14659     * @see #getTag(int)
14660     */
14661    @ViewDebug.ExportedProperty
14662    public Object getTag() {
14663        return mTag;
14664    }
14665
14666    /**
14667     * Sets the tag associated with this view. A tag can be used to mark
14668     * a view in its hierarchy and does not have to be unique within the
14669     * hierarchy. Tags can also be used to store data within a view without
14670     * resorting to another data structure.
14671     *
14672     * @param tag an Object to tag the view with
14673     *
14674     * @see #getTag()
14675     * @see #setTag(int, Object)
14676     */
14677    public void setTag(final Object tag) {
14678        mTag = tag;
14679    }
14680
14681    /**
14682     * Returns the tag associated with this view and the specified key.
14683     *
14684     * @param key The key identifying the tag
14685     *
14686     * @return the Object stored in this view as a tag
14687     *
14688     * @see #setTag(int, Object)
14689     * @see #getTag()
14690     */
14691    public Object getTag(int key) {
14692        if (mKeyedTags != null) return mKeyedTags.get(key);
14693        return null;
14694    }
14695
14696    /**
14697     * Sets a tag associated with this view and a key. A tag can be used
14698     * to mark a view in its hierarchy and does not have to be unique within
14699     * the hierarchy. Tags can also be used to store data within a view
14700     * without resorting to another data structure.
14701     *
14702     * The specified key should be an id declared in the resources of the
14703     * application to ensure it is unique (see the <a
14704     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14705     * Keys identified as belonging to
14706     * the Android framework or not associated with any package will cause
14707     * an {@link IllegalArgumentException} to be thrown.
14708     *
14709     * @param key The key identifying the tag
14710     * @param tag An Object to tag the view with
14711     *
14712     * @throws IllegalArgumentException If they specified key is not valid
14713     *
14714     * @see #setTag(Object)
14715     * @see #getTag(int)
14716     */
14717    public void setTag(int key, final Object tag) {
14718        // If the package id is 0x00 or 0x01, it's either an undefined package
14719        // or a framework id
14720        if ((key >>> 24) < 2) {
14721            throw new IllegalArgumentException("The key must be an application-specific "
14722                    + "resource id.");
14723        }
14724
14725        setKeyedTag(key, tag);
14726    }
14727
14728    /**
14729     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14730     * framework id.
14731     *
14732     * @hide
14733     */
14734    public void setTagInternal(int key, Object tag) {
14735        if ((key >>> 24) != 0x1) {
14736            throw new IllegalArgumentException("The key must be a framework-specific "
14737                    + "resource id.");
14738        }
14739
14740        setKeyedTag(key, tag);
14741    }
14742
14743    private void setKeyedTag(int key, Object tag) {
14744        if (mKeyedTags == null) {
14745            mKeyedTags = new SparseArray<Object>();
14746        }
14747
14748        mKeyedTags.put(key, tag);
14749    }
14750
14751    /**
14752     * Prints information about this view in the log output, with the tag
14753     * {@link #VIEW_LOG_TAG}.
14754     *
14755     * @hide
14756     */
14757    public void debug() {
14758        debug(0);
14759    }
14760
14761    /**
14762     * Prints information about this view in the log output, with the tag
14763     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14764     * indentation defined by the <code>depth</code>.
14765     *
14766     * @param depth the indentation level
14767     *
14768     * @hide
14769     */
14770    protected void debug(int depth) {
14771        String output = debugIndent(depth - 1);
14772
14773        output += "+ " + this;
14774        int id = getId();
14775        if (id != -1) {
14776            output += " (id=" + id + ")";
14777        }
14778        Object tag = getTag();
14779        if (tag != null) {
14780            output += " (tag=" + tag + ")";
14781        }
14782        Log.d(VIEW_LOG_TAG, output);
14783
14784        if ((mPrivateFlags & FOCUSED) != 0) {
14785            output = debugIndent(depth) + " FOCUSED";
14786            Log.d(VIEW_LOG_TAG, output);
14787        }
14788
14789        output = debugIndent(depth);
14790        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14791                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14792                + "} ";
14793        Log.d(VIEW_LOG_TAG, output);
14794
14795        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14796                || mPaddingBottom != 0) {
14797            output = debugIndent(depth);
14798            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14799                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14800            Log.d(VIEW_LOG_TAG, output);
14801        }
14802
14803        output = debugIndent(depth);
14804        output += "mMeasureWidth=" + mMeasuredWidth +
14805                " mMeasureHeight=" + mMeasuredHeight;
14806        Log.d(VIEW_LOG_TAG, output);
14807
14808        output = debugIndent(depth);
14809        if (mLayoutParams == null) {
14810            output += "BAD! no layout params";
14811        } else {
14812            output = mLayoutParams.debug(output);
14813        }
14814        Log.d(VIEW_LOG_TAG, output);
14815
14816        output = debugIndent(depth);
14817        output += "flags={";
14818        output += View.printFlags(mViewFlags);
14819        output += "}";
14820        Log.d(VIEW_LOG_TAG, output);
14821
14822        output = debugIndent(depth);
14823        output += "privateFlags={";
14824        output += View.printPrivateFlags(mPrivateFlags);
14825        output += "}";
14826        Log.d(VIEW_LOG_TAG, output);
14827    }
14828
14829    /**
14830     * Creates a string of whitespaces used for indentation.
14831     *
14832     * @param depth the indentation level
14833     * @return a String containing (depth * 2 + 3) * 2 white spaces
14834     *
14835     * @hide
14836     */
14837    protected static String debugIndent(int depth) {
14838        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14839        for (int i = 0; i < (depth * 2) + 3; i++) {
14840            spaces.append(' ').append(' ');
14841        }
14842        return spaces.toString();
14843    }
14844
14845    /**
14846     * <p>Return the offset of the widget's text baseline from the widget's top
14847     * boundary. If this widget does not support baseline alignment, this
14848     * method returns -1. </p>
14849     *
14850     * @return the offset of the baseline within the widget's bounds or -1
14851     *         if baseline alignment is not supported
14852     */
14853    @ViewDebug.ExportedProperty(category = "layout")
14854    public int getBaseline() {
14855        return -1;
14856    }
14857
14858    /**
14859     * Call this when something has changed which has invalidated the
14860     * layout of this view. This will schedule a layout pass of the view
14861     * tree.
14862     */
14863    public void requestLayout() {
14864        mPrivateFlags |= FORCE_LAYOUT;
14865        mPrivateFlags |= INVALIDATED;
14866
14867        if (mLayoutParams != null) {
14868            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14869        }
14870
14871        if (mParent != null && !mParent.isLayoutRequested()) {
14872            mParent.requestLayout();
14873        }
14874    }
14875
14876    /**
14877     * Forces this view to be laid out during the next layout pass.
14878     * This method does not call requestLayout() or forceLayout()
14879     * on the parent.
14880     */
14881    public void forceLayout() {
14882        mPrivateFlags |= FORCE_LAYOUT;
14883        mPrivateFlags |= INVALIDATED;
14884    }
14885
14886    /**
14887     * <p>
14888     * This is called to find out how big a view should be. The parent
14889     * supplies constraint information in the width and height parameters.
14890     * </p>
14891     *
14892     * <p>
14893     * The actual measurement work of a view is performed in
14894     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14895     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14896     * </p>
14897     *
14898     *
14899     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14900     *        parent
14901     * @param heightMeasureSpec Vertical space requirements as imposed by the
14902     *        parent
14903     *
14904     * @see #onMeasure(int, int)
14905     */
14906    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14907        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14908                widthMeasureSpec != mOldWidthMeasureSpec ||
14909                heightMeasureSpec != mOldHeightMeasureSpec) {
14910
14911            // first clears the measured dimension flag
14912            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14913
14914            // measure ourselves, this should set the measured dimension flag back
14915            onMeasure(widthMeasureSpec, heightMeasureSpec);
14916
14917            // flag not set, setMeasuredDimension() was not invoked, we raise
14918            // an exception to warn the developer
14919            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14920                throw new IllegalStateException("onMeasure() did not set the"
14921                        + " measured dimension by calling"
14922                        + " setMeasuredDimension()");
14923            }
14924
14925            mPrivateFlags |= LAYOUT_REQUIRED;
14926        }
14927
14928        mOldWidthMeasureSpec = widthMeasureSpec;
14929        mOldHeightMeasureSpec = heightMeasureSpec;
14930    }
14931
14932    /**
14933     * <p>
14934     * Measure the view and its content to determine the measured width and the
14935     * measured height. This method is invoked by {@link #measure(int, int)} and
14936     * should be overriden by subclasses to provide accurate and efficient
14937     * measurement of their contents.
14938     * </p>
14939     *
14940     * <p>
14941     * <strong>CONTRACT:</strong> When overriding this method, you
14942     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14943     * measured width and height of this view. Failure to do so will trigger an
14944     * <code>IllegalStateException</code>, thrown by
14945     * {@link #measure(int, int)}. Calling the superclass'
14946     * {@link #onMeasure(int, int)} is a valid use.
14947     * </p>
14948     *
14949     * <p>
14950     * The base class implementation of measure defaults to the background size,
14951     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14952     * override {@link #onMeasure(int, int)} to provide better measurements of
14953     * their content.
14954     * </p>
14955     *
14956     * <p>
14957     * If this method is overridden, it is the subclass's responsibility to make
14958     * sure the measured height and width are at least the view's minimum height
14959     * and width ({@link #getSuggestedMinimumHeight()} and
14960     * {@link #getSuggestedMinimumWidth()}).
14961     * </p>
14962     *
14963     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14964     *                         The requirements are encoded with
14965     *                         {@link android.view.View.MeasureSpec}.
14966     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14967     *                         The requirements are encoded with
14968     *                         {@link android.view.View.MeasureSpec}.
14969     *
14970     * @see #getMeasuredWidth()
14971     * @see #getMeasuredHeight()
14972     * @see #setMeasuredDimension(int, int)
14973     * @see #getSuggestedMinimumHeight()
14974     * @see #getSuggestedMinimumWidth()
14975     * @see android.view.View.MeasureSpec#getMode(int)
14976     * @see android.view.View.MeasureSpec#getSize(int)
14977     */
14978    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14979        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14980                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14981    }
14982
14983    /**
14984     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14985     * measured width and measured height. Failing to do so will trigger an
14986     * exception at measurement time.</p>
14987     *
14988     * @param measuredWidth The measured width of this view.  May be a complex
14989     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14990     * {@link #MEASURED_STATE_TOO_SMALL}.
14991     * @param measuredHeight The measured height of this view.  May be a complex
14992     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14993     * {@link #MEASURED_STATE_TOO_SMALL}.
14994     */
14995    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14996        mMeasuredWidth = measuredWidth;
14997        mMeasuredHeight = measuredHeight;
14998
14999        mPrivateFlags |= MEASURED_DIMENSION_SET;
15000    }
15001
15002    /**
15003     * Merge two states as returned by {@link #getMeasuredState()}.
15004     * @param curState The current state as returned from a view or the result
15005     * of combining multiple views.
15006     * @param newState The new view state to combine.
15007     * @return Returns a new integer reflecting the combination of the two
15008     * states.
15009     */
15010    public static int combineMeasuredStates(int curState, int newState) {
15011        return curState | newState;
15012    }
15013
15014    /**
15015     * Version of {@link #resolveSizeAndState(int, int, int)}
15016     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15017     */
15018    public static int resolveSize(int size, int measureSpec) {
15019        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15020    }
15021
15022    /**
15023     * Utility to reconcile a desired size and state, with constraints imposed
15024     * by a MeasureSpec.  Will take the desired size, unless a different size
15025     * is imposed by the constraints.  The returned value is a compound integer,
15026     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15027     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15028     * size is smaller than the size the view wants to be.
15029     *
15030     * @param size How big the view wants to be
15031     * @param measureSpec Constraints imposed by the parent
15032     * @return Size information bit mask as defined by
15033     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15034     */
15035    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15036        int result = size;
15037        int specMode = MeasureSpec.getMode(measureSpec);
15038        int specSize =  MeasureSpec.getSize(measureSpec);
15039        switch (specMode) {
15040        case MeasureSpec.UNSPECIFIED:
15041            result = size;
15042            break;
15043        case MeasureSpec.AT_MOST:
15044            if (specSize < size) {
15045                result = specSize | MEASURED_STATE_TOO_SMALL;
15046            } else {
15047                result = size;
15048            }
15049            break;
15050        case MeasureSpec.EXACTLY:
15051            result = specSize;
15052            break;
15053        }
15054        return result | (childMeasuredState&MEASURED_STATE_MASK);
15055    }
15056
15057    /**
15058     * Utility to return a default size. Uses the supplied size if the
15059     * MeasureSpec imposed no constraints. Will get larger if allowed
15060     * by the MeasureSpec.
15061     *
15062     * @param size Default size for this view
15063     * @param measureSpec Constraints imposed by the parent
15064     * @return The size this view should be.
15065     */
15066    public static int getDefaultSize(int size, int measureSpec) {
15067        int result = size;
15068        int specMode = MeasureSpec.getMode(measureSpec);
15069        int specSize = MeasureSpec.getSize(measureSpec);
15070
15071        switch (specMode) {
15072        case MeasureSpec.UNSPECIFIED:
15073            result = size;
15074            break;
15075        case MeasureSpec.AT_MOST:
15076        case MeasureSpec.EXACTLY:
15077            result = specSize;
15078            break;
15079        }
15080        return result;
15081    }
15082
15083    /**
15084     * Returns the suggested minimum height that the view should use. This
15085     * returns the maximum of the view's minimum height
15086     * and the background's minimum height
15087     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15088     * <p>
15089     * When being used in {@link #onMeasure(int, int)}, the caller should still
15090     * ensure the returned height is within the requirements of the parent.
15091     *
15092     * @return The suggested minimum height of the view.
15093     */
15094    protected int getSuggestedMinimumHeight() {
15095        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15096
15097    }
15098
15099    /**
15100     * Returns the suggested minimum width that the view should use. This
15101     * returns the maximum of the view's minimum width)
15102     * and the background's minimum width
15103     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15104     * <p>
15105     * When being used in {@link #onMeasure(int, int)}, the caller should still
15106     * ensure the returned width is within the requirements of the parent.
15107     *
15108     * @return The suggested minimum width of the view.
15109     */
15110    protected int getSuggestedMinimumWidth() {
15111        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15112    }
15113
15114    /**
15115     * Returns the minimum height of the view.
15116     *
15117     * @return the minimum height the view will try to be.
15118     *
15119     * @see #setMinimumHeight(int)
15120     *
15121     * @attr ref android.R.styleable#View_minHeight
15122     */
15123    public int getMinimumHeight() {
15124        return mMinHeight;
15125    }
15126
15127    /**
15128     * Sets the minimum height of the view. It is not guaranteed the view will
15129     * be able to achieve this minimum height (for example, if its parent layout
15130     * constrains it with less available height).
15131     *
15132     * @param minHeight The minimum height the view will try to be.
15133     *
15134     * @see #getMinimumHeight()
15135     *
15136     * @attr ref android.R.styleable#View_minHeight
15137     */
15138    public void setMinimumHeight(int minHeight) {
15139        mMinHeight = minHeight;
15140        requestLayout();
15141    }
15142
15143    /**
15144     * Returns the minimum width of the view.
15145     *
15146     * @return the minimum width the view will try to be.
15147     *
15148     * @see #setMinimumWidth(int)
15149     *
15150     * @attr ref android.R.styleable#View_minWidth
15151     */
15152    public int getMinimumWidth() {
15153        return mMinWidth;
15154    }
15155
15156    /**
15157     * Sets the minimum width of the view. It is not guaranteed the view will
15158     * be able to achieve this minimum width (for example, if its parent layout
15159     * constrains it with less available width).
15160     *
15161     * @param minWidth The minimum width the view will try to be.
15162     *
15163     * @see #getMinimumWidth()
15164     *
15165     * @attr ref android.R.styleable#View_minWidth
15166     */
15167    public void setMinimumWidth(int minWidth) {
15168        mMinWidth = minWidth;
15169        requestLayout();
15170
15171    }
15172
15173    /**
15174     * Get the animation currently associated with this view.
15175     *
15176     * @return The animation that is currently playing or
15177     *         scheduled to play for this view.
15178     */
15179    public Animation getAnimation() {
15180        return mCurrentAnimation;
15181    }
15182
15183    /**
15184     * Start the specified animation now.
15185     *
15186     * @param animation the animation to start now
15187     */
15188    public void startAnimation(Animation animation) {
15189        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15190        setAnimation(animation);
15191        invalidateParentCaches();
15192        invalidate(true);
15193    }
15194
15195    /**
15196     * Cancels any animations for this view.
15197     */
15198    public void clearAnimation() {
15199        if (mCurrentAnimation != null) {
15200            mCurrentAnimation.detach();
15201        }
15202        mCurrentAnimation = null;
15203        invalidateParentIfNeeded();
15204    }
15205
15206    /**
15207     * Sets the next animation to play for this view.
15208     * If you want the animation to play immediately, use
15209     * {@link #startAnimation(android.view.animation.Animation)} instead.
15210     * This method provides allows fine-grained
15211     * control over the start time and invalidation, but you
15212     * must make sure that 1) the animation has a start time set, and
15213     * 2) the view's parent (which controls animations on its children)
15214     * will be invalidated when the animation is supposed to
15215     * start.
15216     *
15217     * @param animation The next animation, or null.
15218     */
15219    public void setAnimation(Animation animation) {
15220        mCurrentAnimation = animation;
15221
15222        if (animation != null) {
15223            // If the screen is off assume the animation start time is now instead of
15224            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15225            // would cause the animation to start when the screen turns back on
15226            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15227                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15228                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15229            }
15230            animation.reset();
15231        }
15232    }
15233
15234    /**
15235     * Invoked by a parent ViewGroup to notify the start of the animation
15236     * currently associated with this view. If you override this method,
15237     * always call super.onAnimationStart();
15238     *
15239     * @see #setAnimation(android.view.animation.Animation)
15240     * @see #getAnimation()
15241     */
15242    protected void onAnimationStart() {
15243        mPrivateFlags |= ANIMATION_STARTED;
15244    }
15245
15246    /**
15247     * Invoked by a parent ViewGroup to notify the end of the animation
15248     * currently associated with this view. If you override this method,
15249     * always call super.onAnimationEnd();
15250     *
15251     * @see #setAnimation(android.view.animation.Animation)
15252     * @see #getAnimation()
15253     */
15254    protected void onAnimationEnd() {
15255        mPrivateFlags &= ~ANIMATION_STARTED;
15256    }
15257
15258    /**
15259     * Invoked if there is a Transform that involves alpha. Subclass that can
15260     * draw themselves with the specified alpha should return true, and then
15261     * respect that alpha when their onDraw() is called. If this returns false
15262     * then the view may be redirected to draw into an offscreen buffer to
15263     * fulfill the request, which will look fine, but may be slower than if the
15264     * subclass handles it internally. The default implementation returns false.
15265     *
15266     * @param alpha The alpha (0..255) to apply to the view's drawing
15267     * @return true if the view can draw with the specified alpha.
15268     */
15269    protected boolean onSetAlpha(int alpha) {
15270        return false;
15271    }
15272
15273    /**
15274     * This is used by the RootView to perform an optimization when
15275     * the view hierarchy contains one or several SurfaceView.
15276     * SurfaceView is always considered transparent, but its children are not,
15277     * therefore all View objects remove themselves from the global transparent
15278     * region (passed as a parameter to this function).
15279     *
15280     * @param region The transparent region for this ViewAncestor (window).
15281     *
15282     * @return Returns true if the effective visibility of the view at this
15283     * point is opaque, regardless of the transparent region; returns false
15284     * if it is possible for underlying windows to be seen behind the view.
15285     *
15286     * {@hide}
15287     */
15288    public boolean gatherTransparentRegion(Region region) {
15289        final AttachInfo attachInfo = mAttachInfo;
15290        if (region != null && attachInfo != null) {
15291            final int pflags = mPrivateFlags;
15292            if ((pflags & SKIP_DRAW) == 0) {
15293                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15294                // remove it from the transparent region.
15295                final int[] location = attachInfo.mTransparentLocation;
15296                getLocationInWindow(location);
15297                region.op(location[0], location[1], location[0] + mRight - mLeft,
15298                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15299            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15300                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15301                // exists, so we remove the background drawable's non-transparent
15302                // parts from this transparent region.
15303                applyDrawableToTransparentRegion(mBackground, region);
15304            }
15305        }
15306        return true;
15307    }
15308
15309    /**
15310     * Play a sound effect for this view.
15311     *
15312     * <p>The framework will play sound effects for some built in actions, such as
15313     * clicking, but you may wish to play these effects in your widget,
15314     * for instance, for internal navigation.
15315     *
15316     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15317     * {@link #isSoundEffectsEnabled()} is true.
15318     *
15319     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15320     */
15321    public void playSoundEffect(int soundConstant) {
15322        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15323            return;
15324        }
15325        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15326    }
15327
15328    /**
15329     * BZZZTT!!1!
15330     *
15331     * <p>Provide haptic feedback to the user for this view.
15332     *
15333     * <p>The framework will provide haptic feedback for some built in actions,
15334     * such as long presses, but you may wish to provide feedback for your
15335     * own widget.
15336     *
15337     * <p>The feedback will only be performed if
15338     * {@link #isHapticFeedbackEnabled()} is true.
15339     *
15340     * @param feedbackConstant One of the constants defined in
15341     * {@link HapticFeedbackConstants}
15342     */
15343    public boolean performHapticFeedback(int feedbackConstant) {
15344        return performHapticFeedback(feedbackConstant, 0);
15345    }
15346
15347    /**
15348     * BZZZTT!!1!
15349     *
15350     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15351     *
15352     * @param feedbackConstant One of the constants defined in
15353     * {@link HapticFeedbackConstants}
15354     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15355     */
15356    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15357        if (mAttachInfo == null) {
15358            return false;
15359        }
15360        //noinspection SimplifiableIfStatement
15361        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15362                && !isHapticFeedbackEnabled()) {
15363            return false;
15364        }
15365        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15366                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15367    }
15368
15369    /**
15370     * Request that the visibility of the status bar or other screen/window
15371     * decorations be changed.
15372     *
15373     * <p>This method is used to put the over device UI into temporary modes
15374     * where the user's attention is focused more on the application content,
15375     * by dimming or hiding surrounding system affordances.  This is typically
15376     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15377     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15378     * to be placed behind the action bar (and with these flags other system
15379     * affordances) so that smooth transitions between hiding and showing them
15380     * can be done.
15381     *
15382     * <p>Two representative examples of the use of system UI visibility is
15383     * implementing a content browsing application (like a magazine reader)
15384     * and a video playing application.
15385     *
15386     * <p>The first code shows a typical implementation of a View in a content
15387     * browsing application.  In this implementation, the application goes
15388     * into a content-oriented mode by hiding the status bar and action bar,
15389     * and putting the navigation elements into lights out mode.  The user can
15390     * then interact with content while in this mode.  Such an application should
15391     * provide an easy way for the user to toggle out of the mode (such as to
15392     * check information in the status bar or access notifications).  In the
15393     * implementation here, this is done simply by tapping on the content.
15394     *
15395     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15396     *      content}
15397     *
15398     * <p>This second code sample shows a typical implementation of a View
15399     * in a video playing application.  In this situation, while the video is
15400     * playing the application would like to go into a complete full-screen mode,
15401     * to use as much of the display as possible for the video.  When in this state
15402     * the user can not interact with the application; the system intercepts
15403     * touching on the screen to pop the UI out of full screen mode.  See
15404     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15405     *
15406     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15407     *      content}
15408     *
15409     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15410     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15411     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15412     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15413     */
15414    public void setSystemUiVisibility(int visibility) {
15415        if (visibility != mSystemUiVisibility) {
15416            mSystemUiVisibility = visibility;
15417            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15418                mParent.recomputeViewAttributes(this);
15419            }
15420        }
15421    }
15422
15423    /**
15424     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15425     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15426     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15427     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15428     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15429     */
15430    public int getSystemUiVisibility() {
15431        return mSystemUiVisibility;
15432    }
15433
15434    /**
15435     * Returns the current system UI visibility that is currently set for
15436     * the entire window.  This is the combination of the
15437     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15438     * views in the window.
15439     */
15440    public int getWindowSystemUiVisibility() {
15441        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15442    }
15443
15444    /**
15445     * Override to find out when the window's requested system UI visibility
15446     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15447     * This is different from the callbacks recieved through
15448     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15449     * in that this is only telling you about the local request of the window,
15450     * not the actual values applied by the system.
15451     */
15452    public void onWindowSystemUiVisibilityChanged(int visible) {
15453    }
15454
15455    /**
15456     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15457     * the view hierarchy.
15458     */
15459    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15460        onWindowSystemUiVisibilityChanged(visible);
15461    }
15462
15463    /**
15464     * Set a listener to receive callbacks when the visibility of the system bar changes.
15465     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15466     */
15467    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15468        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15469        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15470            mParent.recomputeViewAttributes(this);
15471        }
15472    }
15473
15474    /**
15475     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15476     * the view hierarchy.
15477     */
15478    public void dispatchSystemUiVisibilityChanged(int visibility) {
15479        ListenerInfo li = mListenerInfo;
15480        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15481            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15482                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15483        }
15484    }
15485
15486    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15487        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15488        if (val != mSystemUiVisibility) {
15489            setSystemUiVisibility(val);
15490            return true;
15491        }
15492        return false;
15493    }
15494
15495    /** @hide */
15496    public void setDisabledSystemUiVisibility(int flags) {
15497        if (mAttachInfo != null) {
15498            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15499                mAttachInfo.mDisabledSystemUiVisibility = flags;
15500                if (mParent != null) {
15501                    mParent.recomputeViewAttributes(this);
15502                }
15503            }
15504        }
15505    }
15506
15507    /**
15508     * Creates an image that the system displays during the drag and drop
15509     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15510     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15511     * appearance as the given View. The default also positions the center of the drag shadow
15512     * directly under the touch point. If no View is provided (the constructor with no parameters
15513     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15514     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15515     * default is an invisible drag shadow.
15516     * <p>
15517     * You are not required to use the View you provide to the constructor as the basis of the
15518     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15519     * anything you want as the drag shadow.
15520     * </p>
15521     * <p>
15522     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15523     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15524     *  size and position of the drag shadow. It uses this data to construct a
15525     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15526     *  so that your application can draw the shadow image in the Canvas.
15527     * </p>
15528     *
15529     * <div class="special reference">
15530     * <h3>Developer Guides</h3>
15531     * <p>For a guide to implementing drag and drop features, read the
15532     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15533     * </div>
15534     */
15535    public static class DragShadowBuilder {
15536        private final WeakReference<View> mView;
15537
15538        /**
15539         * Constructs a shadow image builder based on a View. By default, the resulting drag
15540         * shadow will have the same appearance and dimensions as the View, with the touch point
15541         * over the center of the View.
15542         * @param view A View. Any View in scope can be used.
15543         */
15544        public DragShadowBuilder(View view) {
15545            mView = new WeakReference<View>(view);
15546        }
15547
15548        /**
15549         * Construct a shadow builder object with no associated View.  This
15550         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15551         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15552         * to supply the drag shadow's dimensions and appearance without
15553         * reference to any View object. If they are not overridden, then the result is an
15554         * invisible drag shadow.
15555         */
15556        public DragShadowBuilder() {
15557            mView = new WeakReference<View>(null);
15558        }
15559
15560        /**
15561         * Returns the View object that had been passed to the
15562         * {@link #View.DragShadowBuilder(View)}
15563         * constructor.  If that View parameter was {@code null} or if the
15564         * {@link #View.DragShadowBuilder()}
15565         * constructor was used to instantiate the builder object, this method will return
15566         * null.
15567         *
15568         * @return The View object associate with this builder object.
15569         */
15570        @SuppressWarnings({"JavadocReference"})
15571        final public View getView() {
15572            return mView.get();
15573        }
15574
15575        /**
15576         * Provides the metrics for the shadow image. These include the dimensions of
15577         * the shadow image, and the point within that shadow that should
15578         * be centered under the touch location while dragging.
15579         * <p>
15580         * The default implementation sets the dimensions of the shadow to be the
15581         * same as the dimensions of the View itself and centers the shadow under
15582         * the touch point.
15583         * </p>
15584         *
15585         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15586         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15587         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15588         * image.
15589         *
15590         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15591         * shadow image that should be underneath the touch point during the drag and drop
15592         * operation. Your application must set {@link android.graphics.Point#x} to the
15593         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15594         */
15595        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15596            final View view = mView.get();
15597            if (view != null) {
15598                shadowSize.set(view.getWidth(), view.getHeight());
15599                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15600            } else {
15601                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15602            }
15603        }
15604
15605        /**
15606         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15607         * based on the dimensions it received from the
15608         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15609         *
15610         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15611         */
15612        public void onDrawShadow(Canvas canvas) {
15613            final View view = mView.get();
15614            if (view != null) {
15615                view.draw(canvas);
15616            } else {
15617                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15618            }
15619        }
15620    }
15621
15622    /**
15623     * Starts a drag and drop operation. When your application calls this method, it passes a
15624     * {@link android.view.View.DragShadowBuilder} object to the system. The
15625     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15626     * to get metrics for the drag shadow, and then calls the object's
15627     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15628     * <p>
15629     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15630     *  drag events to all the View objects in your application that are currently visible. It does
15631     *  this either by calling the View object's drag listener (an implementation of
15632     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15633     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15634     *  Both are passed a {@link android.view.DragEvent} object that has a
15635     *  {@link android.view.DragEvent#getAction()} value of
15636     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15637     * </p>
15638     * <p>
15639     * Your application can invoke startDrag() on any attached View object. The View object does not
15640     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15641     * be related to the View the user selected for dragging.
15642     * </p>
15643     * @param data A {@link android.content.ClipData} object pointing to the data to be
15644     * transferred by the drag and drop operation.
15645     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15646     * drag shadow.
15647     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15648     * drop operation. This Object is put into every DragEvent object sent by the system during the
15649     * current drag.
15650     * <p>
15651     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15652     * to the target Views. For example, it can contain flags that differentiate between a
15653     * a copy operation and a move operation.
15654     * </p>
15655     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15656     * so the parameter should be set to 0.
15657     * @return {@code true} if the method completes successfully, or
15658     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15659     * do a drag, and so no drag operation is in progress.
15660     */
15661    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15662            Object myLocalState, int flags) {
15663        if (ViewDebug.DEBUG_DRAG) {
15664            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15665        }
15666        boolean okay = false;
15667
15668        Point shadowSize = new Point();
15669        Point shadowTouchPoint = new Point();
15670        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15671
15672        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15673                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15674            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15675        }
15676
15677        if (ViewDebug.DEBUG_DRAG) {
15678            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15679                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15680        }
15681        Surface surface = new Surface();
15682        try {
15683            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15684                    flags, shadowSize.x, shadowSize.y, surface);
15685            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15686                    + " surface=" + surface);
15687            if (token != null) {
15688                Canvas canvas = surface.lockCanvas(null);
15689                try {
15690                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15691                    shadowBuilder.onDrawShadow(canvas);
15692                } finally {
15693                    surface.unlockCanvasAndPost(canvas);
15694                }
15695
15696                final ViewRootImpl root = getViewRootImpl();
15697
15698                // Cache the local state object for delivery with DragEvents
15699                root.setLocalDragState(myLocalState);
15700
15701                // repurpose 'shadowSize' for the last touch point
15702                root.getLastTouchPoint(shadowSize);
15703
15704                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15705                        shadowSize.x, shadowSize.y,
15706                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15707                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15708
15709                // Off and running!  Release our local surface instance; the drag
15710                // shadow surface is now managed by the system process.
15711                surface.release();
15712            }
15713        } catch (Exception e) {
15714            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15715            surface.destroy();
15716        }
15717
15718        return okay;
15719    }
15720
15721    /**
15722     * Handles drag events sent by the system following a call to
15723     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15724     *<p>
15725     * When the system calls this method, it passes a
15726     * {@link android.view.DragEvent} object. A call to
15727     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15728     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15729     * operation.
15730     * @param event The {@link android.view.DragEvent} sent by the system.
15731     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15732     * in DragEvent, indicating the type of drag event represented by this object.
15733     * @return {@code true} if the method was successful, otherwise {@code false}.
15734     * <p>
15735     *  The method should return {@code true} in response to an action type of
15736     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15737     *  operation.
15738     * </p>
15739     * <p>
15740     *  The method should also return {@code true} in response to an action type of
15741     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15742     *  {@code false} if it didn't.
15743     * </p>
15744     */
15745    public boolean onDragEvent(DragEvent event) {
15746        return false;
15747    }
15748
15749    /**
15750     * Detects if this View is enabled and has a drag event listener.
15751     * If both are true, then it calls the drag event listener with the
15752     * {@link android.view.DragEvent} it received. If the drag event listener returns
15753     * {@code true}, then dispatchDragEvent() returns {@code true}.
15754     * <p>
15755     * For all other cases, the method calls the
15756     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15757     * method and returns its result.
15758     * </p>
15759     * <p>
15760     * This ensures that a drag event is always consumed, even if the View does not have a drag
15761     * event listener. However, if the View has a listener and the listener returns true, then
15762     * onDragEvent() is not called.
15763     * </p>
15764     */
15765    public boolean dispatchDragEvent(DragEvent event) {
15766        //noinspection SimplifiableIfStatement
15767        ListenerInfo li = mListenerInfo;
15768        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15769                && li.mOnDragListener.onDrag(this, event)) {
15770            return true;
15771        }
15772        return onDragEvent(event);
15773    }
15774
15775    boolean canAcceptDrag() {
15776        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15777    }
15778
15779    /**
15780     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15781     * it is ever exposed at all.
15782     * @hide
15783     */
15784    public void onCloseSystemDialogs(String reason) {
15785    }
15786
15787    /**
15788     * Given a Drawable whose bounds have been set to draw into this view,
15789     * update a Region being computed for
15790     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15791     * that any non-transparent parts of the Drawable are removed from the
15792     * given transparent region.
15793     *
15794     * @param dr The Drawable whose transparency is to be applied to the region.
15795     * @param region A Region holding the current transparency information,
15796     * where any parts of the region that are set are considered to be
15797     * transparent.  On return, this region will be modified to have the
15798     * transparency information reduced by the corresponding parts of the
15799     * Drawable that are not transparent.
15800     * {@hide}
15801     */
15802    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15803        if (DBG) {
15804            Log.i("View", "Getting transparent region for: " + this);
15805        }
15806        final Region r = dr.getTransparentRegion();
15807        final Rect db = dr.getBounds();
15808        final AttachInfo attachInfo = mAttachInfo;
15809        if (r != null && attachInfo != null) {
15810            final int w = getRight()-getLeft();
15811            final int h = getBottom()-getTop();
15812            if (db.left > 0) {
15813                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15814                r.op(0, 0, db.left, h, Region.Op.UNION);
15815            }
15816            if (db.right < w) {
15817                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15818                r.op(db.right, 0, w, h, Region.Op.UNION);
15819            }
15820            if (db.top > 0) {
15821                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15822                r.op(0, 0, w, db.top, Region.Op.UNION);
15823            }
15824            if (db.bottom < h) {
15825                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15826                r.op(0, db.bottom, w, h, Region.Op.UNION);
15827            }
15828            final int[] location = attachInfo.mTransparentLocation;
15829            getLocationInWindow(location);
15830            r.translate(location[0], location[1]);
15831            region.op(r, Region.Op.INTERSECT);
15832        } else {
15833            region.op(db, Region.Op.DIFFERENCE);
15834        }
15835    }
15836
15837    private void checkForLongClick(int delayOffset) {
15838        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15839            mHasPerformedLongPress = false;
15840
15841            if (mPendingCheckForLongPress == null) {
15842                mPendingCheckForLongPress = new CheckForLongPress();
15843            }
15844            mPendingCheckForLongPress.rememberWindowAttachCount();
15845            postDelayed(mPendingCheckForLongPress,
15846                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15847        }
15848    }
15849
15850    /**
15851     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15852     * LayoutInflater} class, which provides a full range of options for view inflation.
15853     *
15854     * @param context The Context object for your activity or application.
15855     * @param resource The resource ID to inflate
15856     * @param root A view group that will be the parent.  Used to properly inflate the
15857     * layout_* parameters.
15858     * @see LayoutInflater
15859     */
15860    public static View inflate(Context context, int resource, ViewGroup root) {
15861        LayoutInflater factory = LayoutInflater.from(context);
15862        return factory.inflate(resource, root);
15863    }
15864
15865    /**
15866     * Scroll the view with standard behavior for scrolling beyond the normal
15867     * content boundaries. Views that call this method should override
15868     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15869     * results of an over-scroll operation.
15870     *
15871     * Views can use this method to handle any touch or fling-based scrolling.
15872     *
15873     * @param deltaX Change in X in pixels
15874     * @param deltaY Change in Y in pixels
15875     * @param scrollX Current X scroll value in pixels before applying deltaX
15876     * @param scrollY Current Y scroll value in pixels before applying deltaY
15877     * @param scrollRangeX Maximum content scroll range along the X axis
15878     * @param scrollRangeY Maximum content scroll range along the Y axis
15879     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15880     *          along the X axis.
15881     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15882     *          along the Y axis.
15883     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15884     * @return true if scrolling was clamped to an over-scroll boundary along either
15885     *          axis, false otherwise.
15886     */
15887    @SuppressWarnings({"UnusedParameters"})
15888    protected boolean overScrollBy(int deltaX, int deltaY,
15889            int scrollX, int scrollY,
15890            int scrollRangeX, int scrollRangeY,
15891            int maxOverScrollX, int maxOverScrollY,
15892            boolean isTouchEvent) {
15893        final int overScrollMode = mOverScrollMode;
15894        final boolean canScrollHorizontal =
15895                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15896        final boolean canScrollVertical =
15897                computeVerticalScrollRange() > computeVerticalScrollExtent();
15898        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15899                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15900        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15901                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15902
15903        int newScrollX = scrollX + deltaX;
15904        if (!overScrollHorizontal) {
15905            maxOverScrollX = 0;
15906        }
15907
15908        int newScrollY = scrollY + deltaY;
15909        if (!overScrollVertical) {
15910            maxOverScrollY = 0;
15911        }
15912
15913        // Clamp values if at the limits and record
15914        final int left = -maxOverScrollX;
15915        final int right = maxOverScrollX + scrollRangeX;
15916        final int top = -maxOverScrollY;
15917        final int bottom = maxOverScrollY + scrollRangeY;
15918
15919        boolean clampedX = false;
15920        if (newScrollX > right) {
15921            newScrollX = right;
15922            clampedX = true;
15923        } else if (newScrollX < left) {
15924            newScrollX = left;
15925            clampedX = true;
15926        }
15927
15928        boolean clampedY = false;
15929        if (newScrollY > bottom) {
15930            newScrollY = bottom;
15931            clampedY = true;
15932        } else if (newScrollY < top) {
15933            newScrollY = top;
15934            clampedY = true;
15935        }
15936
15937        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15938
15939        return clampedX || clampedY;
15940    }
15941
15942    /**
15943     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15944     * respond to the results of an over-scroll operation.
15945     *
15946     * @param scrollX New X scroll value in pixels
15947     * @param scrollY New Y scroll value in pixels
15948     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15949     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15950     */
15951    protected void onOverScrolled(int scrollX, int scrollY,
15952            boolean clampedX, boolean clampedY) {
15953        // Intentionally empty.
15954    }
15955
15956    /**
15957     * Returns the over-scroll mode for this view. The result will be
15958     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15959     * (allow over-scrolling only if the view content is larger than the container),
15960     * or {@link #OVER_SCROLL_NEVER}.
15961     *
15962     * @return This view's over-scroll mode.
15963     */
15964    public int getOverScrollMode() {
15965        return mOverScrollMode;
15966    }
15967
15968    /**
15969     * Set the over-scroll mode for this view. Valid over-scroll modes are
15970     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15971     * (allow over-scrolling only if the view content is larger than the container),
15972     * or {@link #OVER_SCROLL_NEVER}.
15973     *
15974     * Setting the over-scroll mode of a view will have an effect only if the
15975     * view is capable of scrolling.
15976     *
15977     * @param overScrollMode The new over-scroll mode for this view.
15978     */
15979    public void setOverScrollMode(int overScrollMode) {
15980        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15981                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15982                overScrollMode != OVER_SCROLL_NEVER) {
15983            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15984        }
15985        mOverScrollMode = overScrollMode;
15986    }
15987
15988    /**
15989     * Gets a scale factor that determines the distance the view should scroll
15990     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15991     * @return The vertical scroll scale factor.
15992     * @hide
15993     */
15994    protected float getVerticalScrollFactor() {
15995        if (mVerticalScrollFactor == 0) {
15996            TypedValue outValue = new TypedValue();
15997            if (!mContext.getTheme().resolveAttribute(
15998                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15999                throw new IllegalStateException(
16000                        "Expected theme to define listPreferredItemHeight.");
16001            }
16002            mVerticalScrollFactor = outValue.getDimension(
16003                    mContext.getResources().getDisplayMetrics());
16004        }
16005        return mVerticalScrollFactor;
16006    }
16007
16008    /**
16009     * Gets a scale factor that determines the distance the view should scroll
16010     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16011     * @return The horizontal scroll scale factor.
16012     * @hide
16013     */
16014    protected float getHorizontalScrollFactor() {
16015        // TODO: Should use something else.
16016        return getVerticalScrollFactor();
16017    }
16018
16019    /**
16020     * Return the value specifying the text direction or policy that was set with
16021     * {@link #setTextDirection(int)}.
16022     *
16023     * @return the defined text direction. It can be one of:
16024     *
16025     * {@link #TEXT_DIRECTION_INHERIT},
16026     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16027     * {@link #TEXT_DIRECTION_ANY_RTL},
16028     * {@link #TEXT_DIRECTION_LTR},
16029     * {@link #TEXT_DIRECTION_RTL},
16030     * {@link #TEXT_DIRECTION_LOCALE}
16031     */
16032    @ViewDebug.ExportedProperty(category = "text", mapping = {
16033            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16034            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16035            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16036            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16037            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16038            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16039    })
16040    public int getTextDirection() {
16041        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16042    }
16043
16044    /**
16045     * Set the text direction.
16046     *
16047     * @param textDirection the direction to set. Should be one of:
16048     *
16049     * {@link #TEXT_DIRECTION_INHERIT},
16050     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16051     * {@link #TEXT_DIRECTION_ANY_RTL},
16052     * {@link #TEXT_DIRECTION_LTR},
16053     * {@link #TEXT_DIRECTION_RTL},
16054     * {@link #TEXT_DIRECTION_LOCALE}
16055     */
16056    public void setTextDirection(int textDirection) {
16057        if (getTextDirection() != textDirection) {
16058            // Reset the current text direction and the resolved one
16059            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16060            resetResolvedTextDirection();
16061            // Set the new text direction
16062            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16063            // Refresh
16064            requestLayout();
16065            invalidate(true);
16066        }
16067    }
16068
16069    /**
16070     * Return the resolved text direction.
16071     *
16072     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16073     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16074     * up the parent chain of the view. if there is no parent, then it will return the default
16075     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16076     *
16077     * @return the resolved text direction. Returns one of:
16078     *
16079     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16080     * {@link #TEXT_DIRECTION_ANY_RTL},
16081     * {@link #TEXT_DIRECTION_LTR},
16082     * {@link #TEXT_DIRECTION_RTL},
16083     * {@link #TEXT_DIRECTION_LOCALE}
16084     */
16085    public int getResolvedTextDirection() {
16086        // The text direction will be resolved only if needed
16087        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16088            resolveTextDirection();
16089        }
16090        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16091    }
16092
16093    /**
16094     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16095     * resolution is done.
16096     */
16097    public void resolveTextDirection() {
16098        // Reset any previous text direction resolution
16099        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16100
16101        if (hasRtlSupport()) {
16102            // Set resolved text direction flag depending on text direction flag
16103            final int textDirection = getTextDirection();
16104            switch(textDirection) {
16105                case TEXT_DIRECTION_INHERIT:
16106                    if (canResolveTextDirection()) {
16107                        ViewGroup viewGroup = ((ViewGroup) mParent);
16108
16109                        // Set current resolved direction to the same value as the parent's one
16110                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16111                        switch (parentResolvedDirection) {
16112                            case TEXT_DIRECTION_FIRST_STRONG:
16113                            case TEXT_DIRECTION_ANY_RTL:
16114                            case TEXT_DIRECTION_LTR:
16115                            case TEXT_DIRECTION_RTL:
16116                            case TEXT_DIRECTION_LOCALE:
16117                                mPrivateFlags2 |=
16118                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16119                                break;
16120                            default:
16121                                // Default resolved direction is "first strong" heuristic
16122                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16123                        }
16124                    } else {
16125                        // We cannot do the resolution if there is no parent, so use the default one
16126                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16127                    }
16128                    break;
16129                case TEXT_DIRECTION_FIRST_STRONG:
16130                case TEXT_DIRECTION_ANY_RTL:
16131                case TEXT_DIRECTION_LTR:
16132                case TEXT_DIRECTION_RTL:
16133                case TEXT_DIRECTION_LOCALE:
16134                    // Resolved direction is the same as text direction
16135                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16136                    break;
16137                default:
16138                    // Default resolved direction is "first strong" heuristic
16139                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16140            }
16141        } else {
16142            // Default resolved direction is "first strong" heuristic
16143            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16144        }
16145
16146        // Set to resolved
16147        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16148        onResolvedTextDirectionChanged();
16149    }
16150
16151    /**
16152     * Called when text direction has been resolved. Subclasses that care about text direction
16153     * resolution should override this method.
16154     *
16155     * The default implementation does nothing.
16156     */
16157    public void onResolvedTextDirectionChanged() {
16158    }
16159
16160    /**
16161     * Check if text direction resolution can be done.
16162     *
16163     * @return true if text direction resolution can be done otherwise return false.
16164     */
16165    public boolean canResolveTextDirection() {
16166        switch (getTextDirection()) {
16167            case TEXT_DIRECTION_INHERIT:
16168                return (mParent != null) && (mParent instanceof ViewGroup);
16169            default:
16170                return true;
16171        }
16172    }
16173
16174    /**
16175     * Reset resolved text direction. Text direction can be resolved with a call to
16176     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16177     * reset is done.
16178     */
16179    public void resetResolvedTextDirection() {
16180        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16181        onResolvedTextDirectionReset();
16182    }
16183
16184    /**
16185     * Called when text direction is reset. Subclasses that care about text direction reset should
16186     * override this method and do a reset of the text direction of their children. The default
16187     * implementation does nothing.
16188     */
16189    public void onResolvedTextDirectionReset() {
16190    }
16191
16192    /**
16193     * Return the value specifying the text alignment or policy that was set with
16194     * {@link #setTextAlignment(int)}.
16195     *
16196     * @return the defined text alignment. It can be one of:
16197     *
16198     * {@link #TEXT_ALIGNMENT_INHERIT},
16199     * {@link #TEXT_ALIGNMENT_GRAVITY},
16200     * {@link #TEXT_ALIGNMENT_CENTER},
16201     * {@link #TEXT_ALIGNMENT_TEXT_START},
16202     * {@link #TEXT_ALIGNMENT_TEXT_END},
16203     * {@link #TEXT_ALIGNMENT_VIEW_START},
16204     * {@link #TEXT_ALIGNMENT_VIEW_END}
16205     */
16206    @ViewDebug.ExportedProperty(category = "text", mapping = {
16207            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16208            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16209            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16210            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16211            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16212            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16213            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16214    })
16215    public int getTextAlignment() {
16216        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16217    }
16218
16219    /**
16220     * Set the text alignment.
16221     *
16222     * @param textAlignment The text alignment to set. Should be one of
16223     *
16224     * {@link #TEXT_ALIGNMENT_INHERIT},
16225     * {@link #TEXT_ALIGNMENT_GRAVITY},
16226     * {@link #TEXT_ALIGNMENT_CENTER},
16227     * {@link #TEXT_ALIGNMENT_TEXT_START},
16228     * {@link #TEXT_ALIGNMENT_TEXT_END},
16229     * {@link #TEXT_ALIGNMENT_VIEW_START},
16230     * {@link #TEXT_ALIGNMENT_VIEW_END}
16231     *
16232     * @attr ref android.R.styleable#View_textAlignment
16233     */
16234    public void setTextAlignment(int textAlignment) {
16235        if (textAlignment != getTextAlignment()) {
16236            // Reset the current and resolved text alignment
16237            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16238            resetResolvedTextAlignment();
16239            // Set the new text alignment
16240            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16241            // Refresh
16242            requestLayout();
16243            invalidate(true);
16244        }
16245    }
16246
16247    /**
16248     * Return the resolved text alignment.
16249     *
16250     * The resolved text alignment. This needs resolution if the value is
16251     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16252     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16253     *
16254     * @return the resolved text alignment. Returns one of:
16255     *
16256     * {@link #TEXT_ALIGNMENT_GRAVITY},
16257     * {@link #TEXT_ALIGNMENT_CENTER},
16258     * {@link #TEXT_ALIGNMENT_TEXT_START},
16259     * {@link #TEXT_ALIGNMENT_TEXT_END},
16260     * {@link #TEXT_ALIGNMENT_VIEW_START},
16261     * {@link #TEXT_ALIGNMENT_VIEW_END}
16262     */
16263    @ViewDebug.ExportedProperty(category = "text", mapping = {
16264            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16265            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16266            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16267            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16268            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16269            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16270            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16271    })
16272    public int getResolvedTextAlignment() {
16273        // If text alignment is not resolved, then resolve it
16274        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16275            resolveTextAlignment();
16276        }
16277        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16278    }
16279
16280    /**
16281     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16282     * resolution is done.
16283     */
16284    public void resolveTextAlignment() {
16285        // Reset any previous text alignment resolution
16286        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16287
16288        if (hasRtlSupport()) {
16289            // Set resolved text alignment flag depending on text alignment flag
16290            final int textAlignment = getTextAlignment();
16291            switch (textAlignment) {
16292                case TEXT_ALIGNMENT_INHERIT:
16293                    // Check if we can resolve the text alignment
16294                    if (canResolveLayoutDirection() && mParent instanceof View) {
16295                        View view = (View) mParent;
16296
16297                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16298                        switch (parentResolvedTextAlignment) {
16299                            case TEXT_ALIGNMENT_GRAVITY:
16300                            case TEXT_ALIGNMENT_TEXT_START:
16301                            case TEXT_ALIGNMENT_TEXT_END:
16302                            case TEXT_ALIGNMENT_CENTER:
16303                            case TEXT_ALIGNMENT_VIEW_START:
16304                            case TEXT_ALIGNMENT_VIEW_END:
16305                                // Resolved text alignment is the same as the parent resolved
16306                                // text alignment
16307                                mPrivateFlags2 |=
16308                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16309                                break;
16310                            default:
16311                                // Use default resolved text alignment
16312                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16313                        }
16314                    }
16315                    else {
16316                        // We cannot do the resolution if there is no parent so use the default
16317                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16318                    }
16319                    break;
16320                case TEXT_ALIGNMENT_GRAVITY:
16321                case TEXT_ALIGNMENT_TEXT_START:
16322                case TEXT_ALIGNMENT_TEXT_END:
16323                case TEXT_ALIGNMENT_CENTER:
16324                case TEXT_ALIGNMENT_VIEW_START:
16325                case TEXT_ALIGNMENT_VIEW_END:
16326                    // Resolved text alignment is the same as text alignment
16327                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16328                    break;
16329                default:
16330                    // Use default resolved text alignment
16331                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16332            }
16333        } else {
16334            // Use default resolved text alignment
16335            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16336        }
16337
16338        // Set the resolved
16339        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16340        onResolvedTextAlignmentChanged();
16341    }
16342
16343    /**
16344     * Check if text alignment resolution can be done.
16345     *
16346     * @return true if text alignment resolution can be done otherwise return false.
16347     */
16348    public boolean canResolveTextAlignment() {
16349        switch (getTextAlignment()) {
16350            case TEXT_DIRECTION_INHERIT:
16351                return (mParent != null);
16352            default:
16353                return true;
16354        }
16355    }
16356
16357    /**
16358     * Called when text alignment has been resolved. Subclasses that care about text alignment
16359     * resolution should override this method.
16360     *
16361     * The default implementation does nothing.
16362     */
16363    public void onResolvedTextAlignmentChanged() {
16364    }
16365
16366    /**
16367     * Reset resolved text alignment. Text alignment can be resolved with a call to
16368     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16369     * reset is done.
16370     */
16371    public void resetResolvedTextAlignment() {
16372        // Reset any previous text alignment resolution
16373        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16374        onResolvedTextAlignmentReset();
16375    }
16376
16377    /**
16378     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16379     * override this method and do a reset of the text alignment of their children. The default
16380     * implementation does nothing.
16381     */
16382    public void onResolvedTextAlignmentReset() {
16383    }
16384
16385    //
16386    // Properties
16387    //
16388    /**
16389     * A Property wrapper around the <code>alpha</code> functionality handled by the
16390     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16391     */
16392    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16393        @Override
16394        public void setValue(View object, float value) {
16395            object.setAlpha(value);
16396        }
16397
16398        @Override
16399        public Float get(View object) {
16400            return object.getAlpha();
16401        }
16402    };
16403
16404    /**
16405     * A Property wrapper around the <code>translationX</code> functionality handled by the
16406     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16407     */
16408    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16409        @Override
16410        public void setValue(View object, float value) {
16411            object.setTranslationX(value);
16412        }
16413
16414                @Override
16415        public Float get(View object) {
16416            return object.getTranslationX();
16417        }
16418    };
16419
16420    /**
16421     * A Property wrapper around the <code>translationY</code> functionality handled by the
16422     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16423     */
16424    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16425        @Override
16426        public void setValue(View object, float value) {
16427            object.setTranslationY(value);
16428        }
16429
16430        @Override
16431        public Float get(View object) {
16432            return object.getTranslationY();
16433        }
16434    };
16435
16436    /**
16437     * A Property wrapper around the <code>x</code> functionality handled by the
16438     * {@link View#setX(float)} and {@link View#getX()} methods.
16439     */
16440    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16441        @Override
16442        public void setValue(View object, float value) {
16443            object.setX(value);
16444        }
16445
16446        @Override
16447        public Float get(View object) {
16448            return object.getX();
16449        }
16450    };
16451
16452    /**
16453     * A Property wrapper around the <code>y</code> functionality handled by the
16454     * {@link View#setY(float)} and {@link View#getY()} methods.
16455     */
16456    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16457        @Override
16458        public void setValue(View object, float value) {
16459            object.setY(value);
16460        }
16461
16462        @Override
16463        public Float get(View object) {
16464            return object.getY();
16465        }
16466    };
16467
16468    /**
16469     * A Property wrapper around the <code>rotation</code> functionality handled by the
16470     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16471     */
16472    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16473        @Override
16474        public void setValue(View object, float value) {
16475            object.setRotation(value);
16476        }
16477
16478        @Override
16479        public Float get(View object) {
16480            return object.getRotation();
16481        }
16482    };
16483
16484    /**
16485     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16486     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16487     */
16488    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16489        @Override
16490        public void setValue(View object, float value) {
16491            object.setRotationX(value);
16492        }
16493
16494        @Override
16495        public Float get(View object) {
16496            return object.getRotationX();
16497        }
16498    };
16499
16500    /**
16501     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16502     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16503     */
16504    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16505        @Override
16506        public void setValue(View object, float value) {
16507            object.setRotationY(value);
16508        }
16509
16510        @Override
16511        public Float get(View object) {
16512            return object.getRotationY();
16513        }
16514    };
16515
16516    /**
16517     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16518     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16519     */
16520    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16521        @Override
16522        public void setValue(View object, float value) {
16523            object.setScaleX(value);
16524        }
16525
16526        @Override
16527        public Float get(View object) {
16528            return object.getScaleX();
16529        }
16530    };
16531
16532    /**
16533     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16534     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16535     */
16536    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16537        @Override
16538        public void setValue(View object, float value) {
16539            object.setScaleY(value);
16540        }
16541
16542        @Override
16543        public Float get(View object) {
16544            return object.getScaleY();
16545        }
16546    };
16547
16548    /**
16549     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16550     * Each MeasureSpec represents a requirement for either the width or the height.
16551     * A MeasureSpec is comprised of a size and a mode. There are three possible
16552     * modes:
16553     * <dl>
16554     * <dt>UNSPECIFIED</dt>
16555     * <dd>
16556     * The parent has not imposed any constraint on the child. It can be whatever size
16557     * it wants.
16558     * </dd>
16559     *
16560     * <dt>EXACTLY</dt>
16561     * <dd>
16562     * The parent has determined an exact size for the child. The child is going to be
16563     * given those bounds regardless of how big it wants to be.
16564     * </dd>
16565     *
16566     * <dt>AT_MOST</dt>
16567     * <dd>
16568     * The child can be as large as it wants up to the specified size.
16569     * </dd>
16570     * </dl>
16571     *
16572     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16573     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16574     */
16575    public static class MeasureSpec {
16576        private static final int MODE_SHIFT = 30;
16577        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16578
16579        /**
16580         * Measure specification mode: The parent has not imposed any constraint
16581         * on the child. It can be whatever size it wants.
16582         */
16583        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16584
16585        /**
16586         * Measure specification mode: The parent has determined an exact size
16587         * for the child. The child is going to be given those bounds regardless
16588         * of how big it wants to be.
16589         */
16590        public static final int EXACTLY     = 1 << MODE_SHIFT;
16591
16592        /**
16593         * Measure specification mode: The child can be as large as it wants up
16594         * to the specified size.
16595         */
16596        public static final int AT_MOST     = 2 << MODE_SHIFT;
16597
16598        /**
16599         * Creates a measure specification based on the supplied size and mode.
16600         *
16601         * The mode must always be one of the following:
16602         * <ul>
16603         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16604         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16605         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16606         * </ul>
16607         *
16608         * @param size the size of the measure specification
16609         * @param mode the mode of the measure specification
16610         * @return the measure specification based on size and mode
16611         */
16612        public static int makeMeasureSpec(int size, int mode) {
16613            return size + mode;
16614        }
16615
16616        /**
16617         * Extracts the mode from the supplied measure specification.
16618         *
16619         * @param measureSpec the measure specification to extract the mode from
16620         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16621         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16622         *         {@link android.view.View.MeasureSpec#EXACTLY}
16623         */
16624        public static int getMode(int measureSpec) {
16625            return (measureSpec & MODE_MASK);
16626        }
16627
16628        /**
16629         * Extracts the size from the supplied measure specification.
16630         *
16631         * @param measureSpec the measure specification to extract the size from
16632         * @return the size in pixels defined in the supplied measure specification
16633         */
16634        public static int getSize(int measureSpec) {
16635            return (measureSpec & ~MODE_MASK);
16636        }
16637
16638        /**
16639         * Returns a String representation of the specified measure
16640         * specification.
16641         *
16642         * @param measureSpec the measure specification to convert to a String
16643         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16644         */
16645        public static String toString(int measureSpec) {
16646            int mode = getMode(measureSpec);
16647            int size = getSize(measureSpec);
16648
16649            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16650
16651            if (mode == UNSPECIFIED)
16652                sb.append("UNSPECIFIED ");
16653            else if (mode == EXACTLY)
16654                sb.append("EXACTLY ");
16655            else if (mode == AT_MOST)
16656                sb.append("AT_MOST ");
16657            else
16658                sb.append(mode).append(" ");
16659
16660            sb.append(size);
16661            return sb.toString();
16662        }
16663    }
16664
16665    class CheckForLongPress implements Runnable {
16666
16667        private int mOriginalWindowAttachCount;
16668
16669        public void run() {
16670            if (isPressed() && (mParent != null)
16671                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16672                if (performLongClick()) {
16673                    mHasPerformedLongPress = true;
16674                }
16675            }
16676        }
16677
16678        public void rememberWindowAttachCount() {
16679            mOriginalWindowAttachCount = mWindowAttachCount;
16680        }
16681    }
16682
16683    private final class CheckForTap implements Runnable {
16684        public void run() {
16685            mPrivateFlags &= ~PREPRESSED;
16686            setPressed(true);
16687            checkForLongClick(ViewConfiguration.getTapTimeout());
16688        }
16689    }
16690
16691    private final class PerformClick implements Runnable {
16692        public void run() {
16693            performClick();
16694        }
16695    }
16696
16697    /** @hide */
16698    public void hackTurnOffWindowResizeAnim(boolean off) {
16699        mAttachInfo.mTurnOffWindowResizeAnim = off;
16700    }
16701
16702    /**
16703     * This method returns a ViewPropertyAnimator object, which can be used to animate
16704     * specific properties on this View.
16705     *
16706     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16707     */
16708    public ViewPropertyAnimator animate() {
16709        if (mAnimator == null) {
16710            mAnimator = new ViewPropertyAnimator(this);
16711        }
16712        return mAnimator;
16713    }
16714
16715    /**
16716     * Interface definition for a callback to be invoked when a key event is
16717     * dispatched to this view. The callback will be invoked before the key
16718     * event is given to the view.
16719     */
16720    public interface OnKeyListener {
16721        /**
16722         * Called when a key is dispatched to a view. This allows listeners to
16723         * get a chance to respond before the target view.
16724         *
16725         * @param v The view the key has been dispatched to.
16726         * @param keyCode The code for the physical key that was pressed
16727         * @param event The KeyEvent object containing full information about
16728         *        the event.
16729         * @return True if the listener has consumed the event, false otherwise.
16730         */
16731        boolean onKey(View v, int keyCode, KeyEvent event);
16732    }
16733
16734    /**
16735     * Interface definition for a callback to be invoked when a touch event is
16736     * dispatched to this view. The callback will be invoked before the touch
16737     * event is given to the view.
16738     */
16739    public interface OnTouchListener {
16740        /**
16741         * Called when a touch event is dispatched to a view. This allows listeners to
16742         * get a chance to respond before the target view.
16743         *
16744         * @param v The view the touch event has been dispatched to.
16745         * @param event The MotionEvent object containing full information about
16746         *        the event.
16747         * @return True if the listener has consumed the event, false otherwise.
16748         */
16749        boolean onTouch(View v, MotionEvent event);
16750    }
16751
16752    /**
16753     * Interface definition for a callback to be invoked when a hover event is
16754     * dispatched to this view. The callback will be invoked before the hover
16755     * event is given to the view.
16756     */
16757    public interface OnHoverListener {
16758        /**
16759         * Called when a hover event is dispatched to a view. This allows listeners to
16760         * get a chance to respond before the target view.
16761         *
16762         * @param v The view the hover event has been dispatched to.
16763         * @param event The MotionEvent object containing full information about
16764         *        the event.
16765         * @return True if the listener has consumed the event, false otherwise.
16766         */
16767        boolean onHover(View v, MotionEvent event);
16768    }
16769
16770    /**
16771     * Interface definition for a callback to be invoked when a generic motion event is
16772     * dispatched to this view. The callback will be invoked before the generic motion
16773     * event is given to the view.
16774     */
16775    public interface OnGenericMotionListener {
16776        /**
16777         * Called when a generic motion event is dispatched to a view. This allows listeners to
16778         * get a chance to respond before the target view.
16779         *
16780         * @param v The view the generic motion event has been dispatched to.
16781         * @param event The MotionEvent object containing full information about
16782         *        the event.
16783         * @return True if the listener has consumed the event, false otherwise.
16784         */
16785        boolean onGenericMotion(View v, MotionEvent event);
16786    }
16787
16788    /**
16789     * Interface definition for a callback to be invoked when a view has been clicked and held.
16790     */
16791    public interface OnLongClickListener {
16792        /**
16793         * Called when a view has been clicked and held.
16794         *
16795         * @param v The view that was clicked and held.
16796         *
16797         * @return true if the callback consumed the long click, false otherwise.
16798         */
16799        boolean onLongClick(View v);
16800    }
16801
16802    /**
16803     * Interface definition for a callback to be invoked when a drag is being dispatched
16804     * to this view.  The callback will be invoked before the hosting view's own
16805     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16806     * onDrag(event) behavior, it should return 'false' from this callback.
16807     *
16808     * <div class="special reference">
16809     * <h3>Developer Guides</h3>
16810     * <p>For a guide to implementing drag and drop features, read the
16811     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16812     * </div>
16813     */
16814    public interface OnDragListener {
16815        /**
16816         * Called when a drag event is dispatched to a view. This allows listeners
16817         * to get a chance to override base View behavior.
16818         *
16819         * @param v The View that received the drag event.
16820         * @param event The {@link android.view.DragEvent} object for the drag event.
16821         * @return {@code true} if the drag event was handled successfully, or {@code false}
16822         * if the drag event was not handled. Note that {@code false} will trigger the View
16823         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16824         */
16825        boolean onDrag(View v, DragEvent event);
16826    }
16827
16828    /**
16829     * Interface definition for a callback to be invoked when the focus state of
16830     * a view changed.
16831     */
16832    public interface OnFocusChangeListener {
16833        /**
16834         * Called when the focus state of a view has changed.
16835         *
16836         * @param v The view whose state has changed.
16837         * @param hasFocus The new focus state of v.
16838         */
16839        void onFocusChange(View v, boolean hasFocus);
16840    }
16841
16842    /**
16843     * Interface definition for a callback to be invoked when a view is clicked.
16844     */
16845    public interface OnClickListener {
16846        /**
16847         * Called when a view has been clicked.
16848         *
16849         * @param v The view that was clicked.
16850         */
16851        void onClick(View v);
16852    }
16853
16854    /**
16855     * Interface definition for a callback to be invoked when the context menu
16856     * for this view is being built.
16857     */
16858    public interface OnCreateContextMenuListener {
16859        /**
16860         * Called when the context menu for this view is being built. It is not
16861         * safe to hold onto the menu after this method returns.
16862         *
16863         * @param menu The context menu that is being built
16864         * @param v The view for which the context menu is being built
16865         * @param menuInfo Extra information about the item for which the
16866         *            context menu should be shown. This information will vary
16867         *            depending on the class of v.
16868         */
16869        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16870    }
16871
16872    /**
16873     * Interface definition for a callback to be invoked when the status bar changes
16874     * visibility.  This reports <strong>global</strong> changes to the system UI
16875     * state, not what the application is requesting.
16876     *
16877     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16878     */
16879    public interface OnSystemUiVisibilityChangeListener {
16880        /**
16881         * Called when the status bar changes visibility because of a call to
16882         * {@link View#setSystemUiVisibility(int)}.
16883         *
16884         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16885         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
16886         * This tells you the <strong>global</strong> state of these UI visibility
16887         * flags, not what your app is currently applying.
16888         */
16889        public void onSystemUiVisibilityChange(int visibility);
16890    }
16891
16892    /**
16893     * Interface definition for a callback to be invoked when this view is attached
16894     * or detached from its window.
16895     */
16896    public interface OnAttachStateChangeListener {
16897        /**
16898         * Called when the view is attached to a window.
16899         * @param v The view that was attached
16900         */
16901        public void onViewAttachedToWindow(View v);
16902        /**
16903         * Called when the view is detached from a window.
16904         * @param v The view that was detached
16905         */
16906        public void onViewDetachedFromWindow(View v);
16907    }
16908
16909    private final class UnsetPressedState implements Runnable {
16910        public void run() {
16911            setPressed(false);
16912        }
16913    }
16914
16915    /**
16916     * Base class for derived classes that want to save and restore their own
16917     * state in {@link android.view.View#onSaveInstanceState()}.
16918     */
16919    public static class BaseSavedState extends AbsSavedState {
16920        /**
16921         * Constructor used when reading from a parcel. Reads the state of the superclass.
16922         *
16923         * @param source
16924         */
16925        public BaseSavedState(Parcel source) {
16926            super(source);
16927        }
16928
16929        /**
16930         * Constructor called by derived classes when creating their SavedState objects
16931         *
16932         * @param superState The state of the superclass of this view
16933         */
16934        public BaseSavedState(Parcelable superState) {
16935            super(superState);
16936        }
16937
16938        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16939                new Parcelable.Creator<BaseSavedState>() {
16940            public BaseSavedState createFromParcel(Parcel in) {
16941                return new BaseSavedState(in);
16942            }
16943
16944            public BaseSavedState[] newArray(int size) {
16945                return new BaseSavedState[size];
16946            }
16947        };
16948    }
16949
16950    /**
16951     * A set of information given to a view when it is attached to its parent
16952     * window.
16953     */
16954    static class AttachInfo {
16955        interface Callbacks {
16956            void playSoundEffect(int effectId);
16957            boolean performHapticFeedback(int effectId, boolean always);
16958        }
16959
16960        /**
16961         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16962         * to a Handler. This class contains the target (View) to invalidate and
16963         * the coordinates of the dirty rectangle.
16964         *
16965         * For performance purposes, this class also implements a pool of up to
16966         * POOL_LIMIT objects that get reused. This reduces memory allocations
16967         * whenever possible.
16968         */
16969        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16970            private static final int POOL_LIMIT = 10;
16971            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16972                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16973                        public InvalidateInfo newInstance() {
16974                            return new InvalidateInfo();
16975                        }
16976
16977                        public void onAcquired(InvalidateInfo element) {
16978                        }
16979
16980                        public void onReleased(InvalidateInfo element) {
16981                            element.target = null;
16982                        }
16983                    }, POOL_LIMIT)
16984            );
16985
16986            private InvalidateInfo mNext;
16987            private boolean mIsPooled;
16988
16989            View target;
16990
16991            int left;
16992            int top;
16993            int right;
16994            int bottom;
16995
16996            public void setNextPoolable(InvalidateInfo element) {
16997                mNext = element;
16998            }
16999
17000            public InvalidateInfo getNextPoolable() {
17001                return mNext;
17002            }
17003
17004            static InvalidateInfo acquire() {
17005                return sPool.acquire();
17006            }
17007
17008            void release() {
17009                sPool.release(this);
17010            }
17011
17012            public boolean isPooled() {
17013                return mIsPooled;
17014            }
17015
17016            public void setPooled(boolean isPooled) {
17017                mIsPooled = isPooled;
17018            }
17019        }
17020
17021        final IWindowSession mSession;
17022
17023        final IWindow mWindow;
17024
17025        final IBinder mWindowToken;
17026
17027        final Callbacks mRootCallbacks;
17028
17029        HardwareCanvas mHardwareCanvas;
17030
17031        /**
17032         * The top view of the hierarchy.
17033         */
17034        View mRootView;
17035
17036        IBinder mPanelParentWindowToken;
17037        Surface mSurface;
17038
17039        boolean mHardwareAccelerated;
17040        boolean mHardwareAccelerationRequested;
17041        HardwareRenderer mHardwareRenderer;
17042
17043        boolean mScreenOn;
17044
17045        /**
17046         * Scale factor used by the compatibility mode
17047         */
17048        float mApplicationScale;
17049
17050        /**
17051         * Indicates whether the application is in compatibility mode
17052         */
17053        boolean mScalingRequired;
17054
17055        /**
17056         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17057         */
17058        boolean mTurnOffWindowResizeAnim;
17059
17060        /**
17061         * Left position of this view's window
17062         */
17063        int mWindowLeft;
17064
17065        /**
17066         * Top position of this view's window
17067         */
17068        int mWindowTop;
17069
17070        /**
17071         * Indicates whether views need to use 32-bit drawing caches
17072         */
17073        boolean mUse32BitDrawingCache;
17074
17075        /**
17076         * For windows that are full-screen but using insets to layout inside
17077         * of the screen decorations, these are the current insets for the
17078         * content of the window.
17079         */
17080        final Rect mContentInsets = new Rect();
17081
17082        /**
17083         * For windows that are full-screen but using insets to layout inside
17084         * of the screen decorations, these are the current insets for the
17085         * actual visible parts of the window.
17086         */
17087        final Rect mVisibleInsets = new Rect();
17088
17089        /**
17090         * The internal insets given by this window.  This value is
17091         * supplied by the client (through
17092         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17093         * be given to the window manager when changed to be used in laying
17094         * out windows behind it.
17095         */
17096        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17097                = new ViewTreeObserver.InternalInsetsInfo();
17098
17099        /**
17100         * All views in the window's hierarchy that serve as scroll containers,
17101         * used to determine if the window can be resized or must be panned
17102         * to adjust for a soft input area.
17103         */
17104        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17105
17106        final KeyEvent.DispatcherState mKeyDispatchState
17107                = new KeyEvent.DispatcherState();
17108
17109        /**
17110         * Indicates whether the view's window currently has the focus.
17111         */
17112        boolean mHasWindowFocus;
17113
17114        /**
17115         * The current visibility of the window.
17116         */
17117        int mWindowVisibility;
17118
17119        /**
17120         * Indicates the time at which drawing started to occur.
17121         */
17122        long mDrawingTime;
17123
17124        /**
17125         * Indicates whether or not ignoring the DIRTY_MASK flags.
17126         */
17127        boolean mIgnoreDirtyState;
17128
17129        /**
17130         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17131         * to avoid clearing that flag prematurely.
17132         */
17133        boolean mSetIgnoreDirtyState = false;
17134
17135        /**
17136         * Indicates whether the view's window is currently in touch mode.
17137         */
17138        boolean mInTouchMode;
17139
17140        /**
17141         * Indicates that ViewAncestor should trigger a global layout change
17142         * the next time it performs a traversal
17143         */
17144        boolean mRecomputeGlobalAttributes;
17145
17146        /**
17147         * Always report new attributes at next traversal.
17148         */
17149        boolean mForceReportNewAttributes;
17150
17151        /**
17152         * Set during a traveral if any views want to keep the screen on.
17153         */
17154        boolean mKeepScreenOn;
17155
17156        /**
17157         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17158         */
17159        int mSystemUiVisibility;
17160
17161        /**
17162         * Hack to force certain system UI visibility flags to be cleared.
17163         */
17164        int mDisabledSystemUiVisibility;
17165
17166        /**
17167         * Last global system UI visibility reported by the window manager.
17168         */
17169        int mGlobalSystemUiVisibility;
17170
17171        /**
17172         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17173         * attached.
17174         */
17175        boolean mHasSystemUiListeners;
17176
17177        /**
17178         * Set if the visibility of any views has changed.
17179         */
17180        boolean mViewVisibilityChanged;
17181
17182        /**
17183         * Set to true if a view has been scrolled.
17184         */
17185        boolean mViewScrollChanged;
17186
17187        /**
17188         * Global to the view hierarchy used as a temporary for dealing with
17189         * x/y points in the transparent region computations.
17190         */
17191        final int[] mTransparentLocation = new int[2];
17192
17193        /**
17194         * Global to the view hierarchy used as a temporary for dealing with
17195         * x/y points in the ViewGroup.invalidateChild implementation.
17196         */
17197        final int[] mInvalidateChildLocation = new int[2];
17198
17199
17200        /**
17201         * Global to the view hierarchy used as a temporary for dealing with
17202         * x/y location when view is transformed.
17203         */
17204        final float[] mTmpTransformLocation = new float[2];
17205
17206        /**
17207         * The view tree observer used to dispatch global events like
17208         * layout, pre-draw, touch mode change, etc.
17209         */
17210        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17211
17212        /**
17213         * A Canvas used by the view hierarchy to perform bitmap caching.
17214         */
17215        Canvas mCanvas;
17216
17217        /**
17218         * The view root impl.
17219         */
17220        final ViewRootImpl mViewRootImpl;
17221
17222        /**
17223         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17224         * handler can be used to pump events in the UI events queue.
17225         */
17226        final Handler mHandler;
17227
17228        /**
17229         * Temporary for use in computing invalidate rectangles while
17230         * calling up the hierarchy.
17231         */
17232        final Rect mTmpInvalRect = new Rect();
17233
17234        /**
17235         * Temporary for use in computing hit areas with transformed views
17236         */
17237        final RectF mTmpTransformRect = new RectF();
17238
17239        /**
17240         * Temporary list for use in collecting focusable descendents of a view.
17241         */
17242        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17243
17244        /**
17245         * The id of the window for accessibility purposes.
17246         */
17247        int mAccessibilityWindowId = View.NO_ID;
17248
17249        /**
17250         * Whether to ingore not exposed for accessibility Views when
17251         * reporting the view tree to accessibility services.
17252         */
17253        boolean mIncludeNotImportantViews;
17254
17255        /**
17256         * The drawable for highlighting accessibility focus.
17257         */
17258        Drawable mAccessibilityFocusDrawable;
17259
17260        /**
17261         * Show where the margins, bounds and layout bounds are for each view.
17262         */
17263        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17264
17265        /**
17266         * Point used to compute visible regions.
17267         */
17268        final Point mPoint = new Point();
17269
17270        /**
17271         * Creates a new set of attachment information with the specified
17272         * events handler and thread.
17273         *
17274         * @param handler the events handler the view must use
17275         */
17276        AttachInfo(IWindowSession session, IWindow window,
17277                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17278            mSession = session;
17279            mWindow = window;
17280            mWindowToken = window.asBinder();
17281            mViewRootImpl = viewRootImpl;
17282            mHandler = handler;
17283            mRootCallbacks = effectPlayer;
17284        }
17285    }
17286
17287    /**
17288     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17289     * is supported. This avoids keeping too many unused fields in most
17290     * instances of View.</p>
17291     */
17292    private static class ScrollabilityCache implements Runnable {
17293
17294        /**
17295         * Scrollbars are not visible
17296         */
17297        public static final int OFF = 0;
17298
17299        /**
17300         * Scrollbars are visible
17301         */
17302        public static final int ON = 1;
17303
17304        /**
17305         * Scrollbars are fading away
17306         */
17307        public static final int FADING = 2;
17308
17309        public boolean fadeScrollBars;
17310
17311        public int fadingEdgeLength;
17312        public int scrollBarDefaultDelayBeforeFade;
17313        public int scrollBarFadeDuration;
17314
17315        public int scrollBarSize;
17316        public ScrollBarDrawable scrollBar;
17317        public float[] interpolatorValues;
17318        public View host;
17319
17320        public final Paint paint;
17321        public final Matrix matrix;
17322        public Shader shader;
17323
17324        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17325
17326        private static final float[] OPAQUE = { 255 };
17327        private static final float[] TRANSPARENT = { 0.0f };
17328
17329        /**
17330         * When fading should start. This time moves into the future every time
17331         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17332         */
17333        public long fadeStartTime;
17334
17335
17336        /**
17337         * The current state of the scrollbars: ON, OFF, or FADING
17338         */
17339        public int state = OFF;
17340
17341        private int mLastColor;
17342
17343        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17344            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17345            scrollBarSize = configuration.getScaledScrollBarSize();
17346            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17347            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17348
17349            paint = new Paint();
17350            matrix = new Matrix();
17351            // use use a height of 1, and then wack the matrix each time we
17352            // actually use it.
17353            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17354
17355            paint.setShader(shader);
17356            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17357            this.host = host;
17358        }
17359
17360        public void setFadeColor(int color) {
17361            if (color != 0 && color != mLastColor) {
17362                mLastColor = color;
17363                color |= 0xFF000000;
17364
17365                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17366                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17367
17368                paint.setShader(shader);
17369                // Restore the default transfer mode (src_over)
17370                paint.setXfermode(null);
17371            }
17372        }
17373
17374        public void run() {
17375            long now = AnimationUtils.currentAnimationTimeMillis();
17376            if (now >= fadeStartTime) {
17377
17378                // the animation fades the scrollbars out by changing
17379                // the opacity (alpha) from fully opaque to fully
17380                // transparent
17381                int nextFrame = (int) now;
17382                int framesCount = 0;
17383
17384                Interpolator interpolator = scrollBarInterpolator;
17385
17386                // Start opaque
17387                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17388
17389                // End transparent
17390                nextFrame += scrollBarFadeDuration;
17391                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17392
17393                state = FADING;
17394
17395                // Kick off the fade animation
17396                host.invalidate(true);
17397            }
17398        }
17399    }
17400
17401    /**
17402     * Resuable callback for sending
17403     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17404     */
17405    private class SendViewScrolledAccessibilityEvent implements Runnable {
17406        public volatile boolean mIsPending;
17407
17408        public void run() {
17409            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17410            mIsPending = false;
17411        }
17412    }
17413
17414    /**
17415     * <p>
17416     * This class represents a delegate that can be registered in a {@link View}
17417     * to enhance accessibility support via composition rather via inheritance.
17418     * It is specifically targeted to widget developers that extend basic View
17419     * classes i.e. classes in package android.view, that would like their
17420     * applications to be backwards compatible.
17421     * </p>
17422     * <div class="special reference">
17423     * <h3>Developer Guides</h3>
17424     * <p>For more information about making applications accessible, read the
17425     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17426     * developer guide.</p>
17427     * </div>
17428     * <p>
17429     * A scenario in which a developer would like to use an accessibility delegate
17430     * is overriding a method introduced in a later API version then the minimal API
17431     * version supported by the application. For example, the method
17432     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17433     * in API version 4 when the accessibility APIs were first introduced. If a
17434     * developer would like his application to run on API version 4 devices (assuming
17435     * all other APIs used by the application are version 4 or lower) and take advantage
17436     * of this method, instead of overriding the method which would break the application's
17437     * backwards compatibility, he can override the corresponding method in this
17438     * delegate and register the delegate in the target View if the API version of
17439     * the system is high enough i.e. the API version is same or higher to the API
17440     * version that introduced
17441     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17442     * </p>
17443     * <p>
17444     * Here is an example implementation:
17445     * </p>
17446     * <code><pre><p>
17447     * if (Build.VERSION.SDK_INT >= 14) {
17448     *     // If the API version is equal of higher than the version in
17449     *     // which onInitializeAccessibilityNodeInfo was introduced we
17450     *     // register a delegate with a customized implementation.
17451     *     View view = findViewById(R.id.view_id);
17452     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17453     *         public void onInitializeAccessibilityNodeInfo(View host,
17454     *                 AccessibilityNodeInfo info) {
17455     *             // Let the default implementation populate the info.
17456     *             super.onInitializeAccessibilityNodeInfo(host, info);
17457     *             // Set some other information.
17458     *             info.setEnabled(host.isEnabled());
17459     *         }
17460     *     });
17461     * }
17462     * </code></pre></p>
17463     * <p>
17464     * This delegate contains methods that correspond to the accessibility methods
17465     * in View. If a delegate has been specified the implementation in View hands
17466     * off handling to the corresponding method in this delegate. The default
17467     * implementation the delegate methods behaves exactly as the corresponding
17468     * method in View for the case of no accessibility delegate been set. Hence,
17469     * to customize the behavior of a View method, clients can override only the
17470     * corresponding delegate method without altering the behavior of the rest
17471     * accessibility related methods of the host view.
17472     * </p>
17473     */
17474    public static class AccessibilityDelegate {
17475
17476        /**
17477         * Sends an accessibility event of the given type. If accessibility is not
17478         * enabled this method has no effect.
17479         * <p>
17480         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17481         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17482         * been set.
17483         * </p>
17484         *
17485         * @param host The View hosting the delegate.
17486         * @param eventType The type of the event to send.
17487         *
17488         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17489         */
17490        public void sendAccessibilityEvent(View host, int eventType) {
17491            host.sendAccessibilityEventInternal(eventType);
17492        }
17493
17494        /**
17495         * Performs the specified accessibility action on the view. For
17496         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17497         * <p>
17498         * The default implementation behaves as
17499         * {@link View#performAccessibilityAction(int, Bundle)
17500         *  View#performAccessibilityAction(int, Bundle)} for the case of
17501         *  no accessibility delegate been set.
17502         * </p>
17503         *
17504         * @param action The action to perform.
17505         * @return Whether the action was performed.
17506         *
17507         * @see View#performAccessibilityAction(int, Bundle)
17508         *      View#performAccessibilityAction(int, Bundle)
17509         */
17510        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17511            return host.performAccessibilityActionInternal(action, args);
17512        }
17513
17514        /**
17515         * Sends an accessibility event. This method behaves exactly as
17516         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17517         * empty {@link AccessibilityEvent} and does not perform a check whether
17518         * accessibility is enabled.
17519         * <p>
17520         * The default implementation behaves as
17521         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17522         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17523         * the case of no accessibility delegate been set.
17524         * </p>
17525         *
17526         * @param host The View hosting the delegate.
17527         * @param event The event to send.
17528         *
17529         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17530         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17531         */
17532        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17533            host.sendAccessibilityEventUncheckedInternal(event);
17534        }
17535
17536        /**
17537         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17538         * to its children for adding their text content to the event.
17539         * <p>
17540         * The default implementation behaves as
17541         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17542         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17543         * the case of no accessibility delegate been set.
17544         * </p>
17545         *
17546         * @param host The View hosting the delegate.
17547         * @param event The event.
17548         * @return True if the event population was completed.
17549         *
17550         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17551         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17552         */
17553        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17554            return host.dispatchPopulateAccessibilityEventInternal(event);
17555        }
17556
17557        /**
17558         * Gives a chance to the host View to populate the accessibility event with its
17559         * text content.
17560         * <p>
17561         * The default implementation behaves as
17562         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17563         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17564         * the case of no accessibility delegate been set.
17565         * </p>
17566         *
17567         * @param host The View hosting the delegate.
17568         * @param event The accessibility event which to populate.
17569         *
17570         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17571         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17572         */
17573        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17574            host.onPopulateAccessibilityEventInternal(event);
17575        }
17576
17577        /**
17578         * Initializes an {@link AccessibilityEvent} with information about the
17579         * the host View which is the event source.
17580         * <p>
17581         * The default implementation behaves as
17582         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17583         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17584         * the case of no accessibility delegate been set.
17585         * </p>
17586         *
17587         * @param host The View hosting the delegate.
17588         * @param event The event to initialize.
17589         *
17590         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17591         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17592         */
17593        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17594            host.onInitializeAccessibilityEventInternal(event);
17595        }
17596
17597        /**
17598         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17599         * <p>
17600         * The default implementation behaves as
17601         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17602         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17603         * the case of no accessibility delegate been set.
17604         * </p>
17605         *
17606         * @param host The View hosting the delegate.
17607         * @param info The instance to initialize.
17608         *
17609         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17610         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17611         */
17612        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17613            host.onInitializeAccessibilityNodeInfoInternal(info);
17614        }
17615
17616        /**
17617         * Called when a child of the host View has requested sending an
17618         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17619         * to augment the event.
17620         * <p>
17621         * The default implementation behaves as
17622         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17623         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17624         * the case of no accessibility delegate been set.
17625         * </p>
17626         *
17627         * @param host The View hosting the delegate.
17628         * @param child The child which requests sending the event.
17629         * @param event The event to be sent.
17630         * @return True if the event should be sent
17631         *
17632         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17633         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17634         */
17635        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17636                AccessibilityEvent event) {
17637            return host.onRequestSendAccessibilityEventInternal(child, event);
17638        }
17639
17640        /**
17641         * Gets the provider for managing a virtual view hierarchy rooted at this View
17642         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17643         * that explore the window content.
17644         * <p>
17645         * The default implementation behaves as
17646         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17647         * the case of no accessibility delegate been set.
17648         * </p>
17649         *
17650         * @return The provider.
17651         *
17652         * @see AccessibilityNodeProvider
17653         */
17654        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17655            return null;
17656        }
17657    }
17658}
17659