View.java revision 76af556c8d70bad552bf5cc1047f0c018fc5f906
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 continue state.  In practice this means with any of system bar,
2244     * nav bar, and status bar shown, but not the space that would be needed
2245     * for an input method.
2246     *
2247     * <p>If you are using ActionBar in
2248     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2249     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2250     * insets it adds to those given to the application.
2251     */
2252    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2253
2254    /**
2255     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2256     * to be layed out as if it has requested
2257     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2258     * allows it to avoid artifacts when switching in and out of that mode, at
2259     * the expense that some of its user interface may be covered by screen
2260     * decorations when they are shown.  You can perform layout of your inner
2261     * UI elements to account for the navagation system UI through the
2262     * {@link #fitSystemWindows(Rect)} method.
2263     */
2264    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2265
2266    /**
2267     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2268     * to be layed out as if it has requested
2269     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2270     * allows it to avoid artifacts when switching in and out of that mode, at
2271     * the expense that some of its user interface may be covered by screen
2272     * decorations when they are shown.  You can perform layout of your inner
2273     * UI elements to account for non-fullscreen system UI through the
2274     * {@link #fitSystemWindows(Rect)} method.
2275     */
2276    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2277
2278    /**
2279     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2280     */
2281    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2282
2283    /**
2284     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2285     */
2286    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2287
2288    /**
2289     * @hide
2290     *
2291     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2292     * out of the public fields to keep the undefined bits out of the developer's way.
2293     *
2294     * Flag to make the status bar not expandable.  Unless you also
2295     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2296     */
2297    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2298
2299    /**
2300     * @hide
2301     *
2302     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2303     * out of the public fields to keep the undefined bits out of the developer's way.
2304     *
2305     * Flag to hide notification icons and scrolling ticker text.
2306     */
2307    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2308
2309    /**
2310     * @hide
2311     *
2312     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2313     * out of the public fields to keep the undefined bits out of the developer's way.
2314     *
2315     * Flag to disable incoming notification alerts.  This will not block
2316     * icons, but it will block sound, vibrating and other visual or aural notifications.
2317     */
2318    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2319
2320    /**
2321     * @hide
2322     *
2323     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2324     * out of the public fields to keep the undefined bits out of the developer's way.
2325     *
2326     * Flag to hide only the scrolling ticker.  Note that
2327     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2328     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2329     */
2330    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2331
2332    /**
2333     * @hide
2334     *
2335     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2336     * out of the public fields to keep the undefined bits out of the developer's way.
2337     *
2338     * Flag to hide the center system info area.
2339     */
2340    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2341
2342    /**
2343     * @hide
2344     *
2345     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2346     * out of the public fields to keep the undefined bits out of the developer's way.
2347     *
2348     * Flag to hide only the home button.  Don't use this
2349     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2350     */
2351    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2352
2353    /**
2354     * @hide
2355     *
2356     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2357     * out of the public fields to keep the undefined bits out of the developer's way.
2358     *
2359     * Flag to hide only the back button. Don't use this
2360     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2361     */
2362    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2363
2364    /**
2365     * @hide
2366     *
2367     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2368     * out of the public fields to keep the undefined bits out of the developer's way.
2369     *
2370     * Flag to hide only the clock.  You might use this if your activity has
2371     * its own clock making the status bar's clock redundant.
2372     */
2373    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2374
2375    /**
2376     * @hide
2377     *
2378     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2379     * out of the public fields to keep the undefined bits out of the developer's way.
2380     *
2381     * Flag to hide only the recent apps button. Don't use this
2382     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2383     */
2384    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2385
2386    /**
2387     * @hide
2388     */
2389    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2390
2391    /**
2392     * These are the system UI flags that can be cleared by events outside
2393     * of an application.  Currently this is just the ability to tap on the
2394     * screen while hiding the navigation bar to have it return.
2395     * @hide
2396     */
2397    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2398            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2399            | SYSTEM_UI_FLAG_FULLSCREEN;
2400
2401    /**
2402     * Flags that can impact the layout in relation to system UI.
2403     */
2404    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2405            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2406            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2407
2408    /**
2409     * Find views that render the specified text.
2410     *
2411     * @see #findViewsWithText(ArrayList, CharSequence, int)
2412     */
2413    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2414
2415    /**
2416     * Find find views that contain the specified content description.
2417     *
2418     * @see #findViewsWithText(ArrayList, CharSequence, int)
2419     */
2420    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2421
2422    /**
2423     * Find views that contain {@link AccessibilityNodeProvider}. Such
2424     * a View is a root of virtual view hierarchy and may contain the searched
2425     * text. If this flag is set Views with providers are automatically
2426     * added and it is a responsibility of the client to call the APIs of
2427     * the provider to determine whether the virtual tree rooted at this View
2428     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2429     * represeting the virtual views with this text.
2430     *
2431     * @see #findViewsWithText(ArrayList, CharSequence, int)
2432     *
2433     * @hide
2434     */
2435    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2436
2437    /**
2438     * Indicates that the screen has changed state and is now off.
2439     *
2440     * @see #onScreenStateChanged(int)
2441     */
2442    public static final int SCREEN_STATE_OFF = 0x0;
2443
2444    /**
2445     * Indicates that the screen has changed state and is now on.
2446     *
2447     * @see #onScreenStateChanged(int)
2448     */
2449    public static final int SCREEN_STATE_ON = 0x1;
2450
2451    /**
2452     * Controls the over-scroll mode for this view.
2453     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2454     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2455     * and {@link #OVER_SCROLL_NEVER}.
2456     */
2457    private int mOverScrollMode;
2458
2459    /**
2460     * The parent this view is attached to.
2461     * {@hide}
2462     *
2463     * @see #getParent()
2464     */
2465    protected ViewParent mParent;
2466
2467    /**
2468     * {@hide}
2469     */
2470    AttachInfo mAttachInfo;
2471
2472    /**
2473     * {@hide}
2474     */
2475    @ViewDebug.ExportedProperty(flagMapping = {
2476        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2477                name = "FORCE_LAYOUT"),
2478        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2479                name = "LAYOUT_REQUIRED"),
2480        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2481            name = "DRAWING_CACHE_INVALID", outputIf = false),
2482        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2483        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2484        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2485        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2486    })
2487    int mPrivateFlags;
2488    int mPrivateFlags2;
2489
2490    /**
2491     * This view's request for the visibility of the status bar.
2492     * @hide
2493     */
2494    @ViewDebug.ExportedProperty(flagMapping = {
2495        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2496                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2497                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2498        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2499                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2500                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2501        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2502                                equals = SYSTEM_UI_FLAG_VISIBLE,
2503                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2504    })
2505    int mSystemUiVisibility;
2506
2507    /**
2508     * Reference count for transient state.
2509     * @see #setHasTransientState(boolean)
2510     */
2511    int mTransientStateCount = 0;
2512
2513    /**
2514     * Count of how many windows this view has been attached to.
2515     */
2516    int mWindowAttachCount;
2517
2518    /**
2519     * The layout parameters associated with this view and used by the parent
2520     * {@link android.view.ViewGroup} to determine how this view should be
2521     * laid out.
2522     * {@hide}
2523     */
2524    protected ViewGroup.LayoutParams mLayoutParams;
2525
2526    /**
2527     * The view flags hold various views states.
2528     * {@hide}
2529     */
2530    @ViewDebug.ExportedProperty
2531    int mViewFlags;
2532
2533    static class TransformationInfo {
2534        /**
2535         * The transform matrix for the View. This transform is calculated internally
2536         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2537         * is used by default. Do *not* use this variable directly; instead call
2538         * getMatrix(), which will automatically recalculate the matrix if necessary
2539         * to get the correct matrix based on the latest rotation and scale properties.
2540         */
2541        private final Matrix mMatrix = new Matrix();
2542
2543        /**
2544         * The transform matrix for the View. This transform is calculated internally
2545         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2546         * is used by default. Do *not* use this variable directly; instead call
2547         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2548         * to get the correct matrix based on the latest rotation and scale properties.
2549         */
2550        private Matrix mInverseMatrix;
2551
2552        /**
2553         * An internal variable that tracks whether we need to recalculate the
2554         * transform matrix, based on whether the rotation or scaleX/Y properties
2555         * have changed since the matrix was last calculated.
2556         */
2557        boolean mMatrixDirty = false;
2558
2559        /**
2560         * An internal variable that tracks whether we need to recalculate the
2561         * transform matrix, based on whether the rotation or scaleX/Y properties
2562         * have changed since the matrix was last calculated.
2563         */
2564        private boolean mInverseMatrixDirty = true;
2565
2566        /**
2567         * A variable that tracks whether we need to recalculate the
2568         * transform matrix, based on whether the rotation or scaleX/Y properties
2569         * have changed since the matrix was last calculated. This variable
2570         * is only valid after a call to updateMatrix() or to a function that
2571         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2572         */
2573        private boolean mMatrixIsIdentity = true;
2574
2575        /**
2576         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2577         */
2578        private Camera mCamera = null;
2579
2580        /**
2581         * This matrix is used when computing the matrix for 3D rotations.
2582         */
2583        private Matrix matrix3D = null;
2584
2585        /**
2586         * These prev values are used to recalculate a centered pivot point when necessary. The
2587         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2588         * set), so thes values are only used then as well.
2589         */
2590        private int mPrevWidth = -1;
2591        private int mPrevHeight = -1;
2592
2593        /**
2594         * The degrees rotation around the vertical axis through the pivot point.
2595         */
2596        @ViewDebug.ExportedProperty
2597        float mRotationY = 0f;
2598
2599        /**
2600         * The degrees rotation around the horizontal axis through the pivot point.
2601         */
2602        @ViewDebug.ExportedProperty
2603        float mRotationX = 0f;
2604
2605        /**
2606         * The degrees rotation around the pivot point.
2607         */
2608        @ViewDebug.ExportedProperty
2609        float mRotation = 0f;
2610
2611        /**
2612         * The amount of translation of the object away from its left property (post-layout).
2613         */
2614        @ViewDebug.ExportedProperty
2615        float mTranslationX = 0f;
2616
2617        /**
2618         * The amount of translation of the object away from its top property (post-layout).
2619         */
2620        @ViewDebug.ExportedProperty
2621        float mTranslationY = 0f;
2622
2623        /**
2624         * The amount of scale in the x direction around the pivot point. A
2625         * value of 1 means no scaling is applied.
2626         */
2627        @ViewDebug.ExportedProperty
2628        float mScaleX = 1f;
2629
2630        /**
2631         * The amount of scale in the y direction around the pivot point. A
2632         * value of 1 means no scaling is applied.
2633         */
2634        @ViewDebug.ExportedProperty
2635        float mScaleY = 1f;
2636
2637        /**
2638         * The x location of the point around which the view is rotated and scaled.
2639         */
2640        @ViewDebug.ExportedProperty
2641        float mPivotX = 0f;
2642
2643        /**
2644         * The y location of the point around which the view is rotated and scaled.
2645         */
2646        @ViewDebug.ExportedProperty
2647        float mPivotY = 0f;
2648
2649        /**
2650         * The opacity of the View. This is a value from 0 to 1, where 0 means
2651         * completely transparent and 1 means completely opaque.
2652         */
2653        @ViewDebug.ExportedProperty
2654        float mAlpha = 1f;
2655    }
2656
2657    TransformationInfo mTransformationInfo;
2658
2659    private boolean mLastIsOpaque;
2660
2661    /**
2662     * Convenience value to check for float values that are close enough to zero to be considered
2663     * zero.
2664     */
2665    private static final float NONZERO_EPSILON = .001f;
2666
2667    /**
2668     * The distance in pixels from the left edge of this view's parent
2669     * to the left edge of this view.
2670     * {@hide}
2671     */
2672    @ViewDebug.ExportedProperty(category = "layout")
2673    protected int mLeft;
2674    /**
2675     * The distance in pixels from the left edge of this view's parent
2676     * to the right edge of this view.
2677     * {@hide}
2678     */
2679    @ViewDebug.ExportedProperty(category = "layout")
2680    protected int mRight;
2681    /**
2682     * The distance in pixels from the top edge of this view's parent
2683     * to the top edge of this view.
2684     * {@hide}
2685     */
2686    @ViewDebug.ExportedProperty(category = "layout")
2687    protected int mTop;
2688    /**
2689     * The distance in pixels from the top edge of this view's parent
2690     * to the bottom edge of this view.
2691     * {@hide}
2692     */
2693    @ViewDebug.ExportedProperty(category = "layout")
2694    protected int mBottom;
2695
2696    /**
2697     * The offset, in pixels, by which the content of this view is scrolled
2698     * horizontally.
2699     * {@hide}
2700     */
2701    @ViewDebug.ExportedProperty(category = "scrolling")
2702    protected int mScrollX;
2703    /**
2704     * The offset, in pixels, by which the content of this view is scrolled
2705     * vertically.
2706     * {@hide}
2707     */
2708    @ViewDebug.ExportedProperty(category = "scrolling")
2709    protected int mScrollY;
2710
2711    /**
2712     * The left padding in pixels, that is the distance in pixels between the
2713     * left edge of this view and the left edge of its content.
2714     * {@hide}
2715     */
2716    @ViewDebug.ExportedProperty(category = "padding")
2717    protected int mPaddingLeft;
2718    /**
2719     * The right padding in pixels, that is the distance in pixels between the
2720     * right edge of this view and the right edge of its content.
2721     * {@hide}
2722     */
2723    @ViewDebug.ExportedProperty(category = "padding")
2724    protected int mPaddingRight;
2725    /**
2726     * The top padding in pixels, that is the distance in pixels between the
2727     * top edge of this view and the top edge of its content.
2728     * {@hide}
2729     */
2730    @ViewDebug.ExportedProperty(category = "padding")
2731    protected int mPaddingTop;
2732    /**
2733     * The bottom padding in pixels, that is the distance in pixels between the
2734     * bottom edge of this view and the bottom edge of its content.
2735     * {@hide}
2736     */
2737    @ViewDebug.ExportedProperty(category = "padding")
2738    protected int mPaddingBottom;
2739
2740    /**
2741     * The layout insets in pixels, that is the distance in pixels between the
2742     * visible edges of this view its bounds.
2743     */
2744    private Insets mLayoutInsets;
2745
2746    /**
2747     * Briefly describes the view and is primarily used for accessibility support.
2748     */
2749    private CharSequence mContentDescription;
2750
2751    /**
2752     * Cache the paddingRight set by the user to append to the scrollbar's size.
2753     *
2754     * @hide
2755     */
2756    @ViewDebug.ExportedProperty(category = "padding")
2757    protected int mUserPaddingRight;
2758
2759    /**
2760     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2761     *
2762     * @hide
2763     */
2764    @ViewDebug.ExportedProperty(category = "padding")
2765    protected int mUserPaddingBottom;
2766
2767    /**
2768     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2769     *
2770     * @hide
2771     */
2772    @ViewDebug.ExportedProperty(category = "padding")
2773    protected int mUserPaddingLeft;
2774
2775    /**
2776     * Cache if the user padding is relative.
2777     *
2778     */
2779    @ViewDebug.ExportedProperty(category = "padding")
2780    boolean mUserPaddingRelative;
2781
2782    /**
2783     * Cache the paddingStart set by the user to append to the scrollbar's size.
2784     *
2785     */
2786    @ViewDebug.ExportedProperty(category = "padding")
2787    int mUserPaddingStart;
2788
2789    /**
2790     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2791     *
2792     */
2793    @ViewDebug.ExportedProperty(category = "padding")
2794    int mUserPaddingEnd;
2795
2796    /**
2797     * @hide
2798     */
2799    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2800    /**
2801     * @hide
2802     */
2803    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2804
2805    private Drawable mBackground;
2806
2807    private int mBackgroundResource;
2808    private boolean mBackgroundSizeChanged;
2809
2810    static class ListenerInfo {
2811        /**
2812         * Listener used to dispatch focus change events.
2813         * This field should be made private, so it is hidden from the SDK.
2814         * {@hide}
2815         */
2816        protected OnFocusChangeListener mOnFocusChangeListener;
2817
2818        /**
2819         * Listeners for layout change events.
2820         */
2821        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2822
2823        /**
2824         * Listeners for attach events.
2825         */
2826        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2827
2828        /**
2829         * Listener used to dispatch click events.
2830         * This field should be made private, so it is hidden from the SDK.
2831         * {@hide}
2832         */
2833        public OnClickListener mOnClickListener;
2834
2835        /**
2836         * Listener used to dispatch long click events.
2837         * This field should be made private, so it is hidden from the SDK.
2838         * {@hide}
2839         */
2840        protected OnLongClickListener mOnLongClickListener;
2841
2842        /**
2843         * Listener used to build the context menu.
2844         * This field should be made private, so it is hidden from the SDK.
2845         * {@hide}
2846         */
2847        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2848
2849        private OnKeyListener mOnKeyListener;
2850
2851        private OnTouchListener mOnTouchListener;
2852
2853        private OnHoverListener mOnHoverListener;
2854
2855        private OnGenericMotionListener mOnGenericMotionListener;
2856
2857        private OnDragListener mOnDragListener;
2858
2859        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2860    }
2861
2862    ListenerInfo mListenerInfo;
2863
2864    /**
2865     * The application environment this view lives in.
2866     * This field should be made private, so it is hidden from the SDK.
2867     * {@hide}
2868     */
2869    protected Context mContext;
2870
2871    private final Resources mResources;
2872
2873    private ScrollabilityCache mScrollCache;
2874
2875    private int[] mDrawableState = null;
2876
2877    /**
2878     * Set to true when drawing cache is enabled and cannot be created.
2879     *
2880     * @hide
2881     */
2882    public boolean mCachingFailed;
2883
2884    private Bitmap mDrawingCache;
2885    private Bitmap mUnscaledDrawingCache;
2886    private HardwareLayer mHardwareLayer;
2887    DisplayList mDisplayList;
2888
2889    /**
2890     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2891     * the user may specify which view to go to next.
2892     */
2893    private int mNextFocusLeftId = View.NO_ID;
2894
2895    /**
2896     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2897     * the user may specify which view to go to next.
2898     */
2899    private int mNextFocusRightId = View.NO_ID;
2900
2901    /**
2902     * When this view has focus and the next focus is {@link #FOCUS_UP},
2903     * the user may specify which view to go to next.
2904     */
2905    private int mNextFocusUpId = View.NO_ID;
2906
2907    /**
2908     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2909     * the user may specify which view to go to next.
2910     */
2911    private int mNextFocusDownId = View.NO_ID;
2912
2913    /**
2914     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2915     * the user may specify which view to go to next.
2916     */
2917    int mNextFocusForwardId = View.NO_ID;
2918
2919    private CheckForLongPress mPendingCheckForLongPress;
2920    private CheckForTap mPendingCheckForTap = null;
2921    private PerformClick mPerformClick;
2922    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2923
2924    private UnsetPressedState mUnsetPressedState;
2925
2926    /**
2927     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2928     * up event while a long press is invoked as soon as the long press duration is reached, so
2929     * a long press could be performed before the tap is checked, in which case the tap's action
2930     * should not be invoked.
2931     */
2932    private boolean mHasPerformedLongPress;
2933
2934    /**
2935     * The minimum height of the view. We'll try our best to have the height
2936     * of this view to at least this amount.
2937     */
2938    @ViewDebug.ExportedProperty(category = "measurement")
2939    private int mMinHeight;
2940
2941    /**
2942     * The minimum width of the view. We'll try our best to have the width
2943     * of this view to at least this amount.
2944     */
2945    @ViewDebug.ExportedProperty(category = "measurement")
2946    private int mMinWidth;
2947
2948    /**
2949     * The delegate to handle touch events that are physically in this view
2950     * but should be handled by another view.
2951     */
2952    private TouchDelegate mTouchDelegate = null;
2953
2954    /**
2955     * Solid color to use as a background when creating the drawing cache. Enables
2956     * the cache to use 16 bit bitmaps instead of 32 bit.
2957     */
2958    private int mDrawingCacheBackgroundColor = 0;
2959
2960    /**
2961     * Special tree observer used when mAttachInfo is null.
2962     */
2963    private ViewTreeObserver mFloatingTreeObserver;
2964
2965    /**
2966     * Cache the touch slop from the context that created the view.
2967     */
2968    private int mTouchSlop;
2969
2970    /**
2971     * Object that handles automatic animation of view properties.
2972     */
2973    private ViewPropertyAnimator mAnimator = null;
2974
2975    /**
2976     * Flag indicating that a drag can cross window boundaries.  When
2977     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2978     * with this flag set, all visible applications will be able to participate
2979     * in the drag operation and receive the dragged content.
2980     *
2981     * @hide
2982     */
2983    public static final int DRAG_FLAG_GLOBAL = 1;
2984
2985    /**
2986     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2987     */
2988    private float mVerticalScrollFactor;
2989
2990    /**
2991     * Position of the vertical scroll bar.
2992     */
2993    private int mVerticalScrollbarPosition;
2994
2995    /**
2996     * Position the scroll bar at the default position as determined by the system.
2997     */
2998    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2999
3000    /**
3001     * Position the scroll bar along the left edge.
3002     */
3003    public static final int SCROLLBAR_POSITION_LEFT = 1;
3004
3005    /**
3006     * Position the scroll bar along the right edge.
3007     */
3008    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3009
3010    /**
3011     * Indicates that the view does not have a layer.
3012     *
3013     * @see #getLayerType()
3014     * @see #setLayerType(int, android.graphics.Paint)
3015     * @see #LAYER_TYPE_SOFTWARE
3016     * @see #LAYER_TYPE_HARDWARE
3017     */
3018    public static final int LAYER_TYPE_NONE = 0;
3019
3020    /**
3021     * <p>Indicates that the view has a software layer. A software layer is backed
3022     * by a bitmap and causes the view to be rendered using Android's software
3023     * rendering pipeline, even if hardware acceleration is enabled.</p>
3024     *
3025     * <p>Software layers have various usages:</p>
3026     * <p>When the application is not using hardware acceleration, a software layer
3027     * is useful to apply a specific color filter and/or blending mode and/or
3028     * translucency to a view and all its children.</p>
3029     * <p>When the application is using hardware acceleration, a software layer
3030     * is useful to render drawing primitives not supported by the hardware
3031     * accelerated pipeline. It can also be used to cache a complex view tree
3032     * into a texture and reduce the complexity of drawing operations. For instance,
3033     * when animating a complex view tree with a translation, a software layer can
3034     * be used to render the view tree only once.</p>
3035     * <p>Software layers should be avoided when the affected view tree updates
3036     * often. Every update will require to re-render the software layer, which can
3037     * potentially be slow (particularly when hardware acceleration is turned on
3038     * since the layer will have to be uploaded into a hardware texture after every
3039     * update.)</p>
3040     *
3041     * @see #getLayerType()
3042     * @see #setLayerType(int, android.graphics.Paint)
3043     * @see #LAYER_TYPE_NONE
3044     * @see #LAYER_TYPE_HARDWARE
3045     */
3046    public static final int LAYER_TYPE_SOFTWARE = 1;
3047
3048    /**
3049     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3050     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3051     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3052     * rendering pipeline, but only if hardware acceleration is turned on for the
3053     * view hierarchy. When hardware acceleration is turned off, hardware layers
3054     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3055     *
3056     * <p>A hardware layer is useful to apply a specific color filter and/or
3057     * blending mode and/or translucency to a view and all its children.</p>
3058     * <p>A hardware layer can be used to cache a complex view tree into a
3059     * texture and reduce the complexity of drawing operations. For instance,
3060     * when animating a complex view tree with a translation, a hardware layer can
3061     * be used to render the view tree only once.</p>
3062     * <p>A hardware layer can also be used to increase the rendering quality when
3063     * rotation transformations are applied on a view. It can also be used to
3064     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3065     *
3066     * @see #getLayerType()
3067     * @see #setLayerType(int, android.graphics.Paint)
3068     * @see #LAYER_TYPE_NONE
3069     * @see #LAYER_TYPE_SOFTWARE
3070     */
3071    public static final int LAYER_TYPE_HARDWARE = 2;
3072
3073    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3074            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3075            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3076            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3077    })
3078    int mLayerType = LAYER_TYPE_NONE;
3079    Paint mLayerPaint;
3080    Rect mLocalDirtyRect;
3081
3082    /**
3083     * Set to true when the view is sending hover accessibility events because it
3084     * is the innermost hovered view.
3085     */
3086    private boolean mSendingHoverAccessibilityEvents;
3087
3088    /**
3089     * Simple constructor to use when creating a view from code.
3090     *
3091     * @param context The Context the view is running in, through which it can
3092     *        access the current theme, resources, etc.
3093     */
3094    public View(Context context) {
3095        mContext = context;
3096        mResources = context != null ? context.getResources() : null;
3097        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3098        // Set layout and text direction defaults
3099        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3100                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3101                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3102                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3103        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3104        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3105        mUserPaddingStart = -1;
3106        mUserPaddingEnd = -1;
3107        mUserPaddingRelative = false;
3108    }
3109
3110    /**
3111     * Delegate for injecting accessiblity functionality.
3112     */
3113    AccessibilityDelegate mAccessibilityDelegate;
3114
3115    /**
3116     * Consistency verifier for debugging purposes.
3117     * @hide
3118     */
3119    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3120            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3121                    new InputEventConsistencyVerifier(this, 0) : null;
3122
3123    /**
3124     * Constructor that is called when inflating a view from XML. This is called
3125     * when a view is being constructed from an XML file, supplying attributes
3126     * that were specified in the XML file. This version uses a default style of
3127     * 0, so the only attribute values applied are those in the Context's Theme
3128     * and the given AttributeSet.
3129     *
3130     * <p>
3131     * The method onFinishInflate() will be called after all children have been
3132     * added.
3133     *
3134     * @param context The Context the view is running in, through which it can
3135     *        access the current theme, resources, etc.
3136     * @param attrs The attributes of the XML tag that is inflating the view.
3137     * @see #View(Context, AttributeSet, int)
3138     */
3139    public View(Context context, AttributeSet attrs) {
3140        this(context, attrs, 0);
3141    }
3142
3143    /**
3144     * Perform inflation from XML and apply a class-specific base style. This
3145     * constructor of View allows subclasses to use their own base style when
3146     * they are inflating. For example, a Button class's constructor would call
3147     * this version of the super class constructor and supply
3148     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3149     * the theme's button style to modify all of the base view attributes (in
3150     * particular its background) as well as the Button class's attributes.
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     * @param defStyle The default style to apply to this view. If 0, no style
3156     *        will be applied (beyond what is included in the theme). This may
3157     *        either be an attribute resource, whose value will be retrieved
3158     *        from the current theme, or an explicit style resource.
3159     * @see #View(Context, AttributeSet)
3160     */
3161    public View(Context context, AttributeSet attrs, int defStyle) {
3162        this(context);
3163
3164        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3165                defStyle, 0);
3166
3167        Drawable background = null;
3168
3169        int leftPadding = -1;
3170        int topPadding = -1;
3171        int rightPadding = -1;
3172        int bottomPadding = -1;
3173        int startPadding = -1;
3174        int endPadding = -1;
3175
3176        int padding = -1;
3177
3178        int viewFlagValues = 0;
3179        int viewFlagMasks = 0;
3180
3181        boolean setScrollContainer = false;
3182
3183        int x = 0;
3184        int y = 0;
3185
3186        float tx = 0;
3187        float ty = 0;
3188        float rotation = 0;
3189        float rotationX = 0;
3190        float rotationY = 0;
3191        float sx = 1f;
3192        float sy = 1f;
3193        boolean transformSet = false;
3194
3195        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3196
3197        int overScrollMode = mOverScrollMode;
3198        final int N = a.getIndexCount();
3199        for (int i = 0; i < N; i++) {
3200            int attr = a.getIndex(i);
3201            switch (attr) {
3202                case com.android.internal.R.styleable.View_background:
3203                    background = a.getDrawable(attr);
3204                    break;
3205                case com.android.internal.R.styleable.View_padding:
3206                    padding = a.getDimensionPixelSize(attr, -1);
3207                    break;
3208                 case com.android.internal.R.styleable.View_paddingLeft:
3209                    leftPadding = a.getDimensionPixelSize(attr, -1);
3210                    break;
3211                case com.android.internal.R.styleable.View_paddingTop:
3212                    topPadding = a.getDimensionPixelSize(attr, -1);
3213                    break;
3214                case com.android.internal.R.styleable.View_paddingRight:
3215                    rightPadding = a.getDimensionPixelSize(attr, -1);
3216                    break;
3217                case com.android.internal.R.styleable.View_paddingBottom:
3218                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3219                    break;
3220                case com.android.internal.R.styleable.View_paddingStart:
3221                    startPadding = a.getDimensionPixelSize(attr, -1);
3222                    break;
3223                case com.android.internal.R.styleable.View_paddingEnd:
3224                    endPadding = a.getDimensionPixelSize(attr, -1);
3225                    break;
3226                case com.android.internal.R.styleable.View_scrollX:
3227                    x = a.getDimensionPixelOffset(attr, 0);
3228                    break;
3229                case com.android.internal.R.styleable.View_scrollY:
3230                    y = a.getDimensionPixelOffset(attr, 0);
3231                    break;
3232                case com.android.internal.R.styleable.View_alpha:
3233                    setAlpha(a.getFloat(attr, 1f));
3234                    break;
3235                case com.android.internal.R.styleable.View_transformPivotX:
3236                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3237                    break;
3238                case com.android.internal.R.styleable.View_transformPivotY:
3239                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3240                    break;
3241                case com.android.internal.R.styleable.View_translationX:
3242                    tx = a.getDimensionPixelOffset(attr, 0);
3243                    transformSet = true;
3244                    break;
3245                case com.android.internal.R.styleable.View_translationY:
3246                    ty = a.getDimensionPixelOffset(attr, 0);
3247                    transformSet = true;
3248                    break;
3249                case com.android.internal.R.styleable.View_rotation:
3250                    rotation = a.getFloat(attr, 0);
3251                    transformSet = true;
3252                    break;
3253                case com.android.internal.R.styleable.View_rotationX:
3254                    rotationX = a.getFloat(attr, 0);
3255                    transformSet = true;
3256                    break;
3257                case com.android.internal.R.styleable.View_rotationY:
3258                    rotationY = a.getFloat(attr, 0);
3259                    transformSet = true;
3260                    break;
3261                case com.android.internal.R.styleable.View_scaleX:
3262                    sx = a.getFloat(attr, 1f);
3263                    transformSet = true;
3264                    break;
3265                case com.android.internal.R.styleable.View_scaleY:
3266                    sy = a.getFloat(attr, 1f);
3267                    transformSet = true;
3268                    break;
3269                case com.android.internal.R.styleable.View_id:
3270                    mID = a.getResourceId(attr, NO_ID);
3271                    break;
3272                case com.android.internal.R.styleable.View_tag:
3273                    mTag = a.getText(attr);
3274                    break;
3275                case com.android.internal.R.styleable.View_fitsSystemWindows:
3276                    if (a.getBoolean(attr, false)) {
3277                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3278                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3279                    }
3280                    break;
3281                case com.android.internal.R.styleable.View_focusable:
3282                    if (a.getBoolean(attr, false)) {
3283                        viewFlagValues |= FOCUSABLE;
3284                        viewFlagMasks |= FOCUSABLE_MASK;
3285                    }
3286                    break;
3287                case com.android.internal.R.styleable.View_focusableInTouchMode:
3288                    if (a.getBoolean(attr, false)) {
3289                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3290                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3291                    }
3292                    break;
3293                case com.android.internal.R.styleable.View_clickable:
3294                    if (a.getBoolean(attr, false)) {
3295                        viewFlagValues |= CLICKABLE;
3296                        viewFlagMasks |= CLICKABLE;
3297                    }
3298                    break;
3299                case com.android.internal.R.styleable.View_longClickable:
3300                    if (a.getBoolean(attr, false)) {
3301                        viewFlagValues |= LONG_CLICKABLE;
3302                        viewFlagMasks |= LONG_CLICKABLE;
3303                    }
3304                    break;
3305                case com.android.internal.R.styleable.View_saveEnabled:
3306                    if (!a.getBoolean(attr, true)) {
3307                        viewFlagValues |= SAVE_DISABLED;
3308                        viewFlagMasks |= SAVE_DISABLED_MASK;
3309                    }
3310                    break;
3311                case com.android.internal.R.styleable.View_duplicateParentState:
3312                    if (a.getBoolean(attr, false)) {
3313                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3314                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3315                    }
3316                    break;
3317                case com.android.internal.R.styleable.View_visibility:
3318                    final int visibility = a.getInt(attr, 0);
3319                    if (visibility != 0) {
3320                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3321                        viewFlagMasks |= VISIBILITY_MASK;
3322                    }
3323                    break;
3324                case com.android.internal.R.styleable.View_layoutDirection:
3325                    // Clear any layout direction flags (included resolved bits) already set
3326                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3327                    // Set the layout direction flags depending on the value of the attribute
3328                    final int layoutDirection = a.getInt(attr, -1);
3329                    final int value = (layoutDirection != -1) ?
3330                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3331                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3332                    break;
3333                case com.android.internal.R.styleable.View_drawingCacheQuality:
3334                    final int cacheQuality = a.getInt(attr, 0);
3335                    if (cacheQuality != 0) {
3336                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3337                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3338                    }
3339                    break;
3340                case com.android.internal.R.styleable.View_contentDescription:
3341                    mContentDescription = a.getString(attr);
3342                    break;
3343                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3344                    if (!a.getBoolean(attr, true)) {
3345                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3346                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3347                    }
3348                    break;
3349                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3350                    if (!a.getBoolean(attr, true)) {
3351                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3352                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3353                    }
3354                    break;
3355                case R.styleable.View_scrollbars:
3356                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3357                    if (scrollbars != SCROLLBARS_NONE) {
3358                        viewFlagValues |= scrollbars;
3359                        viewFlagMasks |= SCROLLBARS_MASK;
3360                        initializeScrollbars(a);
3361                    }
3362                    break;
3363                //noinspection deprecation
3364                case R.styleable.View_fadingEdge:
3365                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3366                        // Ignore the attribute starting with ICS
3367                        break;
3368                    }
3369                    // With builds < ICS, fall through and apply fading edges
3370                case R.styleable.View_requiresFadingEdge:
3371                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3372                    if (fadingEdge != FADING_EDGE_NONE) {
3373                        viewFlagValues |= fadingEdge;
3374                        viewFlagMasks |= FADING_EDGE_MASK;
3375                        initializeFadingEdge(a);
3376                    }
3377                    break;
3378                case R.styleable.View_scrollbarStyle:
3379                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3380                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3381                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3382                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3383                    }
3384                    break;
3385                case R.styleable.View_isScrollContainer:
3386                    setScrollContainer = true;
3387                    if (a.getBoolean(attr, false)) {
3388                        setScrollContainer(true);
3389                    }
3390                    break;
3391                case com.android.internal.R.styleable.View_keepScreenOn:
3392                    if (a.getBoolean(attr, false)) {
3393                        viewFlagValues |= KEEP_SCREEN_ON;
3394                        viewFlagMasks |= KEEP_SCREEN_ON;
3395                    }
3396                    break;
3397                case R.styleable.View_filterTouchesWhenObscured:
3398                    if (a.getBoolean(attr, false)) {
3399                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3400                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3401                    }
3402                    break;
3403                case R.styleable.View_nextFocusLeft:
3404                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3405                    break;
3406                case R.styleable.View_nextFocusRight:
3407                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3408                    break;
3409                case R.styleable.View_nextFocusUp:
3410                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3411                    break;
3412                case R.styleable.View_nextFocusDown:
3413                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3414                    break;
3415                case R.styleable.View_nextFocusForward:
3416                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3417                    break;
3418                case R.styleable.View_minWidth:
3419                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3420                    break;
3421                case R.styleable.View_minHeight:
3422                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3423                    break;
3424                case R.styleable.View_onClick:
3425                    if (context.isRestricted()) {
3426                        throw new IllegalStateException("The android:onClick attribute cannot "
3427                                + "be used within a restricted context");
3428                    }
3429
3430                    final String handlerName = a.getString(attr);
3431                    if (handlerName != null) {
3432                        setOnClickListener(new OnClickListener() {
3433                            private Method mHandler;
3434
3435                            public void onClick(View v) {
3436                                if (mHandler == null) {
3437                                    try {
3438                                        mHandler = getContext().getClass().getMethod(handlerName,
3439                                                View.class);
3440                                    } catch (NoSuchMethodException e) {
3441                                        int id = getId();
3442                                        String idText = id == NO_ID ? "" : " with id '"
3443                                                + getContext().getResources().getResourceEntryName(
3444                                                    id) + "'";
3445                                        throw new IllegalStateException("Could not find a method " +
3446                                                handlerName + "(View) in the activity "
3447                                                + getContext().getClass() + " for onClick handler"
3448                                                + " on view " + View.this.getClass() + idText, e);
3449                                    }
3450                                }
3451
3452                                try {
3453                                    mHandler.invoke(getContext(), View.this);
3454                                } catch (IllegalAccessException e) {
3455                                    throw new IllegalStateException("Could not execute non "
3456                                            + "public method of the activity", e);
3457                                } catch (InvocationTargetException e) {
3458                                    throw new IllegalStateException("Could not execute "
3459                                            + "method of the activity", e);
3460                                }
3461                            }
3462                        });
3463                    }
3464                    break;
3465                case R.styleable.View_overScrollMode:
3466                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3467                    break;
3468                case R.styleable.View_verticalScrollbarPosition:
3469                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3470                    break;
3471                case R.styleable.View_layerType:
3472                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3473                    break;
3474                case R.styleable.View_textDirection:
3475                    // Clear any text direction flag already set
3476                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3477                    // Set the text direction flags depending on the value of the attribute
3478                    final int textDirection = a.getInt(attr, -1);
3479                    if (textDirection != -1) {
3480                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3481                    }
3482                    break;
3483                case R.styleable.View_textAlignment:
3484                    // Clear any text alignment flag already set
3485                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3486                    // Set the text alignment flag depending on the value of the attribute
3487                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3488                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3489                    break;
3490                case R.styleable.View_importantForAccessibility:
3491                    setImportantForAccessibility(a.getInt(attr,
3492                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3493            }
3494        }
3495
3496        a.recycle();
3497
3498        setOverScrollMode(overScrollMode);
3499
3500        if (background != null) {
3501            setBackground(background);
3502        }
3503
3504        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3505        // layout direction). Those cached values will be used later during padding resolution.
3506        mUserPaddingStart = startPadding;
3507        mUserPaddingEnd = endPadding;
3508
3509        updateUserPaddingRelative();
3510
3511        if (padding >= 0) {
3512            leftPadding = padding;
3513            topPadding = padding;
3514            rightPadding = padding;
3515            bottomPadding = padding;
3516        }
3517
3518        // If the user specified the padding (either with android:padding or
3519        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3520        // use the default padding or the padding from the background drawable
3521        // (stored at this point in mPadding*)
3522        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3523                topPadding >= 0 ? topPadding : mPaddingTop,
3524                rightPadding >= 0 ? rightPadding : mPaddingRight,
3525                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3526
3527        if (viewFlagMasks != 0) {
3528            setFlags(viewFlagValues, viewFlagMasks);
3529        }
3530
3531        // Needs to be called after mViewFlags is set
3532        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3533            recomputePadding();
3534        }
3535
3536        if (x != 0 || y != 0) {
3537            scrollTo(x, y);
3538        }
3539
3540        if (transformSet) {
3541            setTranslationX(tx);
3542            setTranslationY(ty);
3543            setRotation(rotation);
3544            setRotationX(rotationX);
3545            setRotationY(rotationY);
3546            setScaleX(sx);
3547            setScaleY(sy);
3548        }
3549
3550        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3551            setScrollContainer(true);
3552        }
3553
3554        computeOpaqueFlags();
3555    }
3556
3557    private void updateUserPaddingRelative() {
3558        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3559    }
3560
3561    /**
3562     * Non-public constructor for use in testing
3563     */
3564    View() {
3565        mResources = null;
3566    }
3567
3568    /**
3569     * <p>
3570     * Initializes the fading edges from a given set of styled attributes. This
3571     * method should be called by subclasses that need fading edges and when an
3572     * instance of these subclasses is created programmatically rather than
3573     * being inflated from XML. This method is automatically called when the XML
3574     * is inflated.
3575     * </p>
3576     *
3577     * @param a the styled attributes set to initialize the fading edges from
3578     */
3579    protected void initializeFadingEdge(TypedArray a) {
3580        initScrollCache();
3581
3582        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3583                R.styleable.View_fadingEdgeLength,
3584                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3585    }
3586
3587    /**
3588     * Returns the size of the vertical faded edges used to indicate that more
3589     * content in this view is visible.
3590     *
3591     * @return The size in pixels of the vertical faded edge or 0 if vertical
3592     *         faded edges are not enabled for this view.
3593     * @attr ref android.R.styleable#View_fadingEdgeLength
3594     */
3595    public int getVerticalFadingEdgeLength() {
3596        if (isVerticalFadingEdgeEnabled()) {
3597            ScrollabilityCache cache = mScrollCache;
3598            if (cache != null) {
3599                return cache.fadingEdgeLength;
3600            }
3601        }
3602        return 0;
3603    }
3604
3605    /**
3606     * Set the size of the faded edge used to indicate that more content in this
3607     * view is available.  Will not change whether the fading edge is enabled; use
3608     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3609     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3610     * for the vertical or horizontal fading edges.
3611     *
3612     * @param length The size in pixels of the faded edge used to indicate that more
3613     *        content in this view is visible.
3614     */
3615    public void setFadingEdgeLength(int length) {
3616        initScrollCache();
3617        mScrollCache.fadingEdgeLength = length;
3618    }
3619
3620    /**
3621     * Returns the size of the horizontal faded edges used to indicate that more
3622     * content in this view is visible.
3623     *
3624     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3625     *         faded edges are not enabled for this view.
3626     * @attr ref android.R.styleable#View_fadingEdgeLength
3627     */
3628    public int getHorizontalFadingEdgeLength() {
3629        if (isHorizontalFadingEdgeEnabled()) {
3630            ScrollabilityCache cache = mScrollCache;
3631            if (cache != null) {
3632                return cache.fadingEdgeLength;
3633            }
3634        }
3635        return 0;
3636    }
3637
3638    /**
3639     * Returns the width of the vertical scrollbar.
3640     *
3641     * @return The width in pixels of the vertical scrollbar or 0 if there
3642     *         is no vertical scrollbar.
3643     */
3644    public int getVerticalScrollbarWidth() {
3645        ScrollabilityCache cache = mScrollCache;
3646        if (cache != null) {
3647            ScrollBarDrawable scrollBar = cache.scrollBar;
3648            if (scrollBar != null) {
3649                int size = scrollBar.getSize(true);
3650                if (size <= 0) {
3651                    size = cache.scrollBarSize;
3652                }
3653                return size;
3654            }
3655            return 0;
3656        }
3657        return 0;
3658    }
3659
3660    /**
3661     * Returns the height of the horizontal scrollbar.
3662     *
3663     * @return The height in pixels of the horizontal scrollbar or 0 if
3664     *         there is no horizontal scrollbar.
3665     */
3666    protected int getHorizontalScrollbarHeight() {
3667        ScrollabilityCache cache = mScrollCache;
3668        if (cache != null) {
3669            ScrollBarDrawable scrollBar = cache.scrollBar;
3670            if (scrollBar != null) {
3671                int size = scrollBar.getSize(false);
3672                if (size <= 0) {
3673                    size = cache.scrollBarSize;
3674                }
3675                return size;
3676            }
3677            return 0;
3678        }
3679        return 0;
3680    }
3681
3682    /**
3683     * <p>
3684     * Initializes the scrollbars from a given set of styled attributes. This
3685     * method should be called by subclasses that need scrollbars and when an
3686     * instance of these subclasses is created programmatically rather than
3687     * being inflated from XML. This method is automatically called when the XML
3688     * is inflated.
3689     * </p>
3690     *
3691     * @param a the styled attributes set to initialize the scrollbars from
3692     */
3693    protected void initializeScrollbars(TypedArray a) {
3694        initScrollCache();
3695
3696        final ScrollabilityCache scrollabilityCache = mScrollCache;
3697
3698        if (scrollabilityCache.scrollBar == null) {
3699            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3700        }
3701
3702        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3703
3704        if (!fadeScrollbars) {
3705            scrollabilityCache.state = ScrollabilityCache.ON;
3706        }
3707        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3708
3709
3710        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3711                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3712                        .getScrollBarFadeDuration());
3713        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3714                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3715                ViewConfiguration.getScrollDefaultDelay());
3716
3717
3718        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3719                com.android.internal.R.styleable.View_scrollbarSize,
3720                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3721
3722        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3723        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3724
3725        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3726        if (thumb != null) {
3727            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3728        }
3729
3730        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3731                false);
3732        if (alwaysDraw) {
3733            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3734        }
3735
3736        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3737        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3738
3739        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3740        if (thumb != null) {
3741            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3742        }
3743
3744        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3745                false);
3746        if (alwaysDraw) {
3747            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3748        }
3749
3750        // Re-apply user/background padding so that scrollbar(s) get added
3751        resolvePadding();
3752    }
3753
3754    /**
3755     * <p>
3756     * Initalizes the scrollability cache if necessary.
3757     * </p>
3758     */
3759    private void initScrollCache() {
3760        if (mScrollCache == null) {
3761            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3762        }
3763    }
3764
3765    private ScrollabilityCache getScrollCache() {
3766        initScrollCache();
3767        return mScrollCache;
3768    }
3769
3770    /**
3771     * Set the position of the vertical scroll bar. Should be one of
3772     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3773     * {@link #SCROLLBAR_POSITION_RIGHT}.
3774     *
3775     * @param position Where the vertical scroll bar should be positioned.
3776     */
3777    public void setVerticalScrollbarPosition(int position) {
3778        if (mVerticalScrollbarPosition != position) {
3779            mVerticalScrollbarPosition = position;
3780            computeOpaqueFlags();
3781            resolvePadding();
3782        }
3783    }
3784
3785    /**
3786     * @return The position where the vertical scroll bar will show, if applicable.
3787     * @see #setVerticalScrollbarPosition(int)
3788     */
3789    public int getVerticalScrollbarPosition() {
3790        return mVerticalScrollbarPosition;
3791    }
3792
3793    ListenerInfo getListenerInfo() {
3794        if (mListenerInfo != null) {
3795            return mListenerInfo;
3796        }
3797        mListenerInfo = new ListenerInfo();
3798        return mListenerInfo;
3799    }
3800
3801    /**
3802     * Register a callback to be invoked when focus of this view changed.
3803     *
3804     * @param l The callback that will run.
3805     */
3806    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3807        getListenerInfo().mOnFocusChangeListener = l;
3808    }
3809
3810    /**
3811     * Add a listener that will be called when the bounds of the view change due to
3812     * layout processing.
3813     *
3814     * @param listener The listener that will be called when layout bounds change.
3815     */
3816    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3817        ListenerInfo li = getListenerInfo();
3818        if (li.mOnLayoutChangeListeners == null) {
3819            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3820        }
3821        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3822            li.mOnLayoutChangeListeners.add(listener);
3823        }
3824    }
3825
3826    /**
3827     * Remove a listener for layout changes.
3828     *
3829     * @param listener The listener for layout bounds change.
3830     */
3831    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3832        ListenerInfo li = mListenerInfo;
3833        if (li == null || li.mOnLayoutChangeListeners == null) {
3834            return;
3835        }
3836        li.mOnLayoutChangeListeners.remove(listener);
3837    }
3838
3839    /**
3840     * Add a listener for attach state changes.
3841     *
3842     * This listener will be called whenever this view is attached or detached
3843     * from a window. Remove the listener using
3844     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3845     *
3846     * @param listener Listener to attach
3847     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3848     */
3849    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3850        ListenerInfo li = getListenerInfo();
3851        if (li.mOnAttachStateChangeListeners == null) {
3852            li.mOnAttachStateChangeListeners
3853                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3854        }
3855        li.mOnAttachStateChangeListeners.add(listener);
3856    }
3857
3858    /**
3859     * Remove a listener for attach state changes. The listener will receive no further
3860     * notification of window attach/detach events.
3861     *
3862     * @param listener Listener to remove
3863     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3864     */
3865    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3866        ListenerInfo li = mListenerInfo;
3867        if (li == null || li.mOnAttachStateChangeListeners == null) {
3868            return;
3869        }
3870        li.mOnAttachStateChangeListeners.remove(listener);
3871    }
3872
3873    /**
3874     * Returns the focus-change callback registered for this view.
3875     *
3876     * @return The callback, or null if one is not registered.
3877     */
3878    public OnFocusChangeListener getOnFocusChangeListener() {
3879        ListenerInfo li = mListenerInfo;
3880        return li != null ? li.mOnFocusChangeListener : null;
3881    }
3882
3883    /**
3884     * Register a callback to be invoked when this view is clicked. If this view is not
3885     * clickable, it becomes clickable.
3886     *
3887     * @param l The callback that will run
3888     *
3889     * @see #setClickable(boolean)
3890     */
3891    public void setOnClickListener(OnClickListener l) {
3892        if (!isClickable()) {
3893            setClickable(true);
3894        }
3895        getListenerInfo().mOnClickListener = l;
3896    }
3897
3898    /**
3899     * Return whether this view has an attached OnClickListener.  Returns
3900     * true if there is a listener, false if there is none.
3901     */
3902    public boolean hasOnClickListeners() {
3903        ListenerInfo li = mListenerInfo;
3904        return (li != null && li.mOnClickListener != null);
3905    }
3906
3907    /**
3908     * Register a callback to be invoked when this view is clicked and held. If this view is not
3909     * long clickable, it becomes long clickable.
3910     *
3911     * @param l The callback that will run
3912     *
3913     * @see #setLongClickable(boolean)
3914     */
3915    public void setOnLongClickListener(OnLongClickListener l) {
3916        if (!isLongClickable()) {
3917            setLongClickable(true);
3918        }
3919        getListenerInfo().mOnLongClickListener = l;
3920    }
3921
3922    /**
3923     * Register a callback to be invoked when the context menu for this view is
3924     * being built. If this view is not long clickable, it becomes long clickable.
3925     *
3926     * @param l The callback that will run
3927     *
3928     */
3929    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3930        if (!isLongClickable()) {
3931            setLongClickable(true);
3932        }
3933        getListenerInfo().mOnCreateContextMenuListener = l;
3934    }
3935
3936    /**
3937     * Call this view's OnClickListener, if it is defined.  Performs all normal
3938     * actions associated with clicking: reporting accessibility event, playing
3939     * a sound, etc.
3940     *
3941     * @return True there was an assigned OnClickListener that was called, false
3942     *         otherwise is returned.
3943     */
3944    public boolean performClick() {
3945        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3946
3947        ListenerInfo li = mListenerInfo;
3948        if (li != null && li.mOnClickListener != null) {
3949            playSoundEffect(SoundEffectConstants.CLICK);
3950            li.mOnClickListener.onClick(this);
3951            return true;
3952        }
3953
3954        return false;
3955    }
3956
3957    /**
3958     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3959     * this only calls the listener, and does not do any associated clicking
3960     * actions like reporting an accessibility event.
3961     *
3962     * @return True there was an assigned OnClickListener that was called, false
3963     *         otherwise is returned.
3964     */
3965    public boolean callOnClick() {
3966        ListenerInfo li = mListenerInfo;
3967        if (li != null && li.mOnClickListener != null) {
3968            li.mOnClickListener.onClick(this);
3969            return true;
3970        }
3971        return false;
3972    }
3973
3974    /**
3975     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3976     * OnLongClickListener did not consume the event.
3977     *
3978     * @return True if one of the above receivers consumed the event, false otherwise.
3979     */
3980    public boolean performLongClick() {
3981        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3982
3983        boolean handled = false;
3984        ListenerInfo li = mListenerInfo;
3985        if (li != null && li.mOnLongClickListener != null) {
3986            handled = li.mOnLongClickListener.onLongClick(View.this);
3987        }
3988        if (!handled) {
3989            handled = showContextMenu();
3990        }
3991        if (handled) {
3992            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3993        }
3994        return handled;
3995    }
3996
3997    /**
3998     * Performs button-related actions during a touch down event.
3999     *
4000     * @param event The event.
4001     * @return True if the down was consumed.
4002     *
4003     * @hide
4004     */
4005    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4006        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4007            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4008                return true;
4009            }
4010        }
4011        return false;
4012    }
4013
4014    /**
4015     * Bring up the context menu for this view.
4016     *
4017     * @return Whether a context menu was displayed.
4018     */
4019    public boolean showContextMenu() {
4020        return getParent().showContextMenuForChild(this);
4021    }
4022
4023    /**
4024     * Bring up the context menu for this view, referring to the item under the specified point.
4025     *
4026     * @param x The referenced x coordinate.
4027     * @param y The referenced y coordinate.
4028     * @param metaState The keyboard modifiers that were pressed.
4029     * @return Whether a context menu was displayed.
4030     *
4031     * @hide
4032     */
4033    public boolean showContextMenu(float x, float y, int metaState) {
4034        return showContextMenu();
4035    }
4036
4037    /**
4038     * Start an action mode.
4039     *
4040     * @param callback Callback that will control the lifecycle of the action mode
4041     * @return The new action mode if it is started, null otherwise
4042     *
4043     * @see ActionMode
4044     */
4045    public ActionMode startActionMode(ActionMode.Callback callback) {
4046        ViewParent parent = getParent();
4047        if (parent == null) return null;
4048        return parent.startActionModeForChild(this, callback);
4049    }
4050
4051    /**
4052     * Register a callback to be invoked when a key is pressed in this view.
4053     * @param l the key listener to attach to this view
4054     */
4055    public void setOnKeyListener(OnKeyListener l) {
4056        getListenerInfo().mOnKeyListener = l;
4057    }
4058
4059    /**
4060     * Register a callback to be invoked when a touch event is sent to this view.
4061     * @param l the touch listener to attach to this view
4062     */
4063    public void setOnTouchListener(OnTouchListener l) {
4064        getListenerInfo().mOnTouchListener = l;
4065    }
4066
4067    /**
4068     * Register a callback to be invoked when a generic motion event is sent to this view.
4069     * @param l the generic motion listener to attach to this view
4070     */
4071    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4072        getListenerInfo().mOnGenericMotionListener = l;
4073    }
4074
4075    /**
4076     * Register a callback to be invoked when a hover event is sent to this view.
4077     * @param l the hover listener to attach to this view
4078     */
4079    public void setOnHoverListener(OnHoverListener l) {
4080        getListenerInfo().mOnHoverListener = l;
4081    }
4082
4083    /**
4084     * Register a drag event listener callback object for this View. The parameter is
4085     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4086     * View, the system calls the
4087     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4088     * @param l An implementation of {@link android.view.View.OnDragListener}.
4089     */
4090    public void setOnDragListener(OnDragListener l) {
4091        getListenerInfo().mOnDragListener = l;
4092    }
4093
4094    /**
4095     * Give this view focus. This will cause
4096     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4097     *
4098     * Note: this does not check whether this {@link View} should get focus, it just
4099     * gives it focus no matter what.  It should only be called internally by framework
4100     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4101     *
4102     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4103     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4104     *        focus moved when requestFocus() is called. It may not always
4105     *        apply, in which case use the default View.FOCUS_DOWN.
4106     * @param previouslyFocusedRect The rectangle of the view that had focus
4107     *        prior in this View's coordinate system.
4108     */
4109    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4110        if (DBG) {
4111            System.out.println(this + " requestFocus()");
4112        }
4113
4114        if ((mPrivateFlags & FOCUSED) == 0) {
4115            mPrivateFlags |= FOCUSED;
4116
4117            if (mParent != null) {
4118                mParent.requestChildFocus(this, this);
4119            }
4120
4121            onFocusChanged(true, direction, previouslyFocusedRect);
4122            refreshDrawableState();
4123
4124            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4125                notifyAccessibilityStateChanged();
4126            }
4127        }
4128    }
4129
4130    /**
4131     * Request that a rectangle of this view be visible on the screen,
4132     * scrolling if necessary just enough.
4133     *
4134     * <p>A View should call this if it maintains some notion of which part
4135     * of its content is interesting.  For example, a text editing view
4136     * should call this when its cursor moves.
4137     *
4138     * @param rectangle The rectangle.
4139     * @return Whether any parent scrolled.
4140     */
4141    public boolean requestRectangleOnScreen(Rect rectangle) {
4142        return requestRectangleOnScreen(rectangle, false);
4143    }
4144
4145    /**
4146     * Request that a rectangle of this view be visible on the screen,
4147     * scrolling if necessary just enough.
4148     *
4149     * <p>A View should call this if it maintains some notion of which part
4150     * of its content is interesting.  For example, a text editing view
4151     * should call this when its cursor moves.
4152     *
4153     * <p>When <code>immediate</code> is set to true, scrolling will not be
4154     * animated.
4155     *
4156     * @param rectangle The rectangle.
4157     * @param immediate True to forbid animated scrolling, false otherwise
4158     * @return Whether any parent scrolled.
4159     */
4160    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4161        View child = this;
4162        ViewParent parent = mParent;
4163        boolean scrolled = false;
4164        while (parent != null) {
4165            scrolled |= parent.requestChildRectangleOnScreen(child,
4166                    rectangle, immediate);
4167
4168            // offset rect so next call has the rectangle in the
4169            // coordinate system of its direct child.
4170            rectangle.offset(child.getLeft(), child.getTop());
4171            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4172
4173            if (!(parent instanceof View)) {
4174                break;
4175            }
4176
4177            child = (View) parent;
4178            parent = child.getParent();
4179        }
4180        return scrolled;
4181    }
4182
4183    /**
4184     * Called when this view wants to give up focus. If focus is cleared
4185     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4186     * <p>
4187     * <strong>Note:</strong> When a View clears focus the framework is trying
4188     * to give focus to the first focusable View from the top. Hence, if this
4189     * View is the first from the top that can take focus, then all callbacks
4190     * related to clearing focus will be invoked after wich the framework will
4191     * give focus to this view.
4192     * </p>
4193     */
4194    public void clearFocus() {
4195        if (DBG) {
4196            System.out.println(this + " clearFocus()");
4197        }
4198
4199        if ((mPrivateFlags & FOCUSED) != 0) {
4200            mPrivateFlags &= ~FOCUSED;
4201
4202            if (mParent != null) {
4203                mParent.clearChildFocus(this);
4204            }
4205
4206            onFocusChanged(false, 0, null);
4207
4208            refreshDrawableState();
4209
4210            ensureInputFocusOnFirstFocusable();
4211
4212            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4213                notifyAccessibilityStateChanged();
4214            }
4215        }
4216    }
4217
4218    void ensureInputFocusOnFirstFocusable() {
4219        View root = getRootView();
4220        if (root != null) {
4221            root.requestFocus();
4222        }
4223    }
4224
4225    /**
4226     * Called internally by the view system when a new view is getting focus.
4227     * This is what clears the old focus.
4228     */
4229    void unFocus() {
4230        if (DBG) {
4231            System.out.println(this + " unFocus()");
4232        }
4233
4234        if ((mPrivateFlags & FOCUSED) != 0) {
4235            mPrivateFlags &= ~FOCUSED;
4236
4237            onFocusChanged(false, 0, null);
4238            refreshDrawableState();
4239
4240            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4241                notifyAccessibilityStateChanged();
4242            }
4243        }
4244    }
4245
4246    /**
4247     * Returns true if this view has focus iteself, or is the ancestor of the
4248     * view that has focus.
4249     *
4250     * @return True if this view has or contains focus, false otherwise.
4251     */
4252    @ViewDebug.ExportedProperty(category = "focus")
4253    public boolean hasFocus() {
4254        return (mPrivateFlags & FOCUSED) != 0;
4255    }
4256
4257    /**
4258     * Returns true if this view is focusable or if it contains a reachable View
4259     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4260     * is a View whose parents do not block descendants focus.
4261     *
4262     * Only {@link #VISIBLE} views are considered focusable.
4263     *
4264     * @return True if the view is focusable or if the view contains a focusable
4265     *         View, false otherwise.
4266     *
4267     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4268     */
4269    public boolean hasFocusable() {
4270        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4271    }
4272
4273    /**
4274     * Called by the view system when the focus state of this view changes.
4275     * When the focus change event is caused by directional navigation, direction
4276     * and previouslyFocusedRect provide insight into where the focus is coming from.
4277     * When overriding, be sure to call up through to the super class so that
4278     * the standard focus handling will occur.
4279     *
4280     * @param gainFocus True if the View has focus; false otherwise.
4281     * @param direction The direction focus has moved when requestFocus()
4282     *                  is called to give this view focus. Values are
4283     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4284     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4285     *                  It may not always apply, in which case use the default.
4286     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4287     *        system, of the previously focused view.  If applicable, this will be
4288     *        passed in as finer grained information about where the focus is coming
4289     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4290     */
4291    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4292        if (gainFocus) {
4293            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4294                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4295                requestAccessibilityFocus();
4296            }
4297        }
4298
4299        InputMethodManager imm = InputMethodManager.peekInstance();
4300        if (!gainFocus) {
4301            if (isPressed()) {
4302                setPressed(false);
4303            }
4304            if (imm != null && mAttachInfo != null
4305                    && mAttachInfo.mHasWindowFocus) {
4306                imm.focusOut(this);
4307            }
4308            onFocusLost();
4309        } else if (imm != null && mAttachInfo != null
4310                && mAttachInfo.mHasWindowFocus) {
4311            imm.focusIn(this);
4312        }
4313
4314        invalidate(true);
4315        ListenerInfo li = mListenerInfo;
4316        if (li != null && li.mOnFocusChangeListener != null) {
4317            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4318        }
4319
4320        if (mAttachInfo != null) {
4321            mAttachInfo.mKeyDispatchState.reset(this);
4322        }
4323    }
4324
4325    /**
4326     * Sends an accessibility event of the given type. If accessiiblity is
4327     * not enabled this method has no effect. The default implementation calls
4328     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4329     * to populate information about the event source (this View), then calls
4330     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4331     * populate the text content of the event source including its descendants,
4332     * and last calls
4333     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4334     * on its parent to resuest sending of the event to interested parties.
4335     * <p>
4336     * If an {@link AccessibilityDelegate} has been specified via calling
4337     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4338     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4339     * responsible for handling this call.
4340     * </p>
4341     *
4342     * @param eventType The type of the event to send, as defined by several types from
4343     * {@link android.view.accessibility.AccessibilityEvent}, such as
4344     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4345     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4346     *
4347     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4348     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4349     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4350     * @see AccessibilityDelegate
4351     */
4352    public void sendAccessibilityEvent(int eventType) {
4353        if (mAccessibilityDelegate != null) {
4354            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4355        } else {
4356            sendAccessibilityEventInternal(eventType);
4357        }
4358    }
4359
4360    /**
4361     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4362     * {@link AccessibilityEvent} to make an announcement which is related to some
4363     * sort of a context change for which none of the events representing UI transitions
4364     * is a good fit. For example, announcing a new page in a book. If accessibility
4365     * is not enabled this method does nothing.
4366     *
4367     * @param text The announcement text.
4368     */
4369    public void announceForAccessibility(CharSequence text) {
4370        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4371            AccessibilityEvent event = AccessibilityEvent.obtain(
4372                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4373            event.getText().add(text);
4374            sendAccessibilityEventUnchecked(event);
4375        }
4376    }
4377
4378    /**
4379     * @see #sendAccessibilityEvent(int)
4380     *
4381     * Note: Called from the default {@link AccessibilityDelegate}.
4382     */
4383    void sendAccessibilityEventInternal(int eventType) {
4384        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4385            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4386        }
4387    }
4388
4389    /**
4390     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4391     * takes as an argument an empty {@link AccessibilityEvent} and does not
4392     * perform a check whether accessibility is enabled.
4393     * <p>
4394     * If an {@link AccessibilityDelegate} has been specified via calling
4395     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4396     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4397     * is responsible for handling this call.
4398     * </p>
4399     *
4400     * @param event The event to send.
4401     *
4402     * @see #sendAccessibilityEvent(int)
4403     */
4404    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4405        if (mAccessibilityDelegate != null) {
4406            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4407        } else {
4408            sendAccessibilityEventUncheckedInternal(event);
4409        }
4410    }
4411
4412    /**
4413     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4414     *
4415     * Note: Called from the default {@link AccessibilityDelegate}.
4416     */
4417    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4418        if (!isShown()) {
4419            return;
4420        }
4421        onInitializeAccessibilityEvent(event);
4422        // Only a subset of accessibility events populates text content.
4423        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4424            dispatchPopulateAccessibilityEvent(event);
4425        }
4426        // Intercept accessibility focus events fired by virtual nodes to keep
4427        // track of accessibility focus position in such nodes.
4428        final int eventType = event.getEventType();
4429        switch (eventType) {
4430            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4431                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4432                        event.getSourceNodeId());
4433                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4434                    ViewRootImpl viewRootImpl = getViewRootImpl();
4435                    if (viewRootImpl != null) {
4436                        viewRootImpl.setAccessibilityFocusedHost(this);
4437                    }
4438                }
4439            } break;
4440            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4441                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4442                        event.getSourceNodeId());
4443                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4444                    ViewRootImpl viewRootImpl = getViewRootImpl();
4445                    if (viewRootImpl != null) {
4446                        viewRootImpl.setAccessibilityFocusedHost(null);
4447                    }
4448                }
4449            } break;
4450        }
4451        // In the beginning we called #isShown(), so we know that getParent() is not null.
4452        getParent().requestSendAccessibilityEvent(this, event);
4453    }
4454
4455    /**
4456     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4457     * to its children for adding their text content to the event. Note that the
4458     * event text is populated in a separate dispatch path since we add to the
4459     * event not only the text of the source but also the text of all its descendants.
4460     * A typical implementation will call
4461     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4462     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4463     * on each child. Override this method if custom population of the event text
4464     * content is required.
4465     * <p>
4466     * If an {@link AccessibilityDelegate} has been specified via calling
4467     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4468     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4469     * is responsible for handling this call.
4470     * </p>
4471     * <p>
4472     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4473     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4474     * </p>
4475     *
4476     * @param event The event.
4477     *
4478     * @return True if the event population was completed.
4479     */
4480    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4481        if (mAccessibilityDelegate != null) {
4482            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4483        } else {
4484            return dispatchPopulateAccessibilityEventInternal(event);
4485        }
4486    }
4487
4488    /**
4489     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4490     *
4491     * Note: Called from the default {@link AccessibilityDelegate}.
4492     */
4493    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4494        onPopulateAccessibilityEvent(event);
4495        return false;
4496    }
4497
4498    /**
4499     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4500     * giving a chance to this View to populate the accessibility event with its
4501     * text content. While this method is free to modify event
4502     * attributes other than text content, doing so should normally be performed in
4503     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4504     * <p>
4505     * Example: Adding formatted date string to an accessibility event in addition
4506     *          to the text added by the super implementation:
4507     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4508     *     super.onPopulateAccessibilityEvent(event);
4509     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4510     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4511     *         mCurrentDate.getTimeInMillis(), flags);
4512     *     event.getText().add(selectedDateUtterance);
4513     * }</pre>
4514     * <p>
4515     * If an {@link AccessibilityDelegate} has been specified via calling
4516     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4517     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4518     * is responsible for handling this call.
4519     * </p>
4520     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4521     * information to the event, in case the default implementation has basic information to add.
4522     * </p>
4523     *
4524     * @param event The accessibility event which to populate.
4525     *
4526     * @see #sendAccessibilityEvent(int)
4527     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4528     */
4529    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4530        if (mAccessibilityDelegate != null) {
4531            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4532        } else {
4533            onPopulateAccessibilityEventInternal(event);
4534        }
4535    }
4536
4537    /**
4538     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4539     *
4540     * Note: Called from the default {@link AccessibilityDelegate}.
4541     */
4542    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4543
4544    }
4545
4546    /**
4547     * Initializes an {@link AccessibilityEvent} with information about
4548     * this View which is the event source. In other words, the source of
4549     * an accessibility event is the view whose state change triggered firing
4550     * the event.
4551     * <p>
4552     * Example: Setting the password property of an event in addition
4553     *          to properties set by the super implementation:
4554     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4555     *     super.onInitializeAccessibilityEvent(event);
4556     *     event.setPassword(true);
4557     * }</pre>
4558     * <p>
4559     * If an {@link AccessibilityDelegate} has been specified via calling
4560     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4561     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4562     * is responsible for handling this call.
4563     * </p>
4564     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4565     * information to the event, in case the default implementation has basic information to add.
4566     * </p>
4567     * @param event The event to initialize.
4568     *
4569     * @see #sendAccessibilityEvent(int)
4570     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4571     */
4572    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4573        if (mAccessibilityDelegate != null) {
4574            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4575        } else {
4576            onInitializeAccessibilityEventInternal(event);
4577        }
4578    }
4579
4580    /**
4581     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4582     *
4583     * Note: Called from the default {@link AccessibilityDelegate}.
4584     */
4585    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4586        event.setSource(this);
4587        event.setClassName(View.class.getName());
4588        event.setPackageName(getContext().getPackageName());
4589        event.setEnabled(isEnabled());
4590        event.setContentDescription(mContentDescription);
4591
4592        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4593            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4594            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4595                    FOCUSABLES_ALL);
4596            event.setItemCount(focusablesTempList.size());
4597            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4598            focusablesTempList.clear();
4599        }
4600    }
4601
4602    /**
4603     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4604     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4605     * This method is responsible for obtaining an accessibility node info from a
4606     * pool of reusable instances and calling
4607     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4608     * initialize the former.
4609     * <p>
4610     * Note: The client is responsible for recycling the obtained instance by calling
4611     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4612     * </p>
4613     *
4614     * @return A populated {@link AccessibilityNodeInfo}.
4615     *
4616     * @see AccessibilityNodeInfo
4617     */
4618    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4619        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4620        if (provider != null) {
4621            return provider.createAccessibilityNodeInfo(View.NO_ID);
4622        } else {
4623            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4624            onInitializeAccessibilityNodeInfo(info);
4625            return info;
4626        }
4627    }
4628
4629    /**
4630     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4631     * The base implementation sets:
4632     * <ul>
4633     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4634     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4635     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4636     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4637     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4638     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4639     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4640     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4641     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4642     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4643     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4644     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4645     * </ul>
4646     * <p>
4647     * Subclasses should override this method, call the super implementation,
4648     * and set additional attributes.
4649     * </p>
4650     * <p>
4651     * If an {@link AccessibilityDelegate} has been specified via calling
4652     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4653     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4654     * is responsible for handling this call.
4655     * </p>
4656     *
4657     * @param info The instance to initialize.
4658     */
4659    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4660        if (mAccessibilityDelegate != null) {
4661            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4662        } else {
4663            onInitializeAccessibilityNodeInfoInternal(info);
4664        }
4665    }
4666
4667    /**
4668     * Gets the location of this view in screen coordintates.
4669     *
4670     * @param outRect The output location
4671     */
4672    private void getBoundsOnScreen(Rect outRect) {
4673        if (mAttachInfo == null) {
4674            return;
4675        }
4676
4677        RectF position = mAttachInfo.mTmpTransformRect;
4678        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4679
4680        if (!hasIdentityMatrix()) {
4681            getMatrix().mapRect(position);
4682        }
4683
4684        position.offset(mLeft, mTop);
4685
4686        ViewParent parent = mParent;
4687        while (parent instanceof View) {
4688            View parentView = (View) parent;
4689
4690            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4691
4692            if (!parentView.hasIdentityMatrix()) {
4693                parentView.getMatrix().mapRect(position);
4694            }
4695
4696            position.offset(parentView.mLeft, parentView.mTop);
4697
4698            parent = parentView.mParent;
4699        }
4700
4701        if (parent instanceof ViewRootImpl) {
4702            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4703            position.offset(0, -viewRootImpl.mCurScrollY);
4704        }
4705
4706        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4707
4708        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4709                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4710    }
4711
4712    /**
4713     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4714     *
4715     * Note: Called from the default {@link AccessibilityDelegate}.
4716     */
4717    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4718        Rect bounds = mAttachInfo.mTmpInvalRect;
4719        getDrawingRect(bounds);
4720        info.setBoundsInParent(bounds);
4721
4722        getBoundsOnScreen(bounds);
4723        info.setBoundsInScreen(bounds);
4724
4725        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4726            ViewParent parent = getParentForAccessibility();
4727            if (parent instanceof View) {
4728                info.setParent((View) parent);
4729            }
4730        }
4731
4732        info.setVisibleToUser(isVisibleToUser());
4733
4734        info.setPackageName(mContext.getPackageName());
4735        info.setClassName(View.class.getName());
4736        info.setContentDescription(getContentDescription());
4737
4738        info.setEnabled(isEnabled());
4739        info.setClickable(isClickable());
4740        info.setFocusable(isFocusable());
4741        info.setFocused(isFocused());
4742        info.setAccessibilityFocused(isAccessibilityFocused());
4743        info.setSelected(isSelected());
4744        info.setLongClickable(isLongClickable());
4745
4746        // TODO: These make sense only if we are in an AdapterView but all
4747        // views can be selected. Maybe from accessiiblity perspective
4748        // we should report as selectable view in an AdapterView.
4749        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4750        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4751
4752        if (isFocusable()) {
4753            if (isFocused()) {
4754                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4755            } else {
4756                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4757            }
4758        }
4759
4760        if (!isAccessibilityFocused()) {
4761            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4762        } else {
4763            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4764        }
4765
4766        if (isClickable()) {
4767            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4768        }
4769
4770        if (isLongClickable()) {
4771            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4772        }
4773
4774        if (mContentDescription != null && mContentDescription.length() > 0) {
4775            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4776            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4777            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4778                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4779                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4780        }
4781    }
4782
4783    /**
4784     * Computes whether this view is visible to the user. Such a view is
4785     * attached, visible, all its predecessors are visible, it is not clipped
4786     * entirely by its predecessors, and has an alpha greater than zero.
4787     *
4788     * @return Whether the view is visible on the screen.
4789     *
4790     * @hide
4791     */
4792    protected boolean isVisibleToUser() {
4793        return isVisibleToUser(null);
4794    }
4795
4796    /**
4797     * Computes whether the given portion of this view is visible to the user. Such a view is
4798     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4799     * the specified portion is not clipped entirely by its predecessors.
4800     *
4801     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4802     *                    <code>null</code>, and the entire view will be tested in this case.
4803     *                    When <code>true</code> is returned by the function, the actual visible
4804     *                    region will be stored in this parameter; that is, if boundInView is fully
4805     *                    contained within the view, no modification will be made, otherwise regions
4806     *                    outside of the visible area of the view will be clipped.
4807     *
4808     * @return Whether the specified portion of the view is visible on the screen.
4809     *
4810     * @hide
4811     */
4812    protected boolean isVisibleToUser(Rect boundInView) {
4813        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4814        Point offset = mAttachInfo.mPoint;
4815        // The first two checks are made also made by isShown() which
4816        // however traverses the tree up to the parent to catch that.
4817        // Therefore, we do some fail fast check to minimize the up
4818        // tree traversal.
4819        boolean isVisible = mAttachInfo != null
4820            && mAttachInfo.mWindowVisibility == View.VISIBLE
4821            && getAlpha() > 0
4822            && isShown()
4823            && getGlobalVisibleRect(visibleRect, offset);
4824            if (isVisible && boundInView != null) {
4825                visibleRect.offset(-offset.x, -offset.y);
4826                isVisible &= boundInView.intersect(visibleRect);
4827            }
4828            return isVisible;
4829    }
4830
4831    /**
4832     * Sets a delegate for implementing accessibility support via compositon as
4833     * opposed to inheritance. The delegate's primary use is for implementing
4834     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4835     *
4836     * @param delegate The delegate instance.
4837     *
4838     * @see AccessibilityDelegate
4839     */
4840    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4841        mAccessibilityDelegate = delegate;
4842    }
4843
4844    /**
4845     * Gets the provider for managing a virtual view hierarchy rooted at this View
4846     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4847     * that explore the window content.
4848     * <p>
4849     * If this method returns an instance, this instance is responsible for managing
4850     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4851     * View including the one representing the View itself. Similarly the returned
4852     * instance is responsible for performing accessibility actions on any virtual
4853     * view or the root view itself.
4854     * </p>
4855     * <p>
4856     * If an {@link AccessibilityDelegate} has been specified via calling
4857     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4858     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4859     * is responsible for handling this call.
4860     * </p>
4861     *
4862     * @return The provider.
4863     *
4864     * @see AccessibilityNodeProvider
4865     */
4866    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4867        if (mAccessibilityDelegate != null) {
4868            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4869        } else {
4870            return null;
4871        }
4872    }
4873
4874    /**
4875     * Gets the unique identifier of this view on the screen for accessibility purposes.
4876     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4877     *
4878     * @return The view accessibility id.
4879     *
4880     * @hide
4881     */
4882    public int getAccessibilityViewId() {
4883        if (mAccessibilityViewId == NO_ID) {
4884            mAccessibilityViewId = sNextAccessibilityViewId++;
4885        }
4886        return mAccessibilityViewId;
4887    }
4888
4889    /**
4890     * Gets the unique identifier of the window in which this View reseides.
4891     *
4892     * @return The window accessibility id.
4893     *
4894     * @hide
4895     */
4896    public int getAccessibilityWindowId() {
4897        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4898    }
4899
4900    /**
4901     * Gets the {@link View} description. It briefly describes the view and is
4902     * primarily used for accessibility support. Set this property to enable
4903     * better accessibility support for your application. This is especially
4904     * true for views that do not have textual representation (For example,
4905     * ImageButton).
4906     *
4907     * @return The content description.
4908     *
4909     * @attr ref android.R.styleable#View_contentDescription
4910     */
4911    @ViewDebug.ExportedProperty(category = "accessibility")
4912    public CharSequence getContentDescription() {
4913        return mContentDescription;
4914    }
4915
4916    /**
4917     * Sets the {@link View} description. It briefly describes the view and is
4918     * primarily used for accessibility support. Set this property to enable
4919     * better accessibility support for your application. This is especially
4920     * true for views that do not have textual representation (For example,
4921     * ImageButton).
4922     *
4923     * @param contentDescription The content description.
4924     *
4925     * @attr ref android.R.styleable#View_contentDescription
4926     */
4927    @RemotableViewMethod
4928    public void setContentDescription(CharSequence contentDescription) {
4929        mContentDescription = contentDescription;
4930    }
4931
4932    /**
4933     * Invoked whenever this view loses focus, either by losing window focus or by losing
4934     * focus within its window. This method can be used to clear any state tied to the
4935     * focus. For instance, if a button is held pressed with the trackball and the window
4936     * loses focus, this method can be used to cancel the press.
4937     *
4938     * Subclasses of View overriding this method should always call super.onFocusLost().
4939     *
4940     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4941     * @see #onWindowFocusChanged(boolean)
4942     *
4943     * @hide pending API council approval
4944     */
4945    protected void onFocusLost() {
4946        resetPressedState();
4947    }
4948
4949    private void resetPressedState() {
4950        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4951            return;
4952        }
4953
4954        if (isPressed()) {
4955            setPressed(false);
4956
4957            if (!mHasPerformedLongPress) {
4958                removeLongPressCallback();
4959            }
4960        }
4961    }
4962
4963    /**
4964     * Returns true if this view has focus
4965     *
4966     * @return True if this view has focus, false otherwise.
4967     */
4968    @ViewDebug.ExportedProperty(category = "focus")
4969    public boolean isFocused() {
4970        return (mPrivateFlags & FOCUSED) != 0;
4971    }
4972
4973    /**
4974     * Find the view in the hierarchy rooted at this view that currently has
4975     * focus.
4976     *
4977     * @return The view that currently has focus, or null if no focused view can
4978     *         be found.
4979     */
4980    public View findFocus() {
4981        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4982    }
4983
4984    /**
4985     * Indicates whether this view is one of the set of scrollable containers in
4986     * its window.
4987     *
4988     * @return whether this view is one of the set of scrollable containers in
4989     * its window
4990     *
4991     * @attr ref android.R.styleable#View_isScrollContainer
4992     */
4993    public boolean isScrollContainer() {
4994        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4995    }
4996
4997    /**
4998     * Change whether this view is one of the set of scrollable containers in
4999     * its window.  This will be used to determine whether the window can
5000     * resize or must pan when a soft input area is open -- scrollable
5001     * containers allow the window to use resize mode since the container
5002     * will appropriately shrink.
5003     *
5004     * @attr ref android.R.styleable#View_isScrollContainer
5005     */
5006    public void setScrollContainer(boolean isScrollContainer) {
5007        if (isScrollContainer) {
5008            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5009                mAttachInfo.mScrollContainers.add(this);
5010                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5011            }
5012            mPrivateFlags |= SCROLL_CONTAINER;
5013        } else {
5014            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5015                mAttachInfo.mScrollContainers.remove(this);
5016            }
5017            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5018        }
5019    }
5020
5021    /**
5022     * Returns the quality of the drawing cache.
5023     *
5024     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5025     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5026     *
5027     * @see #setDrawingCacheQuality(int)
5028     * @see #setDrawingCacheEnabled(boolean)
5029     * @see #isDrawingCacheEnabled()
5030     *
5031     * @attr ref android.R.styleable#View_drawingCacheQuality
5032     */
5033    public int getDrawingCacheQuality() {
5034        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5035    }
5036
5037    /**
5038     * Set the drawing cache quality of this view. This value is used only when the
5039     * drawing cache is enabled
5040     *
5041     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5042     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5043     *
5044     * @see #getDrawingCacheQuality()
5045     * @see #setDrawingCacheEnabled(boolean)
5046     * @see #isDrawingCacheEnabled()
5047     *
5048     * @attr ref android.R.styleable#View_drawingCacheQuality
5049     */
5050    public void setDrawingCacheQuality(int quality) {
5051        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5052    }
5053
5054    /**
5055     * Returns whether the screen should remain on, corresponding to the current
5056     * value of {@link #KEEP_SCREEN_ON}.
5057     *
5058     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5059     *
5060     * @see #setKeepScreenOn(boolean)
5061     *
5062     * @attr ref android.R.styleable#View_keepScreenOn
5063     */
5064    public boolean getKeepScreenOn() {
5065        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5066    }
5067
5068    /**
5069     * Controls whether the screen should remain on, modifying the
5070     * value of {@link #KEEP_SCREEN_ON}.
5071     *
5072     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5073     *
5074     * @see #getKeepScreenOn()
5075     *
5076     * @attr ref android.R.styleable#View_keepScreenOn
5077     */
5078    public void setKeepScreenOn(boolean keepScreenOn) {
5079        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5080    }
5081
5082    /**
5083     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5084     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5085     *
5086     * @attr ref android.R.styleable#View_nextFocusLeft
5087     */
5088    public int getNextFocusLeftId() {
5089        return mNextFocusLeftId;
5090    }
5091
5092    /**
5093     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5094     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5095     * decide automatically.
5096     *
5097     * @attr ref android.R.styleable#View_nextFocusLeft
5098     */
5099    public void setNextFocusLeftId(int nextFocusLeftId) {
5100        mNextFocusLeftId = nextFocusLeftId;
5101    }
5102
5103    /**
5104     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5105     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5106     *
5107     * @attr ref android.R.styleable#View_nextFocusRight
5108     */
5109    public int getNextFocusRightId() {
5110        return mNextFocusRightId;
5111    }
5112
5113    /**
5114     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5115     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5116     * decide automatically.
5117     *
5118     * @attr ref android.R.styleable#View_nextFocusRight
5119     */
5120    public void setNextFocusRightId(int nextFocusRightId) {
5121        mNextFocusRightId = nextFocusRightId;
5122    }
5123
5124    /**
5125     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5126     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5127     *
5128     * @attr ref android.R.styleable#View_nextFocusUp
5129     */
5130    public int getNextFocusUpId() {
5131        return mNextFocusUpId;
5132    }
5133
5134    /**
5135     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5136     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5137     * decide automatically.
5138     *
5139     * @attr ref android.R.styleable#View_nextFocusUp
5140     */
5141    public void setNextFocusUpId(int nextFocusUpId) {
5142        mNextFocusUpId = nextFocusUpId;
5143    }
5144
5145    /**
5146     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5147     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5148     *
5149     * @attr ref android.R.styleable#View_nextFocusDown
5150     */
5151    public int getNextFocusDownId() {
5152        return mNextFocusDownId;
5153    }
5154
5155    /**
5156     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5157     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5158     * decide automatically.
5159     *
5160     * @attr ref android.R.styleable#View_nextFocusDown
5161     */
5162    public void setNextFocusDownId(int nextFocusDownId) {
5163        mNextFocusDownId = nextFocusDownId;
5164    }
5165
5166    /**
5167     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5168     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5169     *
5170     * @attr ref android.R.styleable#View_nextFocusForward
5171     */
5172    public int getNextFocusForwardId() {
5173        return mNextFocusForwardId;
5174    }
5175
5176    /**
5177     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5178     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5179     * decide automatically.
5180     *
5181     * @attr ref android.R.styleable#View_nextFocusForward
5182     */
5183    public void setNextFocusForwardId(int nextFocusForwardId) {
5184        mNextFocusForwardId = nextFocusForwardId;
5185    }
5186
5187    /**
5188     * Returns the visibility of this view and all of its ancestors
5189     *
5190     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5191     */
5192    public boolean isShown() {
5193        View current = this;
5194        //noinspection ConstantConditions
5195        do {
5196            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5197                return false;
5198            }
5199            ViewParent parent = current.mParent;
5200            if (parent == null) {
5201                return false; // We are not attached to the view root
5202            }
5203            if (!(parent instanceof View)) {
5204                return true;
5205            }
5206            current = (View) parent;
5207        } while (current != null);
5208
5209        return false;
5210    }
5211
5212    /**
5213     * Called by the view hierarchy when the content insets for a window have
5214     * changed, to allow it to adjust its content to fit within those windows.
5215     * The content insets tell you the space that the status bar, input method,
5216     * and other system windows infringe on the application's window.
5217     *
5218     * <p>You do not normally need to deal with this function, since the default
5219     * window decoration given to applications takes care of applying it to the
5220     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5221     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5222     * and your content can be placed under those system elements.  You can then
5223     * use this method within your view hierarchy if you have parts of your UI
5224     * which you would like to ensure are not being covered.
5225     *
5226     * <p>The default implementation of this method simply applies the content
5227     * inset's to the view's padding.  This can be enabled through
5228     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5229     * the method and handle the insets however you would like.  Note that the
5230     * insets provided by the framework are always relative to the far edges
5231     * of the window, not accounting for the location of the called view within
5232     * that window.  (In fact when this method is called you do not yet know
5233     * where the layout will place the view, as it is done before layout happens.)
5234     *
5235     * <p>Note: unlike many View methods, there is no dispatch phase to this
5236     * call.  If you are overriding it in a ViewGroup and want to allow the
5237     * call to continue to your children, you must be sure to call the super
5238     * implementation.
5239     *
5240     * <p>Here is a sample layout that makes use of fitting system windows
5241     * to have controls for a video view placed inside of the window decorations
5242     * that it hides and shows.  This can be used with code like the second
5243     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5244     *
5245     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5246     *
5247     * @param insets Current content insets of the window.  Prior to
5248     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5249     * the insets or else you and Android will be unhappy.
5250     *
5251     * @return Return true if this view applied the insets and it should not
5252     * continue propagating further down the hierarchy, false otherwise.
5253     */
5254    protected boolean fitSystemWindows(Rect insets) {
5255        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5256            mUserPaddingStart = -1;
5257            mUserPaddingEnd = -1;
5258            mUserPaddingRelative = false;
5259            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5260                    || mAttachInfo == null
5261                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5262                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5263                return true;
5264            } else {
5265                internalSetPadding(0, 0, 0, 0);
5266                return false;
5267            }
5268        }
5269        return false;
5270    }
5271
5272    /**
5273     * Set whether or not this view should account for system screen decorations
5274     * such as the status bar and inset its content. This allows this view to be
5275     * positioned in absolute screen coordinates and remain visible to the user.
5276     *
5277     * <p>This should only be used by top-level window decor views.
5278     *
5279     * @param fitSystemWindows true to inset content for system screen decorations, false for
5280     *                         default behavior.
5281     *
5282     * @attr ref android.R.styleable#View_fitsSystemWindows
5283     */
5284    public void setFitsSystemWindows(boolean fitSystemWindows) {
5285        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5286    }
5287
5288    /**
5289     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5290     * returns true, this view
5291     * will account for system screen decorations such as the status bar and inset its
5292     * content. This allows the view to be positioned in absolute screen coordinates
5293     * and remain visible to the user.
5294     *
5295     * @return true if this view will adjust its content bounds for system screen decorations.
5296     *
5297     * @attr ref android.R.styleable#View_fitsSystemWindows
5298     */
5299    public boolean getFitsSystemWindows() {
5300        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5301    }
5302
5303    /** @hide */
5304    public boolean fitsSystemWindows() {
5305        return getFitsSystemWindows();
5306    }
5307
5308    /**
5309     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5310     */
5311    public void requestFitSystemWindows() {
5312        if (mParent != null) {
5313            mParent.requestFitSystemWindows();
5314        }
5315    }
5316
5317    /**
5318     * For use by PhoneWindow to make its own system window fitting optional.
5319     * @hide
5320     */
5321    public void makeOptionalFitsSystemWindows() {
5322        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5323    }
5324
5325    /**
5326     * Returns the visibility status for this view.
5327     *
5328     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5329     * @attr ref android.R.styleable#View_visibility
5330     */
5331    @ViewDebug.ExportedProperty(mapping = {
5332        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5333        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5334        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5335    })
5336    public int getVisibility() {
5337        return mViewFlags & VISIBILITY_MASK;
5338    }
5339
5340    /**
5341     * Set the enabled state of this view.
5342     *
5343     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5344     * @attr ref android.R.styleable#View_visibility
5345     */
5346    @RemotableViewMethod
5347    public void setVisibility(int visibility) {
5348        setFlags(visibility, VISIBILITY_MASK);
5349        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5350    }
5351
5352    /**
5353     * Returns the enabled status for this view. The interpretation of the
5354     * enabled state varies by subclass.
5355     *
5356     * @return True if this view is enabled, false otherwise.
5357     */
5358    @ViewDebug.ExportedProperty
5359    public boolean isEnabled() {
5360        return (mViewFlags & ENABLED_MASK) == ENABLED;
5361    }
5362
5363    /**
5364     * Set the enabled state of this view. The interpretation of the enabled
5365     * state varies by subclass.
5366     *
5367     * @param enabled True if this view is enabled, false otherwise.
5368     */
5369    @RemotableViewMethod
5370    public void setEnabled(boolean enabled) {
5371        if (enabled == isEnabled()) return;
5372
5373        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5374
5375        /*
5376         * The View most likely has to change its appearance, so refresh
5377         * the drawable state.
5378         */
5379        refreshDrawableState();
5380
5381        // Invalidate too, since the default behavior for views is to be
5382        // be drawn at 50% alpha rather than to change the drawable.
5383        invalidate(true);
5384    }
5385
5386    /**
5387     * Set whether this view can receive the focus.
5388     *
5389     * Setting this to false will also ensure that this view is not focusable
5390     * in touch mode.
5391     *
5392     * @param focusable If true, this view can receive the focus.
5393     *
5394     * @see #setFocusableInTouchMode(boolean)
5395     * @attr ref android.R.styleable#View_focusable
5396     */
5397    public void setFocusable(boolean focusable) {
5398        if (!focusable) {
5399            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5400        }
5401        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5402    }
5403
5404    /**
5405     * Set whether this view can receive focus while in touch mode.
5406     *
5407     * Setting this to true will also ensure that this view is focusable.
5408     *
5409     * @param focusableInTouchMode If true, this view can receive the focus while
5410     *   in touch mode.
5411     *
5412     * @see #setFocusable(boolean)
5413     * @attr ref android.R.styleable#View_focusableInTouchMode
5414     */
5415    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5416        // Focusable in touch mode should always be set before the focusable flag
5417        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5418        // which, in touch mode, will not successfully request focus on this view
5419        // because the focusable in touch mode flag is not set
5420        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5421        if (focusableInTouchMode) {
5422            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5423        }
5424    }
5425
5426    /**
5427     * Set whether this view should have sound effects enabled for events such as
5428     * clicking and touching.
5429     *
5430     * <p>You may wish to disable sound effects for a view if you already play sounds,
5431     * for instance, a dial key that plays dtmf tones.
5432     *
5433     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5434     * @see #isSoundEffectsEnabled()
5435     * @see #playSoundEffect(int)
5436     * @attr ref android.R.styleable#View_soundEffectsEnabled
5437     */
5438    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5439        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5440    }
5441
5442    /**
5443     * @return whether this view should have sound effects enabled for events such as
5444     *     clicking and touching.
5445     *
5446     * @see #setSoundEffectsEnabled(boolean)
5447     * @see #playSoundEffect(int)
5448     * @attr ref android.R.styleable#View_soundEffectsEnabled
5449     */
5450    @ViewDebug.ExportedProperty
5451    public boolean isSoundEffectsEnabled() {
5452        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5453    }
5454
5455    /**
5456     * Set whether this view should have haptic feedback for events such as
5457     * long presses.
5458     *
5459     * <p>You may wish to disable haptic feedback if your view already controls
5460     * its own haptic feedback.
5461     *
5462     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5463     * @see #isHapticFeedbackEnabled()
5464     * @see #performHapticFeedback(int)
5465     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5466     */
5467    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5468        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5469    }
5470
5471    /**
5472     * @return whether this view should have haptic feedback enabled for events
5473     * long presses.
5474     *
5475     * @see #setHapticFeedbackEnabled(boolean)
5476     * @see #performHapticFeedback(int)
5477     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5478     */
5479    @ViewDebug.ExportedProperty
5480    public boolean isHapticFeedbackEnabled() {
5481        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5482    }
5483
5484    /**
5485     * Returns the layout direction for this view.
5486     *
5487     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5488     *   {@link #LAYOUT_DIRECTION_RTL},
5489     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5490     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5491     * @attr ref android.R.styleable#View_layoutDirection
5492     */
5493    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5494        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5495        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5496        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5497        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5498    })
5499    public int getLayoutDirection() {
5500        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5501    }
5502
5503    /**
5504     * Set the layout direction for this view. This will propagate a reset of layout direction
5505     * resolution to the view's children and resolve layout direction for this view.
5506     *
5507     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5508     *   {@link #LAYOUT_DIRECTION_RTL},
5509     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5510     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5511     *
5512     * @attr ref android.R.styleable#View_layoutDirection
5513     */
5514    @RemotableViewMethod
5515    public void setLayoutDirection(int layoutDirection) {
5516        if (getLayoutDirection() != layoutDirection) {
5517            // Reset the current layout direction and the resolved one
5518            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5519            resetResolvedLayoutDirection();
5520            // Set the new layout direction (filtered) and ask for a layout pass
5521            mPrivateFlags2 |=
5522                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5523            requestLayout();
5524        }
5525    }
5526
5527    /**
5528     * Returns the resolved layout direction for this view.
5529     *
5530     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5531     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5532     */
5533    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5534        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5535        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5536    })
5537    public int getResolvedLayoutDirection() {
5538        // The layout diretion will be resolved only if needed
5539        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5540            resolveLayoutDirection();
5541        }
5542        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5543                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5544    }
5545
5546    /**
5547     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5548     * layout attribute and/or the inherited value from the parent
5549     *
5550     * @return true if the layout is right-to-left.
5551     */
5552    @ViewDebug.ExportedProperty(category = "layout")
5553    public boolean isLayoutRtl() {
5554        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5555    }
5556
5557    /**
5558     * Indicates whether the view is currently tracking transient state that the
5559     * app should not need to concern itself with saving and restoring, but that
5560     * the framework should take special note to preserve when possible.
5561     *
5562     * <p>A view with transient state cannot be trivially rebound from an external
5563     * data source, such as an adapter binding item views in a list. This may be
5564     * because the view is performing an animation, tracking user selection
5565     * of content, or similar.</p>
5566     *
5567     * @return true if the view has transient state
5568     */
5569    @ViewDebug.ExportedProperty(category = "layout")
5570    public boolean hasTransientState() {
5571        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5572    }
5573
5574    /**
5575     * Set whether this view is currently tracking transient state that the
5576     * framework should attempt to preserve when possible. This flag is reference counted,
5577     * so every call to setHasTransientState(true) should be paired with a later call
5578     * to setHasTransientState(false).
5579     *
5580     * <p>A view with transient state cannot be trivially rebound from an external
5581     * data source, such as an adapter binding item views in a list. This may be
5582     * because the view is performing an animation, tracking user selection
5583     * of content, or similar.</p>
5584     *
5585     * @param hasTransientState true if this view has transient state
5586     */
5587    public void setHasTransientState(boolean hasTransientState) {
5588        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5589                mTransientStateCount - 1;
5590        if (mTransientStateCount < 0) {
5591            mTransientStateCount = 0;
5592            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5593                    "unmatched pair of setHasTransientState calls");
5594        }
5595        if ((hasTransientState && mTransientStateCount == 1) ||
5596                (!hasTransientState && mTransientStateCount == 0)) {
5597            // update flag if we've just incremented up from 0 or decremented down to 0
5598            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5599                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5600            if (mParent != null) {
5601                try {
5602                    mParent.childHasTransientStateChanged(this, hasTransientState);
5603                } catch (AbstractMethodError e) {
5604                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5605                            " does not fully implement ViewParent", e);
5606                }
5607            }
5608        }
5609    }
5610
5611    /**
5612     * If this view doesn't do any drawing on its own, set this flag to
5613     * allow further optimizations. By default, this flag is not set on
5614     * View, but could be set on some View subclasses such as ViewGroup.
5615     *
5616     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5617     * you should clear this flag.
5618     *
5619     * @param willNotDraw whether or not this View draw on its own
5620     */
5621    public void setWillNotDraw(boolean willNotDraw) {
5622        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5623    }
5624
5625    /**
5626     * Returns whether or not this View draws on its own.
5627     *
5628     * @return true if this view has nothing to draw, false otherwise
5629     */
5630    @ViewDebug.ExportedProperty(category = "drawing")
5631    public boolean willNotDraw() {
5632        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5633    }
5634
5635    /**
5636     * When a View's drawing cache is enabled, drawing is redirected to an
5637     * offscreen bitmap. Some views, like an ImageView, must be able to
5638     * bypass this mechanism if they already draw a single bitmap, to avoid
5639     * unnecessary usage of the memory.
5640     *
5641     * @param willNotCacheDrawing true if this view does not cache its
5642     *        drawing, false otherwise
5643     */
5644    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5645        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5646    }
5647
5648    /**
5649     * Returns whether or not this View can cache its drawing or not.
5650     *
5651     * @return true if this view does not cache its drawing, false otherwise
5652     */
5653    @ViewDebug.ExportedProperty(category = "drawing")
5654    public boolean willNotCacheDrawing() {
5655        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5656    }
5657
5658    /**
5659     * Indicates whether this view reacts to click events or not.
5660     *
5661     * @return true if the view is clickable, false otherwise
5662     *
5663     * @see #setClickable(boolean)
5664     * @attr ref android.R.styleable#View_clickable
5665     */
5666    @ViewDebug.ExportedProperty
5667    public boolean isClickable() {
5668        return (mViewFlags & CLICKABLE) == CLICKABLE;
5669    }
5670
5671    /**
5672     * Enables or disables click events for this view. When a view
5673     * is clickable it will change its state to "pressed" on every click.
5674     * Subclasses should set the view clickable to visually react to
5675     * user's clicks.
5676     *
5677     * @param clickable true to make the view clickable, false otherwise
5678     *
5679     * @see #isClickable()
5680     * @attr ref android.R.styleable#View_clickable
5681     */
5682    public void setClickable(boolean clickable) {
5683        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5684    }
5685
5686    /**
5687     * Indicates whether this view reacts to long click events or not.
5688     *
5689     * @return true if the view is long clickable, false otherwise
5690     *
5691     * @see #setLongClickable(boolean)
5692     * @attr ref android.R.styleable#View_longClickable
5693     */
5694    public boolean isLongClickable() {
5695        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5696    }
5697
5698    /**
5699     * Enables or disables long click events for this view. When a view is long
5700     * clickable it reacts to the user holding down the button for a longer
5701     * duration than a tap. This event can either launch the listener or a
5702     * context menu.
5703     *
5704     * @param longClickable true to make the view long clickable, false otherwise
5705     * @see #isLongClickable()
5706     * @attr ref android.R.styleable#View_longClickable
5707     */
5708    public void setLongClickable(boolean longClickable) {
5709        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5710    }
5711
5712    /**
5713     * Sets the pressed state for this view.
5714     *
5715     * @see #isClickable()
5716     * @see #setClickable(boolean)
5717     *
5718     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5719     *        the View's internal state from a previously set "pressed" state.
5720     */
5721    public void setPressed(boolean pressed) {
5722        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5723
5724        if (pressed) {
5725            mPrivateFlags |= PRESSED;
5726        } else {
5727            mPrivateFlags &= ~PRESSED;
5728        }
5729
5730        if (needsRefresh) {
5731            refreshDrawableState();
5732        }
5733        dispatchSetPressed(pressed);
5734    }
5735
5736    /**
5737     * Dispatch setPressed to all of this View's children.
5738     *
5739     * @see #setPressed(boolean)
5740     *
5741     * @param pressed The new pressed state
5742     */
5743    protected void dispatchSetPressed(boolean pressed) {
5744    }
5745
5746    /**
5747     * Indicates whether the view is currently in pressed state. Unless
5748     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5749     * the pressed state.
5750     *
5751     * @see #setPressed(boolean)
5752     * @see #isClickable()
5753     * @see #setClickable(boolean)
5754     *
5755     * @return true if the view is currently pressed, false otherwise
5756     */
5757    public boolean isPressed() {
5758        return (mPrivateFlags & PRESSED) == PRESSED;
5759    }
5760
5761    /**
5762     * Indicates whether this view will save its state (that is,
5763     * whether its {@link #onSaveInstanceState} method will be called).
5764     *
5765     * @return Returns true if the view state saving is enabled, else false.
5766     *
5767     * @see #setSaveEnabled(boolean)
5768     * @attr ref android.R.styleable#View_saveEnabled
5769     */
5770    public boolean isSaveEnabled() {
5771        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5772    }
5773
5774    /**
5775     * Controls whether the saving of this view's state is
5776     * enabled (that is, whether its {@link #onSaveInstanceState} method
5777     * will be called).  Note that even if freezing is enabled, the
5778     * view still must have an id assigned to it (via {@link #setId(int)})
5779     * for its state to be saved.  This flag can only disable the
5780     * saving of this view; any child views may still have their state saved.
5781     *
5782     * @param enabled Set to false to <em>disable</em> state saving, or true
5783     * (the default) to allow it.
5784     *
5785     * @see #isSaveEnabled()
5786     * @see #setId(int)
5787     * @see #onSaveInstanceState()
5788     * @attr ref android.R.styleable#View_saveEnabled
5789     */
5790    public void setSaveEnabled(boolean enabled) {
5791        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5792    }
5793
5794    /**
5795     * Gets whether the framework should discard touches when the view's
5796     * window is obscured by another visible window.
5797     * Refer to the {@link View} security documentation for more details.
5798     *
5799     * @return True if touch filtering is enabled.
5800     *
5801     * @see #setFilterTouchesWhenObscured(boolean)
5802     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5803     */
5804    @ViewDebug.ExportedProperty
5805    public boolean getFilterTouchesWhenObscured() {
5806        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5807    }
5808
5809    /**
5810     * Sets whether the framework should discard touches when the view's
5811     * window is obscured by another visible window.
5812     * Refer to the {@link View} security documentation for more details.
5813     *
5814     * @param enabled True if touch filtering should be enabled.
5815     *
5816     * @see #getFilterTouchesWhenObscured
5817     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5818     */
5819    public void setFilterTouchesWhenObscured(boolean enabled) {
5820        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5821                FILTER_TOUCHES_WHEN_OBSCURED);
5822    }
5823
5824    /**
5825     * Indicates whether the entire hierarchy under this view will save its
5826     * state when a state saving traversal occurs from its parent.  The default
5827     * is true; if false, these views will not be saved unless
5828     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5829     *
5830     * @return Returns true if the view state saving from parent is enabled, else false.
5831     *
5832     * @see #setSaveFromParentEnabled(boolean)
5833     */
5834    public boolean isSaveFromParentEnabled() {
5835        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5836    }
5837
5838    /**
5839     * Controls whether the entire hierarchy under this view will save its
5840     * state when a state saving traversal occurs from its parent.  The default
5841     * is true; if false, these views will not be saved unless
5842     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5843     *
5844     * @param enabled Set to false to <em>disable</em> state saving, or true
5845     * (the default) to allow it.
5846     *
5847     * @see #isSaveFromParentEnabled()
5848     * @see #setId(int)
5849     * @see #onSaveInstanceState()
5850     */
5851    public void setSaveFromParentEnabled(boolean enabled) {
5852        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5853    }
5854
5855
5856    /**
5857     * Returns whether this View is able to take focus.
5858     *
5859     * @return True if this view can take focus, or false otherwise.
5860     * @attr ref android.R.styleable#View_focusable
5861     */
5862    @ViewDebug.ExportedProperty(category = "focus")
5863    public final boolean isFocusable() {
5864        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5865    }
5866
5867    /**
5868     * When a view is focusable, it may not want to take focus when in touch mode.
5869     * For example, a button would like focus when the user is navigating via a D-pad
5870     * so that the user can click on it, but once the user starts touching the screen,
5871     * the button shouldn't take focus
5872     * @return Whether the view is focusable in touch mode.
5873     * @attr ref android.R.styleable#View_focusableInTouchMode
5874     */
5875    @ViewDebug.ExportedProperty
5876    public final boolean isFocusableInTouchMode() {
5877        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5878    }
5879
5880    /**
5881     * Find the nearest view in the specified direction that can take focus.
5882     * This does not actually give focus to that view.
5883     *
5884     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5885     *
5886     * @return The nearest focusable in the specified direction, or null if none
5887     *         can be found.
5888     */
5889    public View focusSearch(int direction) {
5890        if (mParent != null) {
5891            return mParent.focusSearch(this, direction);
5892        } else {
5893            return null;
5894        }
5895    }
5896
5897    /**
5898     * This method is the last chance for the focused view and its ancestors to
5899     * respond to an arrow key. This is called when the focused view did not
5900     * consume the key internally, nor could the view system find a new view in
5901     * the requested direction to give focus to.
5902     *
5903     * @param focused The currently focused view.
5904     * @param direction The direction focus wants to move. One of FOCUS_UP,
5905     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5906     * @return True if the this view consumed this unhandled move.
5907     */
5908    public boolean dispatchUnhandledMove(View focused, int direction) {
5909        return false;
5910    }
5911
5912    /**
5913     * If a user manually specified the next view id for a particular direction,
5914     * use the root to look up the view.
5915     * @param root The root view of the hierarchy containing this view.
5916     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5917     * or FOCUS_BACKWARD.
5918     * @return The user specified next view, or null if there is none.
5919     */
5920    View findUserSetNextFocus(View root, int direction) {
5921        switch (direction) {
5922            case FOCUS_LEFT:
5923                if (mNextFocusLeftId == View.NO_ID) return null;
5924                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5925            case FOCUS_RIGHT:
5926                if (mNextFocusRightId == View.NO_ID) return null;
5927                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5928            case FOCUS_UP:
5929                if (mNextFocusUpId == View.NO_ID) return null;
5930                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5931            case FOCUS_DOWN:
5932                if (mNextFocusDownId == View.NO_ID) return null;
5933                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5934            case FOCUS_FORWARD:
5935                if (mNextFocusForwardId == View.NO_ID) return null;
5936                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5937            case FOCUS_BACKWARD: {
5938                if (mID == View.NO_ID) return null;
5939                final int id = mID;
5940                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5941                    @Override
5942                    public boolean apply(View t) {
5943                        return t.mNextFocusForwardId == id;
5944                    }
5945                });
5946            }
5947        }
5948        return null;
5949    }
5950
5951    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5952        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5953            @Override
5954            public boolean apply(View t) {
5955                return t.mID == childViewId;
5956            }
5957        });
5958
5959        if (result == null) {
5960            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5961                    + "by user for id " + childViewId);
5962        }
5963        return result;
5964    }
5965
5966    /**
5967     * Find and return all focusable views that are descendants of this view,
5968     * possibly including this view if it is focusable itself.
5969     *
5970     * @param direction The direction of the focus
5971     * @return A list of focusable views
5972     */
5973    public ArrayList<View> getFocusables(int direction) {
5974        ArrayList<View> result = new ArrayList<View>(24);
5975        addFocusables(result, direction);
5976        return result;
5977    }
5978
5979    /**
5980     * Add any focusable views that are descendants of this view (possibly
5981     * including this view if it is focusable itself) to views.  If we are in touch mode,
5982     * only add views that are also focusable in touch mode.
5983     *
5984     * @param views Focusable views found so far
5985     * @param direction The direction of the focus
5986     */
5987    public void addFocusables(ArrayList<View> views, int direction) {
5988        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5989    }
5990
5991    /**
5992     * Adds any focusable views that are descendants of this view (possibly
5993     * including this view if it is focusable itself) to views. This method
5994     * adds all focusable views regardless if we are in touch mode or
5995     * only views focusable in touch mode if we are in touch mode or
5996     * only views that can take accessibility focus if accessibility is enabeld
5997     * depending on the focusable mode paramater.
5998     *
5999     * @param views Focusable views found so far or null if all we are interested is
6000     *        the number of focusables.
6001     * @param direction The direction of the focus.
6002     * @param focusableMode The type of focusables to be added.
6003     *
6004     * @see #FOCUSABLES_ALL
6005     * @see #FOCUSABLES_TOUCH_MODE
6006     */
6007    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6008        if (views == null) {
6009            return;
6010        }
6011        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6012            if (AccessibilityManager.getInstance(mContext).isEnabled()
6013                    && includeForAccessibility()) {
6014                views.add(this);
6015                return;
6016            }
6017        }
6018        if (!isFocusable()) {
6019            return;
6020        }
6021        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6022                && isInTouchMode() && !isFocusableInTouchMode()) {
6023            return;
6024        }
6025        views.add(this);
6026    }
6027
6028    /**
6029     * Finds the Views that contain given text. The containment is case insensitive.
6030     * The search is performed by either the text that the View renders or the content
6031     * description that describes the view for accessibility purposes and the view does
6032     * not render or both. Clients can specify how the search is to be performed via
6033     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6034     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6035     *
6036     * @param outViews The output list of matching Views.
6037     * @param searched The text to match against.
6038     *
6039     * @see #FIND_VIEWS_WITH_TEXT
6040     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6041     * @see #setContentDescription(CharSequence)
6042     */
6043    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6044        if (getAccessibilityNodeProvider() != null) {
6045            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6046                outViews.add(this);
6047            }
6048        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6049                && (searched != null && searched.length() > 0)
6050                && (mContentDescription != null && mContentDescription.length() > 0)) {
6051            String searchedLowerCase = searched.toString().toLowerCase();
6052            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6053            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6054                outViews.add(this);
6055            }
6056        }
6057    }
6058
6059    /**
6060     * Find and return all touchable views that are descendants of this view,
6061     * possibly including this view if it is touchable itself.
6062     *
6063     * @return A list of touchable views
6064     */
6065    public ArrayList<View> getTouchables() {
6066        ArrayList<View> result = new ArrayList<View>();
6067        addTouchables(result);
6068        return result;
6069    }
6070
6071    /**
6072     * Add any touchable views that are descendants of this view (possibly
6073     * including this view if it is touchable itself) to views.
6074     *
6075     * @param views Touchable views found so far
6076     */
6077    public void addTouchables(ArrayList<View> views) {
6078        final int viewFlags = mViewFlags;
6079
6080        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6081                && (viewFlags & ENABLED_MASK) == ENABLED) {
6082            views.add(this);
6083        }
6084    }
6085
6086    /**
6087     * Returns whether this View is accessibility focused.
6088     *
6089     * @return True if this View is accessibility focused.
6090     */
6091    boolean isAccessibilityFocused() {
6092        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6093    }
6094
6095    /**
6096     * Call this to try to give accessibility focus to this view.
6097     *
6098     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6099     * returns false or the view is no visible or the view already has accessibility
6100     * focus.
6101     *
6102     * See also {@link #focusSearch(int)}, which is what you call to say that you
6103     * have focus, and you want your parent to look for the next one.
6104     *
6105     * @return Whether this view actually took accessibility focus.
6106     *
6107     * @hide
6108     */
6109    public boolean requestAccessibilityFocus() {
6110        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6111        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6112            return false;
6113        }
6114        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6115            return false;
6116        }
6117        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6118            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6119            ViewRootImpl viewRootImpl = getViewRootImpl();
6120            if (viewRootImpl != null) {
6121                viewRootImpl.setAccessibilityFocusedHost(this);
6122            }
6123            invalidate();
6124            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6125            notifyAccessibilityStateChanged();
6126            // Try to give input focus to this view - not a descendant.
6127            requestFocusNoSearch(View.FOCUS_DOWN, null);
6128            return true;
6129        }
6130        return false;
6131    }
6132
6133    /**
6134     * Call this to try to clear accessibility focus of this view.
6135     *
6136     * See also {@link #focusSearch(int)}, which is what you call to say that you
6137     * have focus, and you want your parent to look for the next one.
6138     *
6139     * @hide
6140     */
6141    public void clearAccessibilityFocus() {
6142        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6143            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6144            ViewRootImpl viewRootImpl = getViewRootImpl();
6145            if (viewRootImpl != null) {
6146                viewRootImpl.setAccessibilityFocusedHost(null);
6147            }
6148            invalidate();
6149            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6150            notifyAccessibilityStateChanged();
6151
6152            // Clear the text navigation state.
6153            setAccessibilityCursorPosition(-1);
6154
6155            // Try to move accessibility focus to the input focus.
6156            View rootView = getRootView();
6157            if (rootView != null) {
6158                View inputFocus = rootView.findFocus();
6159                if (inputFocus != null) {
6160                    inputFocus.requestAccessibilityFocus();
6161                }
6162            }
6163        }
6164    }
6165
6166    /**
6167     * Find the best view to take accessibility focus from a hover.
6168     * This function finds the deepest actionable view and if that
6169     * fails ask the parent to take accessibility focus from hover.
6170     *
6171     * @param x The X hovered location in this view coorditantes.
6172     * @param y The Y hovered location in this view coorditantes.
6173     * @return Whether the request was handled.
6174     *
6175     * @hide
6176     */
6177    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6178        if (onRequestAccessibilityFocusFromHover(x, y)) {
6179            return true;
6180        }
6181        ViewParent parent = mParent;
6182        if (parent instanceof View) {
6183            View parentView = (View) parent;
6184
6185            float[] position = mAttachInfo.mTmpTransformLocation;
6186            position[0] = x;
6187            position[1] = y;
6188
6189            // Compensate for the transformation of the current matrix.
6190            if (!hasIdentityMatrix()) {
6191                getMatrix().mapPoints(position);
6192            }
6193
6194            // Compensate for the parent scroll and the offset
6195            // of this view stop from the parent top.
6196            position[0] += mLeft - parentView.mScrollX;
6197            position[1] += mTop - parentView.mScrollY;
6198
6199            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6200        }
6201        return false;
6202    }
6203
6204    /**
6205     * Requests to give this View focus from hover.
6206     *
6207     * @param x The X hovered location in this view coorditantes.
6208     * @param y The Y hovered location in this view coorditantes.
6209     * @return Whether the request was handled.
6210     *
6211     * @hide
6212     */
6213    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6214        if (includeForAccessibility()
6215                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6216            return requestAccessibilityFocus();
6217        }
6218        return false;
6219    }
6220
6221    /**
6222     * Clears accessibility focus without calling any callback methods
6223     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6224     * is used for clearing accessibility focus when giving this focus to
6225     * another view.
6226     */
6227    void clearAccessibilityFocusNoCallbacks() {
6228        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6229            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6230            invalidate();
6231        }
6232    }
6233
6234    /**
6235     * Call this to try to give focus to a specific view or to one of its
6236     * descendants.
6237     *
6238     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6239     * false), or if it is focusable and it is not focusable in touch mode
6240     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6241     *
6242     * See also {@link #focusSearch(int)}, which is what you call to say that you
6243     * have focus, and you want your parent to look for the next one.
6244     *
6245     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6246     * {@link #FOCUS_DOWN} and <code>null</code>.
6247     *
6248     * @return Whether this view or one of its descendants actually took focus.
6249     */
6250    public final boolean requestFocus() {
6251        return requestFocus(View.FOCUS_DOWN);
6252    }
6253
6254    /**
6255     * Call this to try to give focus to a specific view or to one of its
6256     * descendants and give it a hint about what direction focus is heading.
6257     *
6258     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6259     * false), or if it is focusable and it is not focusable in touch mode
6260     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6261     *
6262     * See also {@link #focusSearch(int)}, which is what you call to say that you
6263     * have focus, and you want your parent to look for the next one.
6264     *
6265     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6266     * <code>null</code> set for the previously focused rectangle.
6267     *
6268     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6269     * @return Whether this view or one of its descendants actually took focus.
6270     */
6271    public final boolean requestFocus(int direction) {
6272        return requestFocus(direction, null);
6273    }
6274
6275    /**
6276     * Call this to try to give focus to a specific view or to one of its descendants
6277     * and give it hints about the direction and a specific rectangle that the focus
6278     * is coming from.  The rectangle can help give larger views a finer grained hint
6279     * about where focus is coming from, and therefore, where to show selection, or
6280     * forward focus change internally.
6281     *
6282     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6283     * false), or if it is focusable and it is not focusable in touch mode
6284     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6285     *
6286     * A View will not take focus if it is not visible.
6287     *
6288     * A View will not take focus if one of its parents has
6289     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6290     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6291     *
6292     * See also {@link #focusSearch(int)}, which is what you call to say that you
6293     * have focus, and you want your parent to look for the next one.
6294     *
6295     * You may wish to override this method if your custom {@link View} has an internal
6296     * {@link View} that it wishes to forward the request to.
6297     *
6298     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6299     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6300     *        to give a finer grained hint about where focus is coming from.  May be null
6301     *        if there is no hint.
6302     * @return Whether this view or one of its descendants actually took focus.
6303     */
6304    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6305        return requestFocusNoSearch(direction, previouslyFocusedRect);
6306    }
6307
6308    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6309        // need to be focusable
6310        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6311                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6312            return false;
6313        }
6314
6315        // need to be focusable in touch mode if in touch mode
6316        if (isInTouchMode() &&
6317            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6318               return false;
6319        }
6320
6321        // need to not have any parents blocking us
6322        if (hasAncestorThatBlocksDescendantFocus()) {
6323            return false;
6324        }
6325
6326        handleFocusGainInternal(direction, previouslyFocusedRect);
6327        return true;
6328    }
6329
6330    /**
6331     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6332     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6333     * touch mode to request focus when they are touched.
6334     *
6335     * @return Whether this view or one of its descendants actually took focus.
6336     *
6337     * @see #isInTouchMode()
6338     *
6339     */
6340    public final boolean requestFocusFromTouch() {
6341        // Leave touch mode if we need to
6342        if (isInTouchMode()) {
6343            ViewRootImpl viewRoot = getViewRootImpl();
6344            if (viewRoot != null) {
6345                viewRoot.ensureTouchMode(false);
6346            }
6347        }
6348        return requestFocus(View.FOCUS_DOWN);
6349    }
6350
6351    /**
6352     * @return Whether any ancestor of this view blocks descendant focus.
6353     */
6354    private boolean hasAncestorThatBlocksDescendantFocus() {
6355        ViewParent ancestor = mParent;
6356        while (ancestor instanceof ViewGroup) {
6357            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6358            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6359                return true;
6360            } else {
6361                ancestor = vgAncestor.getParent();
6362            }
6363        }
6364        return false;
6365    }
6366
6367    /**
6368     * Gets the mode for determining whether this View is important for accessibility
6369     * which is if it fires accessibility events and if it is reported to
6370     * accessibility services that query the screen.
6371     *
6372     * @return The mode for determining whether a View is important for accessibility.
6373     *
6374     * @attr ref android.R.styleable#View_importantForAccessibility
6375     *
6376     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6377     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6378     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6379     */
6380    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6381            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6382                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6383            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6384                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6385            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6386                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6387        })
6388    public int getImportantForAccessibility() {
6389        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6390                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6391    }
6392
6393    /**
6394     * Sets how to determine whether this view is important for accessibility
6395     * which is if it fires accessibility events and if it is reported to
6396     * accessibility services that query the screen.
6397     *
6398     * @param mode How to determine whether this view is important for accessibility.
6399     *
6400     * @attr ref android.R.styleable#View_importantForAccessibility
6401     *
6402     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6403     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6404     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6405     */
6406    public void setImportantForAccessibility(int mode) {
6407        if (mode != getImportantForAccessibility()) {
6408            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6409            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6410                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6411            notifyAccessibilityStateChanged();
6412        }
6413    }
6414
6415    /**
6416     * Gets whether this view should be exposed for accessibility.
6417     *
6418     * @return Whether the view is exposed for accessibility.
6419     *
6420     * @hide
6421     */
6422    public boolean isImportantForAccessibility() {
6423        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6424                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6425        switch (mode) {
6426            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6427                return true;
6428            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6429                return false;
6430            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6431                return isActionableForAccessibility() || hasListenersForAccessibility();
6432            default:
6433                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6434                        + mode);
6435        }
6436    }
6437
6438    /**
6439     * Gets the parent for accessibility purposes. Note that the parent for
6440     * accessibility is not necessary the immediate parent. It is the first
6441     * predecessor that is important for accessibility.
6442     *
6443     * @return The parent for accessibility purposes.
6444     */
6445    public ViewParent getParentForAccessibility() {
6446        if (mParent instanceof View) {
6447            View parentView = (View) mParent;
6448            if (parentView.includeForAccessibility()) {
6449                return mParent;
6450            } else {
6451                return mParent.getParentForAccessibility();
6452            }
6453        }
6454        return null;
6455    }
6456
6457    /**
6458     * Adds the children of a given View for accessibility. Since some Views are
6459     * not important for accessibility the children for accessibility are not
6460     * necessarily direct children of the riew, rather they are the first level of
6461     * descendants important for accessibility.
6462     *
6463     * @param children The list of children for accessibility.
6464     */
6465    public void addChildrenForAccessibility(ArrayList<View> children) {
6466        if (includeForAccessibility()) {
6467            children.add(this);
6468        }
6469    }
6470
6471    /**
6472     * Whether to regard this view for accessibility. A view is regarded for
6473     * accessibility if it is important for accessibility or the querying
6474     * accessibility service has explicitly requested that view not
6475     * important for accessibility are regarded.
6476     *
6477     * @return Whether to regard the view for accessibility.
6478     */
6479    boolean includeForAccessibility() {
6480        if (mAttachInfo != null) {
6481            if (!mAttachInfo.mIncludeNotImportantViews) {
6482                return isImportantForAccessibility();
6483            } else {
6484                return true;
6485            }
6486        }
6487        return false;
6488    }
6489
6490    /**
6491     * Returns whether the View is considered actionable from
6492     * accessibility perspective. Such view are important for
6493     * accessiiblity.
6494     *
6495     * @return True if the view is actionable for accessibility.
6496     */
6497    private boolean isActionableForAccessibility() {
6498        return (isClickable() || isLongClickable() || isFocusable());
6499    }
6500
6501    /**
6502     * Returns whether the View has registered callbacks wich makes it
6503     * important for accessiiblity.
6504     *
6505     * @return True if the view is actionable for accessibility.
6506     */
6507    private boolean hasListenersForAccessibility() {
6508        ListenerInfo info = getListenerInfo();
6509        return mTouchDelegate != null || info.mOnKeyListener != null
6510                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6511                || info.mOnHoverListener != null || info.mOnDragListener != null;
6512    }
6513
6514    /**
6515     * Notifies accessibility services that some view's important for
6516     * accessibility state has changed. Note that such notifications
6517     * are made at most once every
6518     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6519     * to avoid unnecessary load to the system. Also once a view has
6520     * made a notifucation this method is a NOP until the notification has
6521     * been sent to clients.
6522     *
6523     * @hide
6524     *
6525     * TODO: Makse sure this method is called for any view state change
6526     *       that is interesting for accessilility purposes.
6527     */
6528    public void notifyAccessibilityStateChanged() {
6529        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6530            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6531            if (mParent != null) {
6532                mParent.childAccessibilityStateChanged(this);
6533            }
6534        }
6535    }
6536
6537    /**
6538     * Reset the state indicating the this view has requested clients
6539     * interested in its accessiblity state to be notified.
6540     *
6541     * @hide
6542     */
6543    public void resetAccessibilityStateChanged() {
6544        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6545    }
6546
6547    /**
6548     * Performs the specified accessibility action on the view. For
6549     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6550    * <p>
6551    * If an {@link AccessibilityDelegate} has been specified via calling
6552    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6553    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6554    * is responsible for handling this call.
6555    * </p>
6556     *
6557     * @param action The action to perform.
6558     * @param arguments Optional action arguments.
6559     * @return Whether the action was performed.
6560     */
6561    public boolean performAccessibilityAction(int action, Bundle arguments) {
6562      if (mAccessibilityDelegate != null) {
6563          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6564      } else {
6565          return performAccessibilityActionInternal(action, arguments);
6566      }
6567    }
6568
6569   /**
6570    * @see #performAccessibilityAction(int, Bundle)
6571    *
6572    * Note: Called from the default {@link AccessibilityDelegate}.
6573    */
6574    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6575        switch (action) {
6576            case AccessibilityNodeInfo.ACTION_CLICK: {
6577                if (isClickable()) {
6578                    return performClick();
6579                }
6580            } break;
6581            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6582                if (isLongClickable()) {
6583                    return performLongClick();
6584                }
6585            } break;
6586            case AccessibilityNodeInfo.ACTION_FOCUS: {
6587                if (!hasFocus()) {
6588                    // Get out of touch mode since accessibility
6589                    // wants to move focus around.
6590                    getViewRootImpl().ensureTouchMode(false);
6591                    return requestFocus();
6592                }
6593            } break;
6594            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6595                if (hasFocus()) {
6596                    clearFocus();
6597                    return !isFocused();
6598                }
6599            } break;
6600            case AccessibilityNodeInfo.ACTION_SELECT: {
6601                if (!isSelected()) {
6602                    setSelected(true);
6603                    return isSelected();
6604                }
6605            } break;
6606            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6607                if (isSelected()) {
6608                    setSelected(false);
6609                    return !isSelected();
6610                }
6611            } break;
6612            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6613                if (!isAccessibilityFocused()) {
6614                    return requestAccessibilityFocus();
6615                }
6616            } break;
6617            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6618                if (isAccessibilityFocused()) {
6619                    clearAccessibilityFocus();
6620                    return true;
6621                }
6622            } break;
6623            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6624                if (arguments != null) {
6625                    final int granularity = arguments.getInt(
6626                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6627                    return nextAtGranularity(granularity);
6628                }
6629            } break;
6630            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6631                if (arguments != null) {
6632                    final int granularity = arguments.getInt(
6633                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6634                    return previousAtGranularity(granularity);
6635                }
6636            } break;
6637        }
6638        return false;
6639    }
6640
6641    private boolean nextAtGranularity(int granularity) {
6642        CharSequence text = getIterableTextForAccessibility();
6643        if (text != null && text.length() > 0) {
6644            return false;
6645        }
6646        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6647        if (iterator == null) {
6648            return false;
6649        }
6650        final int current = getAccessibilityCursorPosition();
6651        final int[] range = iterator.following(current);
6652        if (range == null) {
6653            setAccessibilityCursorPosition(-1);
6654            return false;
6655        }
6656        final int start = range[0];
6657        final int end = range[1];
6658        setAccessibilityCursorPosition(start);
6659        sendViewTextTraversedAtGranularityEvent(
6660                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6661                granularity, start, end);
6662        return true;
6663    }
6664
6665    private boolean previousAtGranularity(int granularity) {
6666        CharSequence text = getIterableTextForAccessibility();
6667        if (text != null && text.length() > 0) {
6668            return false;
6669        }
6670        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6671        if (iterator == null) {
6672            return false;
6673        }
6674        final int selectionStart = getAccessibilityCursorPosition();
6675        final int current = selectionStart >= 0 ? selectionStart : text.length() + 1;
6676        final int[] range = iterator.preceding(current);
6677        if (range == null) {
6678            setAccessibilityCursorPosition(-1);
6679            return false;
6680        }
6681        final int start = range[0];
6682        final int end = range[1];
6683        setAccessibilityCursorPosition(end);
6684        sendViewTextTraversedAtGranularityEvent(
6685                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6686                granularity, start, end);
6687        return true;
6688    }
6689
6690    /**
6691     * Gets the text reported for accessibility purposes.
6692     *
6693     * @return The accessibility text.
6694     *
6695     * @hide
6696     */
6697    public CharSequence getIterableTextForAccessibility() {
6698        return mContentDescription;
6699    }
6700
6701    /**
6702     * @hide
6703     */
6704    public int getAccessibilityCursorPosition() {
6705        return mAccessibilityCursorPosition;
6706    }
6707
6708    /**
6709     * @hide
6710     */
6711    public void setAccessibilityCursorPosition(int position) {
6712        mAccessibilityCursorPosition = position;
6713    }
6714
6715    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6716            int fromIndex, int toIndex) {
6717        if (mParent == null) {
6718            return;
6719        }
6720        AccessibilityEvent event = AccessibilityEvent.obtain(
6721                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6722        onInitializeAccessibilityEvent(event);
6723        onPopulateAccessibilityEvent(event);
6724        event.setFromIndex(fromIndex);
6725        event.setToIndex(toIndex);
6726        event.setAction(action);
6727        event.setMovementGranularity(granularity);
6728        mParent.requestSendAccessibilityEvent(this, event);
6729    }
6730
6731    /**
6732     * @hide
6733     */
6734    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6735        switch (granularity) {
6736            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6737                CharSequence text = getIterableTextForAccessibility();
6738                if (text != null && text.length() > 0) {
6739                    CharacterTextSegmentIterator iterator =
6740                        CharacterTextSegmentIterator.getInstance(mContext);
6741                    iterator.initialize(text.toString());
6742                    return iterator;
6743                }
6744            } break;
6745            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6746                CharSequence text = getIterableTextForAccessibility();
6747                if (text != null && text.length() > 0) {
6748                    WordTextSegmentIterator iterator =
6749                        WordTextSegmentIterator.getInstance(mContext);
6750                    iterator.initialize(text.toString());
6751                    return iterator;
6752                }
6753            } break;
6754            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6755                CharSequence text = getIterableTextForAccessibility();
6756                if (text != null && text.length() > 0) {
6757                    ParagraphTextSegmentIterator iterator =
6758                        ParagraphTextSegmentIterator.getInstance();
6759                    iterator.initialize(text.toString());
6760                    return iterator;
6761                }
6762            } break;
6763        }
6764        return null;
6765    }
6766
6767    /**
6768     * @hide
6769     */
6770    public void dispatchStartTemporaryDetach() {
6771        clearAccessibilityFocus();
6772        onStartTemporaryDetach();
6773    }
6774
6775    /**
6776     * This is called when a container is going to temporarily detach a child, with
6777     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6778     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6779     * {@link #onDetachedFromWindow()} when the container is done.
6780     */
6781    public void onStartTemporaryDetach() {
6782        removeUnsetPressCallback();
6783        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6784    }
6785
6786    /**
6787     * @hide
6788     */
6789    public void dispatchFinishTemporaryDetach() {
6790        onFinishTemporaryDetach();
6791    }
6792
6793    /**
6794     * Called after {@link #onStartTemporaryDetach} when the container is done
6795     * changing the view.
6796     */
6797    public void onFinishTemporaryDetach() {
6798    }
6799
6800    /**
6801     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6802     * for this view's window.  Returns null if the view is not currently attached
6803     * to the window.  Normally you will not need to use this directly, but
6804     * just use the standard high-level event callbacks like
6805     * {@link #onKeyDown(int, KeyEvent)}.
6806     */
6807    public KeyEvent.DispatcherState getKeyDispatcherState() {
6808        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6809    }
6810
6811    /**
6812     * Dispatch a key event before it is processed by any input method
6813     * associated with the view hierarchy.  This can be used to intercept
6814     * key events in special situations before the IME consumes them; a
6815     * typical example would be handling the BACK key to update the application's
6816     * UI instead of allowing the IME to see it and close itself.
6817     *
6818     * @param event The key event to be dispatched.
6819     * @return True if the event was handled, false otherwise.
6820     */
6821    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6822        return onKeyPreIme(event.getKeyCode(), event);
6823    }
6824
6825    /**
6826     * Dispatch a key event to the next view on the focus path. This path runs
6827     * from the top of the view tree down to the currently focused view. If this
6828     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6829     * the next node down the focus path. This method also fires any key
6830     * listeners.
6831     *
6832     * @param event The key event to be dispatched.
6833     * @return True if the event was handled, false otherwise.
6834     */
6835    public boolean dispatchKeyEvent(KeyEvent event) {
6836        if (mInputEventConsistencyVerifier != null) {
6837            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6838        }
6839
6840        // Give any attached key listener a first crack at the event.
6841        //noinspection SimplifiableIfStatement
6842        ListenerInfo li = mListenerInfo;
6843        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6844                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6845            return true;
6846        }
6847
6848        if (event.dispatch(this, mAttachInfo != null
6849                ? mAttachInfo.mKeyDispatchState : null, this)) {
6850            return true;
6851        }
6852
6853        if (mInputEventConsistencyVerifier != null) {
6854            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6855        }
6856        return false;
6857    }
6858
6859    /**
6860     * Dispatches a key shortcut event.
6861     *
6862     * @param event The key event to be dispatched.
6863     * @return True if the event was handled by the view, false otherwise.
6864     */
6865    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6866        return onKeyShortcut(event.getKeyCode(), event);
6867    }
6868
6869    /**
6870     * Pass the touch screen motion event down to the target view, or this
6871     * view if it is the target.
6872     *
6873     * @param event The motion event to be dispatched.
6874     * @return True if the event was handled by the view, false otherwise.
6875     */
6876    public boolean dispatchTouchEvent(MotionEvent event) {
6877        if (mInputEventConsistencyVerifier != null) {
6878            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6879        }
6880
6881        if (onFilterTouchEventForSecurity(event)) {
6882            //noinspection SimplifiableIfStatement
6883            ListenerInfo li = mListenerInfo;
6884            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6885                    && li.mOnTouchListener.onTouch(this, event)) {
6886                return true;
6887            }
6888
6889            if (onTouchEvent(event)) {
6890                return true;
6891            }
6892        }
6893
6894        if (mInputEventConsistencyVerifier != null) {
6895            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6896        }
6897        return false;
6898    }
6899
6900    /**
6901     * Filter the touch event to apply security policies.
6902     *
6903     * @param event The motion event to be filtered.
6904     * @return True if the event should be dispatched, false if the event should be dropped.
6905     *
6906     * @see #getFilterTouchesWhenObscured
6907     */
6908    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6909        //noinspection RedundantIfStatement
6910        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6911                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6912            // Window is obscured, drop this touch.
6913            return false;
6914        }
6915        return true;
6916    }
6917
6918    /**
6919     * Pass a trackball motion event down to the focused view.
6920     *
6921     * @param event The motion event to be dispatched.
6922     * @return True if the event was handled by the view, false otherwise.
6923     */
6924    public boolean dispatchTrackballEvent(MotionEvent event) {
6925        if (mInputEventConsistencyVerifier != null) {
6926            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6927        }
6928
6929        return onTrackballEvent(event);
6930    }
6931
6932    /**
6933     * Dispatch a generic motion event.
6934     * <p>
6935     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6936     * are delivered to the view under the pointer.  All other generic motion events are
6937     * delivered to the focused view.  Hover events are handled specially and are delivered
6938     * to {@link #onHoverEvent(MotionEvent)}.
6939     * </p>
6940     *
6941     * @param event The motion event to be dispatched.
6942     * @return True if the event was handled by the view, false otherwise.
6943     */
6944    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6945        if (mInputEventConsistencyVerifier != null) {
6946            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6947        }
6948
6949        final int source = event.getSource();
6950        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6951            final int action = event.getAction();
6952            if (action == MotionEvent.ACTION_HOVER_ENTER
6953                    || action == MotionEvent.ACTION_HOVER_MOVE
6954                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6955                if (dispatchHoverEvent(event)) {
6956                    return true;
6957                }
6958            } else if (dispatchGenericPointerEvent(event)) {
6959                return true;
6960            }
6961        } else if (dispatchGenericFocusedEvent(event)) {
6962            return true;
6963        }
6964
6965        if (dispatchGenericMotionEventInternal(event)) {
6966            return true;
6967        }
6968
6969        if (mInputEventConsistencyVerifier != null) {
6970            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6971        }
6972        return false;
6973    }
6974
6975    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6976        //noinspection SimplifiableIfStatement
6977        ListenerInfo li = mListenerInfo;
6978        if (li != null && li.mOnGenericMotionListener != null
6979                && (mViewFlags & ENABLED_MASK) == ENABLED
6980                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6981            return true;
6982        }
6983
6984        if (onGenericMotionEvent(event)) {
6985            return true;
6986        }
6987
6988        if (mInputEventConsistencyVerifier != null) {
6989            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6990        }
6991        return false;
6992    }
6993
6994    /**
6995     * Dispatch a hover event.
6996     * <p>
6997     * Do not call this method directly.
6998     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6999     * </p>
7000     *
7001     * @param event The motion event to be dispatched.
7002     * @return True if the event was handled by the view, false otherwise.
7003     */
7004    protected boolean dispatchHoverEvent(MotionEvent event) {
7005        //noinspection SimplifiableIfStatement
7006        ListenerInfo li = mListenerInfo;
7007        if (li != null && li.mOnHoverListener != null
7008                && (mViewFlags & ENABLED_MASK) == ENABLED
7009                && li.mOnHoverListener.onHover(this, event)) {
7010            return true;
7011        }
7012
7013        return onHoverEvent(event);
7014    }
7015
7016    /**
7017     * Returns true if the view has a child to which it has recently sent
7018     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7019     * it does not have a hovered child, then it must be the innermost hovered view.
7020     * @hide
7021     */
7022    protected boolean hasHoveredChild() {
7023        return false;
7024    }
7025
7026    /**
7027     * Dispatch a generic motion event to the view under the first pointer.
7028     * <p>
7029     * Do not call this method directly.
7030     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7031     * </p>
7032     *
7033     * @param event The motion event to be dispatched.
7034     * @return True if the event was handled by the view, false otherwise.
7035     */
7036    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7037        return false;
7038    }
7039
7040    /**
7041     * Dispatch a generic motion event to the currently focused view.
7042     * <p>
7043     * Do not call this method directly.
7044     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7045     * </p>
7046     *
7047     * @param event The motion event to be dispatched.
7048     * @return True if the event was handled by the view, false otherwise.
7049     */
7050    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7051        return false;
7052    }
7053
7054    /**
7055     * Dispatch a pointer event.
7056     * <p>
7057     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7058     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7059     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7060     * and should not be expected to handle other pointing device features.
7061     * </p>
7062     *
7063     * @param event The motion event to be dispatched.
7064     * @return True if the event was handled by the view, false otherwise.
7065     * @hide
7066     */
7067    public final boolean dispatchPointerEvent(MotionEvent event) {
7068        if (event.isTouchEvent()) {
7069            return dispatchTouchEvent(event);
7070        } else {
7071            return dispatchGenericMotionEvent(event);
7072        }
7073    }
7074
7075    /**
7076     * Called when the window containing this view gains or loses window focus.
7077     * ViewGroups should override to route to their children.
7078     *
7079     * @param hasFocus True if the window containing this view now has focus,
7080     *        false otherwise.
7081     */
7082    public void dispatchWindowFocusChanged(boolean hasFocus) {
7083        onWindowFocusChanged(hasFocus);
7084    }
7085
7086    /**
7087     * Called when the window containing this view gains or loses focus.  Note
7088     * that this is separate from view focus: to receive key events, both
7089     * your view and its window must have focus.  If a window is displayed
7090     * on top of yours that takes input focus, then your own window will lose
7091     * focus but the view focus will remain unchanged.
7092     *
7093     * @param hasWindowFocus True if the window containing this view now has
7094     *        focus, false otherwise.
7095     */
7096    public void onWindowFocusChanged(boolean hasWindowFocus) {
7097        InputMethodManager imm = InputMethodManager.peekInstance();
7098        if (!hasWindowFocus) {
7099            if (isPressed()) {
7100                setPressed(false);
7101            }
7102            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7103                imm.focusOut(this);
7104            }
7105            removeLongPressCallback();
7106            removeTapCallback();
7107            onFocusLost();
7108        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7109            imm.focusIn(this);
7110        }
7111        refreshDrawableState();
7112    }
7113
7114    /**
7115     * Returns true if this view is in a window that currently has window focus.
7116     * Note that this is not the same as the view itself having focus.
7117     *
7118     * @return True if this view is in a window that currently has window focus.
7119     */
7120    public boolean hasWindowFocus() {
7121        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7122    }
7123
7124    /**
7125     * Dispatch a view visibility change down the view hierarchy.
7126     * ViewGroups should override to route to their children.
7127     * @param changedView The view whose visibility changed. Could be 'this' or
7128     * an ancestor view.
7129     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7130     * {@link #INVISIBLE} or {@link #GONE}.
7131     */
7132    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7133        onVisibilityChanged(changedView, visibility);
7134    }
7135
7136    /**
7137     * Called when the visibility of the view or an ancestor of the view is changed.
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 onVisibilityChanged(View changedView, int visibility) {
7144        if (visibility == VISIBLE) {
7145            if (mAttachInfo != null) {
7146                initialAwakenScrollBars();
7147            } else {
7148                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7149            }
7150        }
7151    }
7152
7153    /**
7154     * Dispatch a hint about whether this view is displayed. For instance, when
7155     * a View moves out of the screen, it might receives a display hint indicating
7156     * the view is not displayed. Applications should not <em>rely</em> on this hint
7157     * as there is no guarantee that they will receive one.
7158     *
7159     * @param hint A hint about whether or not this view is displayed:
7160     * {@link #VISIBLE} or {@link #INVISIBLE}.
7161     */
7162    public void dispatchDisplayHint(int hint) {
7163        onDisplayHint(hint);
7164    }
7165
7166    /**
7167     * Gives this view a hint about whether is displayed or not. For instance, when
7168     * a View moves out of the screen, it might receives a display hint indicating
7169     * the view is not displayed. Applications should not <em>rely</em> on this hint
7170     * as there is no guarantee that they will receive one.
7171     *
7172     * @param hint A hint about whether or not this view is displayed:
7173     * {@link #VISIBLE} or {@link #INVISIBLE}.
7174     */
7175    protected void onDisplayHint(int hint) {
7176    }
7177
7178    /**
7179     * Dispatch a window visibility change down the view hierarchy.
7180     * ViewGroups should override to route to their children.
7181     *
7182     * @param visibility The new visibility of the window.
7183     *
7184     * @see #onWindowVisibilityChanged(int)
7185     */
7186    public void dispatchWindowVisibilityChanged(int visibility) {
7187        onWindowVisibilityChanged(visibility);
7188    }
7189
7190    /**
7191     * Called when the window containing has change its visibility
7192     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7193     * that this tells you whether or not your window is being made visible
7194     * to the window manager; this does <em>not</em> tell you whether or not
7195     * your window is obscured by other windows on the screen, even if it
7196     * is itself visible.
7197     *
7198     * @param visibility The new visibility of the window.
7199     */
7200    protected void onWindowVisibilityChanged(int visibility) {
7201        if (visibility == VISIBLE) {
7202            initialAwakenScrollBars();
7203        }
7204    }
7205
7206    /**
7207     * Returns the current visibility of the window this view is attached to
7208     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7209     *
7210     * @return Returns the current visibility of the view's window.
7211     */
7212    public int getWindowVisibility() {
7213        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7214    }
7215
7216    /**
7217     * Retrieve the overall visible display size in which the window this view is
7218     * attached to has been positioned in.  This takes into account screen
7219     * decorations above the window, for both cases where the window itself
7220     * is being position inside of them or the window is being placed under
7221     * then and covered insets are used for the window to position its content
7222     * inside.  In effect, this tells you the available area where content can
7223     * be placed and remain visible to users.
7224     *
7225     * <p>This function requires an IPC back to the window manager to retrieve
7226     * the requested information, so should not be used in performance critical
7227     * code like drawing.
7228     *
7229     * @param outRect Filled in with the visible display frame.  If the view
7230     * is not attached to a window, this is simply the raw display size.
7231     */
7232    public void getWindowVisibleDisplayFrame(Rect outRect) {
7233        if (mAttachInfo != null) {
7234            try {
7235                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7236            } catch (RemoteException e) {
7237                return;
7238            }
7239            // XXX This is really broken, and probably all needs to be done
7240            // in the window manager, and we need to know more about whether
7241            // we want the area behind or in front of the IME.
7242            final Rect insets = mAttachInfo.mVisibleInsets;
7243            outRect.left += insets.left;
7244            outRect.top += insets.top;
7245            outRect.right -= insets.right;
7246            outRect.bottom -= insets.bottom;
7247            return;
7248        }
7249        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7250        d.getRectSize(outRect);
7251    }
7252
7253    /**
7254     * Dispatch a notification about a resource configuration change down
7255     * the view hierarchy.
7256     * ViewGroups should override to route to their children.
7257     *
7258     * @param newConfig The new resource configuration.
7259     *
7260     * @see #onConfigurationChanged(android.content.res.Configuration)
7261     */
7262    public void dispatchConfigurationChanged(Configuration newConfig) {
7263        onConfigurationChanged(newConfig);
7264    }
7265
7266    /**
7267     * Called when the current configuration of the resources being used
7268     * by the application have changed.  You can use this to decide when
7269     * to reload resources that can changed based on orientation and other
7270     * configuration characterstics.  You only need to use this if you are
7271     * not relying on the normal {@link android.app.Activity} mechanism of
7272     * recreating the activity instance upon a configuration change.
7273     *
7274     * @param newConfig The new resource configuration.
7275     */
7276    protected void onConfigurationChanged(Configuration newConfig) {
7277    }
7278
7279    /**
7280     * Private function to aggregate all per-view attributes in to the view
7281     * root.
7282     */
7283    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7284        performCollectViewAttributes(attachInfo, visibility);
7285    }
7286
7287    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7288        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7289            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7290                attachInfo.mKeepScreenOn = true;
7291            }
7292            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7293            ListenerInfo li = mListenerInfo;
7294            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7295                attachInfo.mHasSystemUiListeners = true;
7296            }
7297        }
7298    }
7299
7300    void needGlobalAttributesUpdate(boolean force) {
7301        final AttachInfo ai = mAttachInfo;
7302        if (ai != null) {
7303            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7304                    || ai.mHasSystemUiListeners) {
7305                ai.mRecomputeGlobalAttributes = true;
7306            }
7307        }
7308    }
7309
7310    /**
7311     * Returns whether the device is currently in touch mode.  Touch mode is entered
7312     * once the user begins interacting with the device by touch, and affects various
7313     * things like whether focus is always visible to the user.
7314     *
7315     * @return Whether the device is in touch mode.
7316     */
7317    @ViewDebug.ExportedProperty
7318    public boolean isInTouchMode() {
7319        if (mAttachInfo != null) {
7320            return mAttachInfo.mInTouchMode;
7321        } else {
7322            return ViewRootImpl.isInTouchMode();
7323        }
7324    }
7325
7326    /**
7327     * Returns the context the view is running in, through which it can
7328     * access the current theme, resources, etc.
7329     *
7330     * @return The view's Context.
7331     */
7332    @ViewDebug.CapturedViewProperty
7333    public final Context getContext() {
7334        return mContext;
7335    }
7336
7337    /**
7338     * Handle a key event before it is processed by any input method
7339     * associated with the view hierarchy.  This can be used to intercept
7340     * key events in special situations before the IME consumes them; a
7341     * typical example would be handling the BACK key to update the application's
7342     * UI instead of allowing the IME to see it and close itself.
7343     *
7344     * @param keyCode The value in event.getKeyCode().
7345     * @param event Description of the key event.
7346     * @return If you handled the event, return true. If you want to allow the
7347     *         event to be handled by the next receiver, return false.
7348     */
7349    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7350        return false;
7351    }
7352
7353    /**
7354     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7355     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7356     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7357     * is released, if the view is enabled and clickable.
7358     *
7359     * @param keyCode A key code that represents the button pressed, from
7360     *                {@link android.view.KeyEvent}.
7361     * @param event   The KeyEvent object that defines the button action.
7362     */
7363    public boolean onKeyDown(int keyCode, KeyEvent event) {
7364        boolean result = false;
7365
7366        switch (keyCode) {
7367            case KeyEvent.KEYCODE_DPAD_CENTER:
7368            case KeyEvent.KEYCODE_ENTER: {
7369                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7370                    return true;
7371                }
7372                // Long clickable items don't necessarily have to be clickable
7373                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7374                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7375                        (event.getRepeatCount() == 0)) {
7376                    setPressed(true);
7377                    checkForLongClick(0);
7378                    return true;
7379                }
7380                break;
7381            }
7382        }
7383        return result;
7384    }
7385
7386    /**
7387     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7388     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7389     * the event).
7390     */
7391    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7392        return false;
7393    }
7394
7395    /**
7396     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7397     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7398     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7399     * {@link KeyEvent#KEYCODE_ENTER} is released.
7400     *
7401     * @param keyCode A key code that represents the button pressed, from
7402     *                {@link android.view.KeyEvent}.
7403     * @param event   The KeyEvent object that defines the button action.
7404     */
7405    public boolean onKeyUp(int keyCode, KeyEvent event) {
7406        boolean result = false;
7407
7408        switch (keyCode) {
7409            case KeyEvent.KEYCODE_DPAD_CENTER:
7410            case KeyEvent.KEYCODE_ENTER: {
7411                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7412                    return true;
7413                }
7414                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7415                    setPressed(false);
7416
7417                    if (!mHasPerformedLongPress) {
7418                        // This is a tap, so remove the longpress check
7419                        removeLongPressCallback();
7420
7421                        result = performClick();
7422                    }
7423                }
7424                break;
7425            }
7426        }
7427        return result;
7428    }
7429
7430    /**
7431     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7432     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7433     * the event).
7434     *
7435     * @param keyCode     A key code that represents the button pressed, from
7436     *                    {@link android.view.KeyEvent}.
7437     * @param repeatCount The number of times the action was made.
7438     * @param event       The KeyEvent object that defines the button action.
7439     */
7440    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7441        return false;
7442    }
7443
7444    /**
7445     * Called on the focused view when a key shortcut event is not handled.
7446     * Override this method to implement local key shortcuts for the View.
7447     * Key shortcuts can also be implemented by setting the
7448     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7449     *
7450     * @param keyCode The value in event.getKeyCode().
7451     * @param event Description of the key event.
7452     * @return If you handled the event, return true. If you want to allow the
7453     *         event to be handled by the next receiver, return false.
7454     */
7455    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7456        return false;
7457    }
7458
7459    /**
7460     * Check whether the called view is a text editor, in which case it
7461     * would make sense to automatically display a soft input window for
7462     * it.  Subclasses should override this if they implement
7463     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7464     * a call on that method would return a non-null InputConnection, and
7465     * they are really a first-class editor that the user would normally
7466     * start typing on when the go into a window containing your view.
7467     *
7468     * <p>The default implementation always returns false.  This does
7469     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7470     * will not be called or the user can not otherwise perform edits on your
7471     * view; it is just a hint to the system that this is not the primary
7472     * purpose of this view.
7473     *
7474     * @return Returns true if this view is a text editor, else false.
7475     */
7476    public boolean onCheckIsTextEditor() {
7477        return false;
7478    }
7479
7480    /**
7481     * Create a new InputConnection for an InputMethod to interact
7482     * with the view.  The default implementation returns null, since it doesn't
7483     * support input methods.  You can override this to implement such support.
7484     * This is only needed for views that take focus and text input.
7485     *
7486     * <p>When implementing this, you probably also want to implement
7487     * {@link #onCheckIsTextEditor()} to indicate you will return a
7488     * non-null InputConnection.
7489     *
7490     * @param outAttrs Fill in with attribute information about the connection.
7491     */
7492    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7493        return null;
7494    }
7495
7496    /**
7497     * Called by the {@link android.view.inputmethod.InputMethodManager}
7498     * when a view who is not the current
7499     * input connection target is trying to make a call on the manager.  The
7500     * default implementation returns false; you can override this to return
7501     * true for certain views if you are performing InputConnection proxying
7502     * to them.
7503     * @param view The View that is making the InputMethodManager call.
7504     * @return Return true to allow the call, false to reject.
7505     */
7506    public boolean checkInputConnectionProxy(View view) {
7507        return false;
7508    }
7509
7510    /**
7511     * Show the context menu for this view. It is not safe to hold on to the
7512     * menu after returning from this method.
7513     *
7514     * You should normally not overload this method. Overload
7515     * {@link #onCreateContextMenu(ContextMenu)} or define an
7516     * {@link OnCreateContextMenuListener} to add items to the context menu.
7517     *
7518     * @param menu The context menu to populate
7519     */
7520    public void createContextMenu(ContextMenu menu) {
7521        ContextMenuInfo menuInfo = getContextMenuInfo();
7522
7523        // Sets the current menu info so all items added to menu will have
7524        // my extra info set.
7525        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7526
7527        onCreateContextMenu(menu);
7528        ListenerInfo li = mListenerInfo;
7529        if (li != null && li.mOnCreateContextMenuListener != null) {
7530            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7531        }
7532
7533        // Clear the extra information so subsequent items that aren't mine don't
7534        // have my extra info.
7535        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7536
7537        if (mParent != null) {
7538            mParent.createContextMenu(menu);
7539        }
7540    }
7541
7542    /**
7543     * Views should implement this if they have extra information to associate
7544     * with the context menu. The return result is supplied as a parameter to
7545     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7546     * callback.
7547     *
7548     * @return Extra information about the item for which the context menu
7549     *         should be shown. This information will vary across different
7550     *         subclasses of View.
7551     */
7552    protected ContextMenuInfo getContextMenuInfo() {
7553        return null;
7554    }
7555
7556    /**
7557     * Views should implement this if the view itself is going to add items to
7558     * the context menu.
7559     *
7560     * @param menu the context menu to populate
7561     */
7562    protected void onCreateContextMenu(ContextMenu menu) {
7563    }
7564
7565    /**
7566     * Implement this method to handle trackball motion events.  The
7567     * <em>relative</em> movement of the trackball since the last event
7568     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7569     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7570     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7571     * they will often be fractional values, representing the more fine-grained
7572     * movement information available from a trackball).
7573     *
7574     * @param event The motion event.
7575     * @return True if the event was handled, false otherwise.
7576     */
7577    public boolean onTrackballEvent(MotionEvent event) {
7578        return false;
7579    }
7580
7581    /**
7582     * Implement this method to handle generic motion events.
7583     * <p>
7584     * Generic motion events describe joystick movements, mouse hovers, track pad
7585     * touches, scroll wheel movements and other input events.  The
7586     * {@link MotionEvent#getSource() source} of the motion event specifies
7587     * the class of input that was received.  Implementations of this method
7588     * must examine the bits in the source before processing the event.
7589     * The following code example shows how this is done.
7590     * </p><p>
7591     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7592     * are delivered to the view under the pointer.  All other generic motion events are
7593     * delivered to the focused view.
7594     * </p>
7595     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7596     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7597     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7598     *             // process the joystick movement...
7599     *             return true;
7600     *         }
7601     *     }
7602     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7603     *         switch (event.getAction()) {
7604     *             case MotionEvent.ACTION_HOVER_MOVE:
7605     *                 // process the mouse hover movement...
7606     *                 return true;
7607     *             case MotionEvent.ACTION_SCROLL:
7608     *                 // process the scroll wheel movement...
7609     *                 return true;
7610     *         }
7611     *     }
7612     *     return super.onGenericMotionEvent(event);
7613     * }</pre>
7614     *
7615     * @param event The generic motion event being processed.
7616     * @return True if the event was handled, false otherwise.
7617     */
7618    public boolean onGenericMotionEvent(MotionEvent event) {
7619        return false;
7620    }
7621
7622    /**
7623     * Implement this method to handle hover events.
7624     * <p>
7625     * This method is called whenever a pointer is hovering into, over, or out of the
7626     * bounds of a view and the view is not currently being touched.
7627     * Hover events are represented as pointer events with action
7628     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7629     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7630     * </p>
7631     * <ul>
7632     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7633     * when the pointer enters the bounds of the view.</li>
7634     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7635     * when the pointer has already entered the bounds of the view and has moved.</li>
7636     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7637     * when the pointer has exited the bounds of the view or when the pointer is
7638     * about to go down due to a button click, tap, or similar user action that
7639     * causes the view to be touched.</li>
7640     * </ul>
7641     * <p>
7642     * The view should implement this method to return true to indicate that it is
7643     * handling the hover event, such as by changing its drawable state.
7644     * </p><p>
7645     * The default implementation calls {@link #setHovered} to update the hovered state
7646     * of the view when a hover enter or hover exit event is received, if the view
7647     * is enabled and is clickable.  The default implementation also sends hover
7648     * accessibility events.
7649     * </p>
7650     *
7651     * @param event The motion event that describes the hover.
7652     * @return True if the view handled the hover event.
7653     *
7654     * @see #isHovered
7655     * @see #setHovered
7656     * @see #onHoverChanged
7657     */
7658    public boolean onHoverEvent(MotionEvent event) {
7659        // The root view may receive hover (or touch) events that are outside the bounds of
7660        // the window.  This code ensures that we only send accessibility events for
7661        // hovers that are actually within the bounds of the root view.
7662        final int action = event.getActionMasked();
7663        if (!mSendingHoverAccessibilityEvents) {
7664            if ((action == MotionEvent.ACTION_HOVER_ENTER
7665                    || action == MotionEvent.ACTION_HOVER_MOVE)
7666                    && !hasHoveredChild()
7667                    && pointInView(event.getX(), event.getY())) {
7668                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7669                mSendingHoverAccessibilityEvents = true;
7670                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7671            }
7672        } else {
7673            if (action == MotionEvent.ACTION_HOVER_EXIT
7674                    || (action == MotionEvent.ACTION_MOVE
7675                            && !pointInView(event.getX(), event.getY()))) {
7676                mSendingHoverAccessibilityEvents = false;
7677                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7678                // If the window does not have input focus we take away accessibility
7679                // focus as soon as the user stop hovering over the view.
7680                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7681                    getViewRootImpl().setAccessibilityFocusedHost(null);
7682                }
7683            }
7684        }
7685
7686        if (isHoverable()) {
7687            switch (action) {
7688                case MotionEvent.ACTION_HOVER_ENTER:
7689                    setHovered(true);
7690                    break;
7691                case MotionEvent.ACTION_HOVER_EXIT:
7692                    setHovered(false);
7693                    break;
7694            }
7695
7696            // Dispatch the event to onGenericMotionEvent before returning true.
7697            // This is to provide compatibility with existing applications that
7698            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7699            // break because of the new default handling for hoverable views
7700            // in onHoverEvent.
7701            // Note that onGenericMotionEvent will be called by default when
7702            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7703            dispatchGenericMotionEventInternal(event);
7704            return true;
7705        }
7706
7707        return false;
7708    }
7709
7710    /**
7711     * Returns true if the view should handle {@link #onHoverEvent}
7712     * by calling {@link #setHovered} to change its hovered state.
7713     *
7714     * @return True if the view is hoverable.
7715     */
7716    private boolean isHoverable() {
7717        final int viewFlags = mViewFlags;
7718        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7719            return false;
7720        }
7721
7722        return (viewFlags & CLICKABLE) == CLICKABLE
7723                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7724    }
7725
7726    /**
7727     * Returns true if the view is currently hovered.
7728     *
7729     * @return True if the view is currently hovered.
7730     *
7731     * @see #setHovered
7732     * @see #onHoverChanged
7733     */
7734    @ViewDebug.ExportedProperty
7735    public boolean isHovered() {
7736        return (mPrivateFlags & HOVERED) != 0;
7737    }
7738
7739    /**
7740     * Sets whether the view is currently hovered.
7741     * <p>
7742     * Calling this method also changes the drawable state of the view.  This
7743     * enables the view to react to hover by using different drawable resources
7744     * to change its appearance.
7745     * </p><p>
7746     * The {@link #onHoverChanged} method is called when the hovered state changes.
7747     * </p>
7748     *
7749     * @param hovered True if the view is hovered.
7750     *
7751     * @see #isHovered
7752     * @see #onHoverChanged
7753     */
7754    public void setHovered(boolean hovered) {
7755        if (hovered) {
7756            if ((mPrivateFlags & HOVERED) == 0) {
7757                mPrivateFlags |= HOVERED;
7758                refreshDrawableState();
7759                onHoverChanged(true);
7760            }
7761        } else {
7762            if ((mPrivateFlags & HOVERED) != 0) {
7763                mPrivateFlags &= ~HOVERED;
7764                refreshDrawableState();
7765                onHoverChanged(false);
7766            }
7767        }
7768    }
7769
7770    /**
7771     * Implement this method to handle hover state changes.
7772     * <p>
7773     * This method is called whenever the hover state changes as a result of a
7774     * call to {@link #setHovered}.
7775     * </p>
7776     *
7777     * @param hovered The current hover state, as returned by {@link #isHovered}.
7778     *
7779     * @see #isHovered
7780     * @see #setHovered
7781     */
7782    public void onHoverChanged(boolean hovered) {
7783    }
7784
7785    /**
7786     * Implement this method to handle touch screen motion events.
7787     *
7788     * @param event The motion event.
7789     * @return True if the event was handled, false otherwise.
7790     */
7791    public boolean onTouchEvent(MotionEvent event) {
7792        final int viewFlags = mViewFlags;
7793
7794        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7795            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7796                setPressed(false);
7797            }
7798            // A disabled view that is clickable still consumes the touch
7799            // events, it just doesn't respond to them.
7800            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7801                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7802        }
7803
7804        if (mTouchDelegate != null) {
7805            if (mTouchDelegate.onTouchEvent(event)) {
7806                return true;
7807            }
7808        }
7809
7810        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7811                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7812            switch (event.getAction()) {
7813                case MotionEvent.ACTION_UP:
7814                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7815                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7816                        // take focus if we don't have it already and we should in
7817                        // touch mode.
7818                        boolean focusTaken = false;
7819                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7820                            focusTaken = requestFocus();
7821                        }
7822
7823                        if (prepressed) {
7824                            // The button is being released before we actually
7825                            // showed it as pressed.  Make it show the pressed
7826                            // state now (before scheduling the click) to ensure
7827                            // the user sees it.
7828                            setPressed(true);
7829                       }
7830
7831                        if (!mHasPerformedLongPress) {
7832                            // This is a tap, so remove the longpress check
7833                            removeLongPressCallback();
7834
7835                            // Only perform take click actions if we were in the pressed state
7836                            if (!focusTaken) {
7837                                // Use a Runnable and post this rather than calling
7838                                // performClick directly. This lets other visual state
7839                                // of the view update before click actions start.
7840                                if (mPerformClick == null) {
7841                                    mPerformClick = new PerformClick();
7842                                }
7843                                if (!post(mPerformClick)) {
7844                                    performClick();
7845                                }
7846                            }
7847                        }
7848
7849                        if (mUnsetPressedState == null) {
7850                            mUnsetPressedState = new UnsetPressedState();
7851                        }
7852
7853                        if (prepressed) {
7854                            postDelayed(mUnsetPressedState,
7855                                    ViewConfiguration.getPressedStateDuration());
7856                        } else if (!post(mUnsetPressedState)) {
7857                            // If the post failed, unpress right now
7858                            mUnsetPressedState.run();
7859                        }
7860                        removeTapCallback();
7861                    }
7862                    break;
7863
7864                case MotionEvent.ACTION_DOWN:
7865                    mHasPerformedLongPress = false;
7866
7867                    if (performButtonActionOnTouchDown(event)) {
7868                        break;
7869                    }
7870
7871                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7872                    boolean isInScrollingContainer = isInScrollingContainer();
7873
7874                    // For views inside a scrolling container, delay the pressed feedback for
7875                    // a short period in case this is a scroll.
7876                    if (isInScrollingContainer) {
7877                        mPrivateFlags |= PREPRESSED;
7878                        if (mPendingCheckForTap == null) {
7879                            mPendingCheckForTap = new CheckForTap();
7880                        }
7881                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7882                    } else {
7883                        // Not inside a scrolling container, so show the feedback right away
7884                        setPressed(true);
7885                        checkForLongClick(0);
7886                    }
7887                    break;
7888
7889                case MotionEvent.ACTION_CANCEL:
7890                    setPressed(false);
7891                    removeTapCallback();
7892                    break;
7893
7894                case MotionEvent.ACTION_MOVE:
7895                    final int x = (int) event.getX();
7896                    final int y = (int) event.getY();
7897
7898                    // Be lenient about moving outside of buttons
7899                    if (!pointInView(x, y, mTouchSlop)) {
7900                        // Outside button
7901                        removeTapCallback();
7902                        if ((mPrivateFlags & PRESSED) != 0) {
7903                            // Remove any future long press/tap checks
7904                            removeLongPressCallback();
7905
7906                            setPressed(false);
7907                        }
7908                    }
7909                    break;
7910            }
7911            return true;
7912        }
7913
7914        return false;
7915    }
7916
7917    /**
7918     * @hide
7919     */
7920    public boolean isInScrollingContainer() {
7921        ViewParent p = getParent();
7922        while (p != null && p instanceof ViewGroup) {
7923            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7924                return true;
7925            }
7926            p = p.getParent();
7927        }
7928        return false;
7929    }
7930
7931    /**
7932     * Remove the longpress detection timer.
7933     */
7934    private void removeLongPressCallback() {
7935        if (mPendingCheckForLongPress != null) {
7936          removeCallbacks(mPendingCheckForLongPress);
7937        }
7938    }
7939
7940    /**
7941     * Remove the pending click action
7942     */
7943    private void removePerformClickCallback() {
7944        if (mPerformClick != null) {
7945            removeCallbacks(mPerformClick);
7946        }
7947    }
7948
7949    /**
7950     * Remove the prepress detection timer.
7951     */
7952    private void removeUnsetPressCallback() {
7953        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7954            setPressed(false);
7955            removeCallbacks(mUnsetPressedState);
7956        }
7957    }
7958
7959    /**
7960     * Remove the tap detection timer.
7961     */
7962    private void removeTapCallback() {
7963        if (mPendingCheckForTap != null) {
7964            mPrivateFlags &= ~PREPRESSED;
7965            removeCallbacks(mPendingCheckForTap);
7966        }
7967    }
7968
7969    /**
7970     * Cancels a pending long press.  Your subclass can use this if you
7971     * want the context menu to come up if the user presses and holds
7972     * at the same place, but you don't want it to come up if they press
7973     * and then move around enough to cause scrolling.
7974     */
7975    public void cancelLongPress() {
7976        removeLongPressCallback();
7977
7978        /*
7979         * The prepressed state handled by the tap callback is a display
7980         * construct, but the tap callback will post a long press callback
7981         * less its own timeout. Remove it here.
7982         */
7983        removeTapCallback();
7984    }
7985
7986    /**
7987     * Remove the pending callback for sending a
7988     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7989     */
7990    private void removeSendViewScrolledAccessibilityEventCallback() {
7991        if (mSendViewScrolledAccessibilityEvent != null) {
7992            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7993        }
7994    }
7995
7996    /**
7997     * Sets the TouchDelegate for this View.
7998     */
7999    public void setTouchDelegate(TouchDelegate delegate) {
8000        mTouchDelegate = delegate;
8001    }
8002
8003    /**
8004     * Gets the TouchDelegate for this View.
8005     */
8006    public TouchDelegate getTouchDelegate() {
8007        return mTouchDelegate;
8008    }
8009
8010    /**
8011     * Set flags controlling behavior of this view.
8012     *
8013     * @param flags Constant indicating the value which should be set
8014     * @param mask Constant indicating the bit range that should be changed
8015     */
8016    void setFlags(int flags, int mask) {
8017        int old = mViewFlags;
8018        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8019
8020        int changed = mViewFlags ^ old;
8021        if (changed == 0) {
8022            return;
8023        }
8024        int privateFlags = mPrivateFlags;
8025
8026        /* Check if the FOCUSABLE bit has changed */
8027        if (((changed & FOCUSABLE_MASK) != 0) &&
8028                ((privateFlags & HAS_BOUNDS) !=0)) {
8029            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8030                    && ((privateFlags & FOCUSED) != 0)) {
8031                /* Give up focus if we are no longer focusable */
8032                clearFocus();
8033            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8034                    && ((privateFlags & FOCUSED) == 0)) {
8035                /*
8036                 * Tell the view system that we are now available to take focus
8037                 * if no one else already has it.
8038                 */
8039                if (mParent != null) mParent.focusableViewAvailable(this);
8040            }
8041            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8042                notifyAccessibilityStateChanged();
8043            }
8044        }
8045
8046        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8047            if ((changed & VISIBILITY_MASK) != 0) {
8048                /*
8049                 * If this view is becoming visible, invalidate it in case it changed while
8050                 * it was not visible. Marking it drawn ensures that the invalidation will
8051                 * go through.
8052                 */
8053                mPrivateFlags |= DRAWN;
8054                invalidate(true);
8055
8056                needGlobalAttributesUpdate(true);
8057
8058                // a view becoming visible is worth notifying the parent
8059                // about in case nothing has focus.  even if this specific view
8060                // isn't focusable, it may contain something that is, so let
8061                // the root view try to give this focus if nothing else does.
8062                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8063                    mParent.focusableViewAvailable(this);
8064                }
8065            }
8066        }
8067
8068        /* Check if the GONE bit has changed */
8069        if ((changed & GONE) != 0) {
8070            needGlobalAttributesUpdate(false);
8071            requestLayout();
8072
8073            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8074                if (hasFocus()) clearFocus();
8075                clearAccessibilityFocus();
8076                destroyDrawingCache();
8077                if (mParent instanceof View) {
8078                    // GONE views noop invalidation, so invalidate the parent
8079                    ((View) mParent).invalidate(true);
8080                }
8081                // Mark the view drawn to ensure that it gets invalidated properly the next
8082                // time it is visible and gets invalidated
8083                mPrivateFlags |= DRAWN;
8084            }
8085            if (mAttachInfo != null) {
8086                mAttachInfo.mViewVisibilityChanged = true;
8087            }
8088        }
8089
8090        /* Check if the VISIBLE bit has changed */
8091        if ((changed & INVISIBLE) != 0) {
8092            needGlobalAttributesUpdate(false);
8093            /*
8094             * If this view is becoming invisible, set the DRAWN flag so that
8095             * the next invalidate() will not be skipped.
8096             */
8097            mPrivateFlags |= DRAWN;
8098
8099            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8100                // root view becoming invisible shouldn't clear focus and accessibility focus
8101                if (getRootView() != this) {
8102                    clearFocus();
8103                    clearAccessibilityFocus();
8104                }
8105            }
8106            if (mAttachInfo != null) {
8107                mAttachInfo.mViewVisibilityChanged = true;
8108            }
8109        }
8110
8111        if ((changed & VISIBILITY_MASK) != 0) {
8112            if (mParent instanceof ViewGroup) {
8113                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8114                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8115                ((View) mParent).invalidate(true);
8116            } else if (mParent != null) {
8117                mParent.invalidateChild(this, null);
8118            }
8119            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8120        }
8121
8122        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8123            destroyDrawingCache();
8124        }
8125
8126        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8127            destroyDrawingCache();
8128            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8129            invalidateParentCaches();
8130        }
8131
8132        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8133            destroyDrawingCache();
8134            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8135        }
8136
8137        if ((changed & DRAW_MASK) != 0) {
8138            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8139                if (mBackground != null) {
8140                    mPrivateFlags &= ~SKIP_DRAW;
8141                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8142                } else {
8143                    mPrivateFlags |= SKIP_DRAW;
8144                }
8145            } else {
8146                mPrivateFlags &= ~SKIP_DRAW;
8147            }
8148            requestLayout();
8149            invalidate(true);
8150        }
8151
8152        if ((changed & KEEP_SCREEN_ON) != 0) {
8153            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8154                mParent.recomputeViewAttributes(this);
8155            }
8156        }
8157
8158        if (AccessibilityManager.getInstance(mContext).isEnabled()
8159                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8160                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8161            notifyAccessibilityStateChanged();
8162        }
8163    }
8164
8165    /**
8166     * Change the view's z order in the tree, so it's on top of other sibling
8167     * views
8168     */
8169    public void bringToFront() {
8170        if (mParent != null) {
8171            mParent.bringChildToFront(this);
8172        }
8173    }
8174
8175    /**
8176     * This is called in response to an internal scroll in this view (i.e., the
8177     * view scrolled its own contents). This is typically as a result of
8178     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8179     * called.
8180     *
8181     * @param l Current horizontal scroll origin.
8182     * @param t Current vertical scroll origin.
8183     * @param oldl Previous horizontal scroll origin.
8184     * @param oldt Previous vertical scroll origin.
8185     */
8186    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8187        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8188            postSendViewScrolledAccessibilityEventCallback();
8189        }
8190
8191        mBackgroundSizeChanged = true;
8192
8193        final AttachInfo ai = mAttachInfo;
8194        if (ai != null) {
8195            ai.mViewScrollChanged = true;
8196        }
8197    }
8198
8199    /**
8200     * Interface definition for a callback to be invoked when the layout bounds of a view
8201     * changes due to layout processing.
8202     */
8203    public interface OnLayoutChangeListener {
8204        /**
8205         * Called when the focus state of a view has changed.
8206         *
8207         * @param v The view whose state has changed.
8208         * @param left The new value of the view's left property.
8209         * @param top The new value of the view's top property.
8210         * @param right The new value of the view's right property.
8211         * @param bottom The new value of the view's bottom property.
8212         * @param oldLeft The previous value of the view's left property.
8213         * @param oldTop The previous value of the view's top property.
8214         * @param oldRight The previous value of the view's right property.
8215         * @param oldBottom The previous value of the view's bottom property.
8216         */
8217        void onLayoutChange(View v, int left, int top, int right, int bottom,
8218            int oldLeft, int oldTop, int oldRight, int oldBottom);
8219    }
8220
8221    /**
8222     * This is called during layout when the size of this view has changed. If
8223     * you were just added to the view hierarchy, you're called with the old
8224     * values of 0.
8225     *
8226     * @param w Current width of this view.
8227     * @param h Current height of this view.
8228     * @param oldw Old width of this view.
8229     * @param oldh Old height of this view.
8230     */
8231    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8232    }
8233
8234    /**
8235     * Called by draw to draw the child views. This may be overridden
8236     * by derived classes to gain control just before its children are drawn
8237     * (but after its own view has been drawn).
8238     * @param canvas the canvas on which to draw the view
8239     */
8240    protected void dispatchDraw(Canvas canvas) {
8241
8242    }
8243
8244    /**
8245     * Gets the parent of this view. Note that the parent is a
8246     * ViewParent and not necessarily a View.
8247     *
8248     * @return Parent of this view.
8249     */
8250    public final ViewParent getParent() {
8251        return mParent;
8252    }
8253
8254    /**
8255     * Set the horizontal scrolled position of your view. This will cause a call to
8256     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8257     * invalidated.
8258     * @param value the x position to scroll to
8259     */
8260    public void setScrollX(int value) {
8261        scrollTo(value, mScrollY);
8262    }
8263
8264    /**
8265     * Set the vertical scrolled position of your view. This will cause a call to
8266     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8267     * invalidated.
8268     * @param value the y position to scroll to
8269     */
8270    public void setScrollY(int value) {
8271        scrollTo(mScrollX, value);
8272    }
8273
8274    /**
8275     * Return the scrolled left position of this view. This is the left edge of
8276     * the displayed part of your view. You do not need to draw any pixels
8277     * farther left, since those are outside of the frame of your view on
8278     * screen.
8279     *
8280     * @return The left edge of the displayed part of your view, in pixels.
8281     */
8282    public final int getScrollX() {
8283        return mScrollX;
8284    }
8285
8286    /**
8287     * Return the scrolled top position of this view. This is the top edge of
8288     * the displayed part of your view. You do not need to draw any pixels above
8289     * it, since those are outside of the frame of your view on screen.
8290     *
8291     * @return The top edge of the displayed part of your view, in pixels.
8292     */
8293    public final int getScrollY() {
8294        return mScrollY;
8295    }
8296
8297    /**
8298     * Return the width of the your view.
8299     *
8300     * @return The width of your view, in pixels.
8301     */
8302    @ViewDebug.ExportedProperty(category = "layout")
8303    public final int getWidth() {
8304        return mRight - mLeft;
8305    }
8306
8307    /**
8308     * Return the height of your view.
8309     *
8310     * @return The height of your view, in pixels.
8311     */
8312    @ViewDebug.ExportedProperty(category = "layout")
8313    public final int getHeight() {
8314        return mBottom - mTop;
8315    }
8316
8317    /**
8318     * Return the visible drawing bounds of your view. Fills in the output
8319     * rectangle with the values from getScrollX(), getScrollY(),
8320     * getWidth(), and getHeight().
8321     *
8322     * @param outRect The (scrolled) drawing bounds of the view.
8323     */
8324    public void getDrawingRect(Rect outRect) {
8325        outRect.left = mScrollX;
8326        outRect.top = mScrollY;
8327        outRect.right = mScrollX + (mRight - mLeft);
8328        outRect.bottom = mScrollY + (mBottom - mTop);
8329    }
8330
8331    /**
8332     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8333     * raw width component (that is the result is masked by
8334     * {@link #MEASURED_SIZE_MASK}).
8335     *
8336     * @return The raw measured width of this view.
8337     */
8338    public final int getMeasuredWidth() {
8339        return mMeasuredWidth & MEASURED_SIZE_MASK;
8340    }
8341
8342    /**
8343     * Return the full width measurement information for this view as computed
8344     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8345     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8346     * This should be used during measurement and layout calculations only. Use
8347     * {@link #getWidth()} to see how wide a view is after layout.
8348     *
8349     * @return The measured width of this view as a bit mask.
8350     */
8351    public final int getMeasuredWidthAndState() {
8352        return mMeasuredWidth;
8353    }
8354
8355    /**
8356     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8357     * raw width component (that is the result is masked by
8358     * {@link #MEASURED_SIZE_MASK}).
8359     *
8360     * @return The raw measured height of this view.
8361     */
8362    public final int getMeasuredHeight() {
8363        return mMeasuredHeight & MEASURED_SIZE_MASK;
8364    }
8365
8366    /**
8367     * Return the full height measurement information for this view as computed
8368     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8369     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8370     * This should be used during measurement and layout calculations only. Use
8371     * {@link #getHeight()} to see how wide a view is after layout.
8372     *
8373     * @return The measured width of this view as a bit mask.
8374     */
8375    public final int getMeasuredHeightAndState() {
8376        return mMeasuredHeight;
8377    }
8378
8379    /**
8380     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8381     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8382     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8383     * and the height component is at the shifted bits
8384     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8385     */
8386    public final int getMeasuredState() {
8387        return (mMeasuredWidth&MEASURED_STATE_MASK)
8388                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8389                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8390    }
8391
8392    /**
8393     * The transform matrix of this view, which is calculated based on the current
8394     * roation, scale, and pivot properties.
8395     *
8396     * @see #getRotation()
8397     * @see #getScaleX()
8398     * @see #getScaleY()
8399     * @see #getPivotX()
8400     * @see #getPivotY()
8401     * @return The current transform matrix for the view
8402     */
8403    public Matrix getMatrix() {
8404        if (mTransformationInfo != null) {
8405            updateMatrix();
8406            return mTransformationInfo.mMatrix;
8407        }
8408        return Matrix.IDENTITY_MATRIX;
8409    }
8410
8411    /**
8412     * Utility function to determine if the value is far enough away from zero to be
8413     * considered non-zero.
8414     * @param value A floating point value to check for zero-ness
8415     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8416     */
8417    private static boolean nonzero(float value) {
8418        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8419    }
8420
8421    /**
8422     * Returns true if the transform matrix is the identity matrix.
8423     * Recomputes the matrix if necessary.
8424     *
8425     * @return True if the transform matrix is the identity matrix, false otherwise.
8426     */
8427    final boolean hasIdentityMatrix() {
8428        if (mTransformationInfo != null) {
8429            updateMatrix();
8430            return mTransformationInfo.mMatrixIsIdentity;
8431        }
8432        return true;
8433    }
8434
8435    void ensureTransformationInfo() {
8436        if (mTransformationInfo == null) {
8437            mTransformationInfo = new TransformationInfo();
8438        }
8439    }
8440
8441    /**
8442     * Recomputes the transform matrix if necessary.
8443     */
8444    private void updateMatrix() {
8445        final TransformationInfo info = mTransformationInfo;
8446        if (info == null) {
8447            return;
8448        }
8449        if (info.mMatrixDirty) {
8450            // transform-related properties have changed since the last time someone
8451            // asked for the matrix; recalculate it with the current values
8452
8453            // Figure out if we need to update the pivot point
8454            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8455                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8456                    info.mPrevWidth = mRight - mLeft;
8457                    info.mPrevHeight = mBottom - mTop;
8458                    info.mPivotX = info.mPrevWidth / 2f;
8459                    info.mPivotY = info.mPrevHeight / 2f;
8460                }
8461            }
8462            info.mMatrix.reset();
8463            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8464                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8465                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8466                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8467            } else {
8468                if (info.mCamera == null) {
8469                    info.mCamera = new Camera();
8470                    info.matrix3D = new Matrix();
8471                }
8472                info.mCamera.save();
8473                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8474                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8475                info.mCamera.getMatrix(info.matrix3D);
8476                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8477                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8478                        info.mPivotY + info.mTranslationY);
8479                info.mMatrix.postConcat(info.matrix3D);
8480                info.mCamera.restore();
8481            }
8482            info.mMatrixDirty = false;
8483            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8484            info.mInverseMatrixDirty = true;
8485        }
8486    }
8487
8488    /**
8489     * Utility method to retrieve the inverse of the current mMatrix property.
8490     * We cache the matrix to avoid recalculating it when transform properties
8491     * have not changed.
8492     *
8493     * @return The inverse of the current matrix of this view.
8494     */
8495    final Matrix getInverseMatrix() {
8496        final TransformationInfo info = mTransformationInfo;
8497        if (info != null) {
8498            updateMatrix();
8499            if (info.mInverseMatrixDirty) {
8500                if (info.mInverseMatrix == null) {
8501                    info.mInverseMatrix = new Matrix();
8502                }
8503                info.mMatrix.invert(info.mInverseMatrix);
8504                info.mInverseMatrixDirty = false;
8505            }
8506            return info.mInverseMatrix;
8507        }
8508        return Matrix.IDENTITY_MATRIX;
8509    }
8510
8511    /**
8512     * Gets the distance along the Z axis from the camera to this view.
8513     *
8514     * @see #setCameraDistance(float)
8515     *
8516     * @return The distance along the Z axis.
8517     */
8518    public float getCameraDistance() {
8519        ensureTransformationInfo();
8520        final float dpi = mResources.getDisplayMetrics().densityDpi;
8521        final TransformationInfo info = mTransformationInfo;
8522        if (info.mCamera == null) {
8523            info.mCamera = new Camera();
8524            info.matrix3D = new Matrix();
8525        }
8526        return -(info.mCamera.getLocationZ() * dpi);
8527    }
8528
8529    /**
8530     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8531     * views are drawn) from the camera to this view. The camera's distance
8532     * affects 3D transformations, for instance rotations around the X and Y
8533     * axis. If the rotationX or rotationY properties are changed and this view is
8534     * large (more than half the size of the screen), it is recommended to always
8535     * use a camera distance that's greater than the height (X axis rotation) or
8536     * the width (Y axis rotation) of this view.</p>
8537     *
8538     * <p>The distance of the camera from the view plane can have an affect on the
8539     * perspective distortion of the view when it is rotated around the x or y axis.
8540     * For example, a large distance will result in a large viewing angle, and there
8541     * will not be much perspective distortion of the view as it rotates. A short
8542     * distance may cause much more perspective distortion upon rotation, and can
8543     * also result in some drawing artifacts if the rotated view ends up partially
8544     * behind the camera (which is why the recommendation is to use a distance at
8545     * least as far as the size of the view, if the view is to be rotated.)</p>
8546     *
8547     * <p>The distance is expressed in "depth pixels." The default distance depends
8548     * on the screen density. For instance, on a medium density display, the
8549     * default distance is 1280. On a high density display, the default distance
8550     * is 1920.</p>
8551     *
8552     * <p>If you want to specify a distance that leads to visually consistent
8553     * results across various densities, use the following formula:</p>
8554     * <pre>
8555     * float scale = context.getResources().getDisplayMetrics().density;
8556     * view.setCameraDistance(distance * scale);
8557     * </pre>
8558     *
8559     * <p>The density scale factor of a high density display is 1.5,
8560     * and 1920 = 1280 * 1.5.</p>
8561     *
8562     * @param distance The distance in "depth pixels", if negative the opposite
8563     *        value is used
8564     *
8565     * @see #setRotationX(float)
8566     * @see #setRotationY(float)
8567     */
8568    public void setCameraDistance(float distance) {
8569        invalidateViewProperty(true, false);
8570
8571        ensureTransformationInfo();
8572        final float dpi = mResources.getDisplayMetrics().densityDpi;
8573        final TransformationInfo info = mTransformationInfo;
8574        if (info.mCamera == null) {
8575            info.mCamera = new Camera();
8576            info.matrix3D = new Matrix();
8577        }
8578
8579        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8580        info.mMatrixDirty = true;
8581
8582        invalidateViewProperty(false, false);
8583        if (mDisplayList != null) {
8584            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8585        }
8586        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8587            // View was rejected last time it was drawn by its parent; this may have changed
8588            invalidateParentIfNeeded();
8589        }
8590    }
8591
8592    /**
8593     * The degrees that the view is rotated around the pivot point.
8594     *
8595     * @see #setRotation(float)
8596     * @see #getPivotX()
8597     * @see #getPivotY()
8598     *
8599     * @return The degrees of rotation.
8600     */
8601    @ViewDebug.ExportedProperty(category = "drawing")
8602    public float getRotation() {
8603        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8604    }
8605
8606    /**
8607     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8608     * result in clockwise rotation.
8609     *
8610     * @param rotation The degrees of rotation.
8611     *
8612     * @see #getRotation()
8613     * @see #getPivotX()
8614     * @see #getPivotY()
8615     * @see #setRotationX(float)
8616     * @see #setRotationY(float)
8617     *
8618     * @attr ref android.R.styleable#View_rotation
8619     */
8620    public void setRotation(float rotation) {
8621        ensureTransformationInfo();
8622        final TransformationInfo info = mTransformationInfo;
8623        if (info.mRotation != rotation) {
8624            // Double-invalidation is necessary to capture view's old and new areas
8625            invalidateViewProperty(true, false);
8626            info.mRotation = rotation;
8627            info.mMatrixDirty = true;
8628            invalidateViewProperty(false, true);
8629            if (mDisplayList != null) {
8630                mDisplayList.setRotation(rotation);
8631            }
8632            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8633                // View was rejected last time it was drawn by its parent; this may have changed
8634                invalidateParentIfNeeded();
8635            }
8636        }
8637    }
8638
8639    /**
8640     * The degrees that the view is rotated around the vertical axis through the pivot point.
8641     *
8642     * @see #getPivotX()
8643     * @see #getPivotY()
8644     * @see #setRotationY(float)
8645     *
8646     * @return The degrees of Y rotation.
8647     */
8648    @ViewDebug.ExportedProperty(category = "drawing")
8649    public float getRotationY() {
8650        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8651    }
8652
8653    /**
8654     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8655     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8656     * down the y axis.
8657     *
8658     * When rotating large views, it is recommended to adjust the camera distance
8659     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8660     *
8661     * @param rotationY The degrees of Y rotation.
8662     *
8663     * @see #getRotationY()
8664     * @see #getPivotX()
8665     * @see #getPivotY()
8666     * @see #setRotation(float)
8667     * @see #setRotationX(float)
8668     * @see #setCameraDistance(float)
8669     *
8670     * @attr ref android.R.styleable#View_rotationY
8671     */
8672    public void setRotationY(float rotationY) {
8673        ensureTransformationInfo();
8674        final TransformationInfo info = mTransformationInfo;
8675        if (info.mRotationY != rotationY) {
8676            invalidateViewProperty(true, false);
8677            info.mRotationY = rotationY;
8678            info.mMatrixDirty = true;
8679            invalidateViewProperty(false, true);
8680            if (mDisplayList != null) {
8681                mDisplayList.setRotationY(rotationY);
8682            }
8683            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8684                // View was rejected last time it was drawn by its parent; this may have changed
8685                invalidateParentIfNeeded();
8686            }
8687        }
8688    }
8689
8690    /**
8691     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8692     *
8693     * @see #getPivotX()
8694     * @see #getPivotY()
8695     * @see #setRotationX(float)
8696     *
8697     * @return The degrees of X rotation.
8698     */
8699    @ViewDebug.ExportedProperty(category = "drawing")
8700    public float getRotationX() {
8701        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8702    }
8703
8704    /**
8705     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8706     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8707     * x axis.
8708     *
8709     * When rotating large views, it is recommended to adjust the camera distance
8710     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8711     *
8712     * @param rotationX The degrees of X rotation.
8713     *
8714     * @see #getRotationX()
8715     * @see #getPivotX()
8716     * @see #getPivotY()
8717     * @see #setRotation(float)
8718     * @see #setRotationY(float)
8719     * @see #setCameraDistance(float)
8720     *
8721     * @attr ref android.R.styleable#View_rotationX
8722     */
8723    public void setRotationX(float rotationX) {
8724        ensureTransformationInfo();
8725        final TransformationInfo info = mTransformationInfo;
8726        if (info.mRotationX != rotationX) {
8727            invalidateViewProperty(true, false);
8728            info.mRotationX = rotationX;
8729            info.mMatrixDirty = true;
8730            invalidateViewProperty(false, true);
8731            if (mDisplayList != null) {
8732                mDisplayList.setRotationX(rotationX);
8733            }
8734            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8735                // View was rejected last time it was drawn by its parent; this may have changed
8736                invalidateParentIfNeeded();
8737            }
8738        }
8739    }
8740
8741    /**
8742     * The amount that the view is scaled in x around the pivot point, as a proportion of
8743     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8744     *
8745     * <p>By default, this is 1.0f.
8746     *
8747     * @see #getPivotX()
8748     * @see #getPivotY()
8749     * @return The scaling factor.
8750     */
8751    @ViewDebug.ExportedProperty(category = "drawing")
8752    public float getScaleX() {
8753        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8754    }
8755
8756    /**
8757     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8758     * the view's unscaled width. A value of 1 means that no scaling is applied.
8759     *
8760     * @param scaleX The scaling factor.
8761     * @see #getPivotX()
8762     * @see #getPivotY()
8763     *
8764     * @attr ref android.R.styleable#View_scaleX
8765     */
8766    public void setScaleX(float scaleX) {
8767        ensureTransformationInfo();
8768        final TransformationInfo info = mTransformationInfo;
8769        if (info.mScaleX != scaleX) {
8770            invalidateViewProperty(true, false);
8771            info.mScaleX = scaleX;
8772            info.mMatrixDirty = true;
8773            invalidateViewProperty(false, true);
8774            if (mDisplayList != null) {
8775                mDisplayList.setScaleX(scaleX);
8776            }
8777            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8778                // View was rejected last time it was drawn by its parent; this may have changed
8779                invalidateParentIfNeeded();
8780            }
8781        }
8782    }
8783
8784    /**
8785     * The amount that the view is scaled in y around the pivot point, as a proportion of
8786     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8787     *
8788     * <p>By default, this is 1.0f.
8789     *
8790     * @see #getPivotX()
8791     * @see #getPivotY()
8792     * @return The scaling factor.
8793     */
8794    @ViewDebug.ExportedProperty(category = "drawing")
8795    public float getScaleY() {
8796        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8797    }
8798
8799    /**
8800     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8801     * the view's unscaled width. A value of 1 means that no scaling is applied.
8802     *
8803     * @param scaleY The scaling factor.
8804     * @see #getPivotX()
8805     * @see #getPivotY()
8806     *
8807     * @attr ref android.R.styleable#View_scaleY
8808     */
8809    public void setScaleY(float scaleY) {
8810        ensureTransformationInfo();
8811        final TransformationInfo info = mTransformationInfo;
8812        if (info.mScaleY != scaleY) {
8813            invalidateViewProperty(true, false);
8814            info.mScaleY = scaleY;
8815            info.mMatrixDirty = true;
8816            invalidateViewProperty(false, true);
8817            if (mDisplayList != null) {
8818                mDisplayList.setScaleY(scaleY);
8819            }
8820            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8821                // View was rejected last time it was drawn by its parent; this may have changed
8822                invalidateParentIfNeeded();
8823            }
8824        }
8825    }
8826
8827    /**
8828     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8829     * and {@link #setScaleX(float) scaled}.
8830     *
8831     * @see #getRotation()
8832     * @see #getScaleX()
8833     * @see #getScaleY()
8834     * @see #getPivotY()
8835     * @return The x location of the pivot point.
8836     *
8837     * @attr ref android.R.styleable#View_transformPivotX
8838     */
8839    @ViewDebug.ExportedProperty(category = "drawing")
8840    public float getPivotX() {
8841        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8842    }
8843
8844    /**
8845     * Sets the x location of the point around which the view is
8846     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8847     * By default, the pivot point is centered on the object.
8848     * Setting this property disables this behavior and causes the view to use only the
8849     * explicitly set pivotX and pivotY values.
8850     *
8851     * @param pivotX The x location of the pivot point.
8852     * @see #getRotation()
8853     * @see #getScaleX()
8854     * @see #getScaleY()
8855     * @see #getPivotY()
8856     *
8857     * @attr ref android.R.styleable#View_transformPivotX
8858     */
8859    public void setPivotX(float pivotX) {
8860        ensureTransformationInfo();
8861        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8862        final TransformationInfo info = mTransformationInfo;
8863        if (info.mPivotX != pivotX) {
8864            invalidateViewProperty(true, false);
8865            info.mPivotX = pivotX;
8866            info.mMatrixDirty = true;
8867            invalidateViewProperty(false, true);
8868            if (mDisplayList != null) {
8869                mDisplayList.setPivotX(pivotX);
8870            }
8871            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8872                // View was rejected last time it was drawn by its parent; this may have changed
8873                invalidateParentIfNeeded();
8874            }
8875        }
8876    }
8877
8878    /**
8879     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8880     * and {@link #setScaleY(float) scaled}.
8881     *
8882     * @see #getRotation()
8883     * @see #getScaleX()
8884     * @see #getScaleY()
8885     * @see #getPivotY()
8886     * @return The y location of the pivot point.
8887     *
8888     * @attr ref android.R.styleable#View_transformPivotY
8889     */
8890    @ViewDebug.ExportedProperty(category = "drawing")
8891    public float getPivotY() {
8892        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8893    }
8894
8895    /**
8896     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8897     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8898     * Setting this property disables this behavior and causes the view to use only the
8899     * explicitly set pivotX and pivotY values.
8900     *
8901     * @param pivotY The y location of the pivot point.
8902     * @see #getRotation()
8903     * @see #getScaleX()
8904     * @see #getScaleY()
8905     * @see #getPivotY()
8906     *
8907     * @attr ref android.R.styleable#View_transformPivotY
8908     */
8909    public void setPivotY(float pivotY) {
8910        ensureTransformationInfo();
8911        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8912        final TransformationInfo info = mTransformationInfo;
8913        if (info.mPivotY != pivotY) {
8914            invalidateViewProperty(true, false);
8915            info.mPivotY = pivotY;
8916            info.mMatrixDirty = true;
8917            invalidateViewProperty(false, true);
8918            if (mDisplayList != null) {
8919                mDisplayList.setPivotY(pivotY);
8920            }
8921            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8922                // View was rejected last time it was drawn by its parent; this may have changed
8923                invalidateParentIfNeeded();
8924            }
8925        }
8926    }
8927
8928    /**
8929     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8930     * completely transparent and 1 means the view is completely opaque.
8931     *
8932     * <p>By default this is 1.0f.
8933     * @return The opacity of the view.
8934     */
8935    @ViewDebug.ExportedProperty(category = "drawing")
8936    public float getAlpha() {
8937        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8938    }
8939
8940    /**
8941     * Returns whether this View has content which overlaps. This function, intended to be
8942     * overridden by specific View types, is an optimization when alpha is set on a view. If
8943     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8944     * and then composited it into place, which can be expensive. If the view has no overlapping
8945     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8946     * An example of overlapping rendering is a TextView with a background image, such as a
8947     * Button. An example of non-overlapping rendering is a TextView with no background, or
8948     * an ImageView with only the foreground image. The default implementation returns true;
8949     * subclasses should override if they have cases which can be optimized.
8950     *
8951     * @return true if the content in this view might overlap, false otherwise.
8952     */
8953    public boolean hasOverlappingRendering() {
8954        return true;
8955    }
8956
8957    /**
8958     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8959     * completely transparent and 1 means the view is completely opaque.</p>
8960     *
8961     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8962     * responsible for applying the opacity itself. Otherwise, calling this method is
8963     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8964     * setting a hardware layer.</p>
8965     *
8966     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8967     * performance implications. It is generally best to use the alpha property sparingly and
8968     * transiently, as in the case of fading animations.</p>
8969     *
8970     * @param alpha The opacity of the view.
8971     *
8972     * @see #setLayerType(int, android.graphics.Paint)
8973     *
8974     * @attr ref android.R.styleable#View_alpha
8975     */
8976    public void setAlpha(float alpha) {
8977        ensureTransformationInfo();
8978        if (mTransformationInfo.mAlpha != alpha) {
8979            mTransformationInfo.mAlpha = alpha;
8980            if (onSetAlpha((int) (alpha * 255))) {
8981                mPrivateFlags |= ALPHA_SET;
8982                // subclass is handling alpha - don't optimize rendering cache invalidation
8983                invalidateParentCaches();
8984                invalidate(true);
8985            } else {
8986                mPrivateFlags &= ~ALPHA_SET;
8987                invalidateViewProperty(true, false);
8988                if (mDisplayList != null) {
8989                    mDisplayList.setAlpha(alpha);
8990                }
8991            }
8992        }
8993    }
8994
8995    /**
8996     * Faster version of setAlpha() which performs the same steps except there are
8997     * no calls to invalidate(). The caller of this function should perform proper invalidation
8998     * on the parent and this object. The return value indicates whether the subclass handles
8999     * alpha (the return value for onSetAlpha()).
9000     *
9001     * @param alpha The new value for the alpha property
9002     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9003     *         the new value for the alpha property is different from the old value
9004     */
9005    boolean setAlphaNoInvalidation(float alpha) {
9006        ensureTransformationInfo();
9007        if (mTransformationInfo.mAlpha != alpha) {
9008            mTransformationInfo.mAlpha = alpha;
9009            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9010            if (subclassHandlesAlpha) {
9011                mPrivateFlags |= ALPHA_SET;
9012                return true;
9013            } else {
9014                mPrivateFlags &= ~ALPHA_SET;
9015                if (mDisplayList != null) {
9016                    mDisplayList.setAlpha(alpha);
9017                }
9018            }
9019        }
9020        return false;
9021    }
9022
9023    /**
9024     * Top position of this view relative to its parent.
9025     *
9026     * @return The top of this view, in pixels.
9027     */
9028    @ViewDebug.CapturedViewProperty
9029    public final int getTop() {
9030        return mTop;
9031    }
9032
9033    /**
9034     * Sets the top position of this view relative to its parent. This method is meant to be called
9035     * by the layout system and should not generally be called otherwise, because the property
9036     * may be changed at any time by the layout.
9037     *
9038     * @param top The top of this view, in pixels.
9039     */
9040    public final void setTop(int top) {
9041        if (top != mTop) {
9042            updateMatrix();
9043            final boolean matrixIsIdentity = mTransformationInfo == null
9044                    || mTransformationInfo.mMatrixIsIdentity;
9045            if (matrixIsIdentity) {
9046                if (mAttachInfo != null) {
9047                    int minTop;
9048                    int yLoc;
9049                    if (top < mTop) {
9050                        minTop = top;
9051                        yLoc = top - mTop;
9052                    } else {
9053                        minTop = mTop;
9054                        yLoc = 0;
9055                    }
9056                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9057                }
9058            } else {
9059                // Double-invalidation is necessary to capture view's old and new areas
9060                invalidate(true);
9061            }
9062
9063            int width = mRight - mLeft;
9064            int oldHeight = mBottom - mTop;
9065
9066            mTop = top;
9067            if (mDisplayList != null) {
9068                mDisplayList.setTop(mTop);
9069            }
9070
9071            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9072
9073            if (!matrixIsIdentity) {
9074                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9075                    // A change in dimension means an auto-centered pivot point changes, too
9076                    mTransformationInfo.mMatrixDirty = true;
9077                }
9078                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9079                invalidate(true);
9080            }
9081            mBackgroundSizeChanged = true;
9082            invalidateParentIfNeeded();
9083            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9084                // View was rejected last time it was drawn by its parent; this may have changed
9085                invalidateParentIfNeeded();
9086            }
9087        }
9088    }
9089
9090    /**
9091     * Bottom position of this view relative to its parent.
9092     *
9093     * @return The bottom of this view, in pixels.
9094     */
9095    @ViewDebug.CapturedViewProperty
9096    public final int getBottom() {
9097        return mBottom;
9098    }
9099
9100    /**
9101     * True if this view has changed since the last time being drawn.
9102     *
9103     * @return The dirty state of this view.
9104     */
9105    public boolean isDirty() {
9106        return (mPrivateFlags & DIRTY_MASK) != 0;
9107    }
9108
9109    /**
9110     * Sets the bottom position of this view relative to its parent. This method is meant to be
9111     * called by the layout system and should not generally be called otherwise, because the
9112     * property may be changed at any time by the layout.
9113     *
9114     * @param bottom The bottom of this view, in pixels.
9115     */
9116    public final void setBottom(int bottom) {
9117        if (bottom != mBottom) {
9118            updateMatrix();
9119            final boolean matrixIsIdentity = mTransformationInfo == null
9120                    || mTransformationInfo.mMatrixIsIdentity;
9121            if (matrixIsIdentity) {
9122                if (mAttachInfo != null) {
9123                    int maxBottom;
9124                    if (bottom < mBottom) {
9125                        maxBottom = mBottom;
9126                    } else {
9127                        maxBottom = bottom;
9128                    }
9129                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9130                }
9131            } else {
9132                // Double-invalidation is necessary to capture view's old and new areas
9133                invalidate(true);
9134            }
9135
9136            int width = mRight - mLeft;
9137            int oldHeight = mBottom - mTop;
9138
9139            mBottom = bottom;
9140            if (mDisplayList != null) {
9141                mDisplayList.setBottom(mBottom);
9142            }
9143
9144            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9145
9146            if (!matrixIsIdentity) {
9147                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9148                    // A change in dimension means an auto-centered pivot point changes, too
9149                    mTransformationInfo.mMatrixDirty = true;
9150                }
9151                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9152                invalidate(true);
9153            }
9154            mBackgroundSizeChanged = true;
9155            invalidateParentIfNeeded();
9156            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9157                // View was rejected last time it was drawn by its parent; this may have changed
9158                invalidateParentIfNeeded();
9159            }
9160        }
9161    }
9162
9163    /**
9164     * Left position of this view relative to its parent.
9165     *
9166     * @return The left edge of this view, in pixels.
9167     */
9168    @ViewDebug.CapturedViewProperty
9169    public final int getLeft() {
9170        return mLeft;
9171    }
9172
9173    /**
9174     * Sets the left position of this view relative to its parent. This method is meant to be called
9175     * by the layout system and should not generally be called otherwise, because the property
9176     * may be changed at any time by the layout.
9177     *
9178     * @param left The bottom of this view, in pixels.
9179     */
9180    public final void setLeft(int left) {
9181        if (left != mLeft) {
9182            updateMatrix();
9183            final boolean matrixIsIdentity = mTransformationInfo == null
9184                    || mTransformationInfo.mMatrixIsIdentity;
9185            if (matrixIsIdentity) {
9186                if (mAttachInfo != null) {
9187                    int minLeft;
9188                    int xLoc;
9189                    if (left < mLeft) {
9190                        minLeft = left;
9191                        xLoc = left - mLeft;
9192                    } else {
9193                        minLeft = mLeft;
9194                        xLoc = 0;
9195                    }
9196                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9197                }
9198            } else {
9199                // Double-invalidation is necessary to capture view's old and new areas
9200                invalidate(true);
9201            }
9202
9203            int oldWidth = mRight - mLeft;
9204            int height = mBottom - mTop;
9205
9206            mLeft = left;
9207            if (mDisplayList != null) {
9208                mDisplayList.setLeft(left);
9209            }
9210
9211            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9212
9213            if (!matrixIsIdentity) {
9214                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9215                    // A change in dimension means an auto-centered pivot point changes, too
9216                    mTransformationInfo.mMatrixDirty = true;
9217                }
9218                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9219                invalidate(true);
9220            }
9221            mBackgroundSizeChanged = true;
9222            invalidateParentIfNeeded();
9223            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9224                // View was rejected last time it was drawn by its parent; this may have changed
9225                invalidateParentIfNeeded();
9226            }
9227        }
9228    }
9229
9230    /**
9231     * Right position of this view relative to its parent.
9232     *
9233     * @return The right edge of this view, in pixels.
9234     */
9235    @ViewDebug.CapturedViewProperty
9236    public final int getRight() {
9237        return mRight;
9238    }
9239
9240    /**
9241     * Sets the right position of this view relative to its parent. This method is meant to be called
9242     * by the layout system and should not generally be called otherwise, because the property
9243     * may be changed at any time by the layout.
9244     *
9245     * @param right The bottom of this view, in pixels.
9246     */
9247    public final void setRight(int right) {
9248        if (right != mRight) {
9249            updateMatrix();
9250            final boolean matrixIsIdentity = mTransformationInfo == null
9251                    || mTransformationInfo.mMatrixIsIdentity;
9252            if (matrixIsIdentity) {
9253                if (mAttachInfo != null) {
9254                    int maxRight;
9255                    if (right < mRight) {
9256                        maxRight = mRight;
9257                    } else {
9258                        maxRight = right;
9259                    }
9260                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9261                }
9262            } else {
9263                // Double-invalidation is necessary to capture view's old and new areas
9264                invalidate(true);
9265            }
9266
9267            int oldWidth = mRight - mLeft;
9268            int height = mBottom - mTop;
9269
9270            mRight = right;
9271            if (mDisplayList != null) {
9272                mDisplayList.setRight(mRight);
9273            }
9274
9275            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9276
9277            if (!matrixIsIdentity) {
9278                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9279                    // A change in dimension means an auto-centered pivot point changes, too
9280                    mTransformationInfo.mMatrixDirty = true;
9281                }
9282                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9283                invalidate(true);
9284            }
9285            mBackgroundSizeChanged = true;
9286            invalidateParentIfNeeded();
9287            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9288                // View was rejected last time it was drawn by its parent; this may have changed
9289                invalidateParentIfNeeded();
9290            }
9291        }
9292    }
9293
9294    /**
9295     * The visual x position of this view, in pixels. This is equivalent to the
9296     * {@link #setTranslationX(float) translationX} property plus the current
9297     * {@link #getLeft() left} property.
9298     *
9299     * @return The visual x position of this view, in pixels.
9300     */
9301    @ViewDebug.ExportedProperty(category = "drawing")
9302    public float getX() {
9303        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9304    }
9305
9306    /**
9307     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9308     * {@link #setTranslationX(float) translationX} property to be the difference between
9309     * the x value passed in and the current {@link #getLeft() left} property.
9310     *
9311     * @param x The visual x position of this view, in pixels.
9312     */
9313    public void setX(float x) {
9314        setTranslationX(x - mLeft);
9315    }
9316
9317    /**
9318     * The visual y position of this view, in pixels. This is equivalent to the
9319     * {@link #setTranslationY(float) translationY} property plus the current
9320     * {@link #getTop() top} property.
9321     *
9322     * @return The visual y position of this view, in pixels.
9323     */
9324    @ViewDebug.ExportedProperty(category = "drawing")
9325    public float getY() {
9326        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9327    }
9328
9329    /**
9330     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9331     * {@link #setTranslationY(float) translationY} property to be the difference between
9332     * the y value passed in and the current {@link #getTop() top} property.
9333     *
9334     * @param y The visual y position of this view, in pixels.
9335     */
9336    public void setY(float y) {
9337        setTranslationY(y - mTop);
9338    }
9339
9340
9341    /**
9342     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9343     * This position is post-layout, in addition to wherever the object's
9344     * layout placed it.
9345     *
9346     * @return The horizontal position of this view relative to its left position, in pixels.
9347     */
9348    @ViewDebug.ExportedProperty(category = "drawing")
9349    public float getTranslationX() {
9350        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9351    }
9352
9353    /**
9354     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9355     * This effectively positions the object post-layout, in addition to wherever the object's
9356     * layout placed it.
9357     *
9358     * @param translationX The horizontal position of this view relative to its left position,
9359     * in pixels.
9360     *
9361     * @attr ref android.R.styleable#View_translationX
9362     */
9363    public void setTranslationX(float translationX) {
9364        ensureTransformationInfo();
9365        final TransformationInfo info = mTransformationInfo;
9366        if (info.mTranslationX != translationX) {
9367            // Double-invalidation is necessary to capture view's old and new areas
9368            invalidateViewProperty(true, false);
9369            info.mTranslationX = translationX;
9370            info.mMatrixDirty = true;
9371            invalidateViewProperty(false, true);
9372            if (mDisplayList != null) {
9373                mDisplayList.setTranslationX(translationX);
9374            }
9375            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9376                // View was rejected last time it was drawn by its parent; this may have changed
9377                invalidateParentIfNeeded();
9378            }
9379        }
9380    }
9381
9382    /**
9383     * The horizontal location of this view relative to its {@link #getTop() top} position.
9384     * This position is post-layout, in addition to wherever the object's
9385     * layout placed it.
9386     *
9387     * @return The vertical position of this view relative to its top position,
9388     * in pixels.
9389     */
9390    @ViewDebug.ExportedProperty(category = "drawing")
9391    public float getTranslationY() {
9392        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9393    }
9394
9395    /**
9396     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9397     * This effectively positions the object post-layout, in addition to wherever the object's
9398     * layout placed it.
9399     *
9400     * @param translationY The vertical position of this view relative to its top position,
9401     * in pixels.
9402     *
9403     * @attr ref android.R.styleable#View_translationY
9404     */
9405    public void setTranslationY(float translationY) {
9406        ensureTransformationInfo();
9407        final TransformationInfo info = mTransformationInfo;
9408        if (info.mTranslationY != translationY) {
9409            invalidateViewProperty(true, false);
9410            info.mTranslationY = translationY;
9411            info.mMatrixDirty = true;
9412            invalidateViewProperty(false, true);
9413            if (mDisplayList != null) {
9414                mDisplayList.setTranslationY(translationY);
9415            }
9416            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9417                // View was rejected last time it was drawn by its parent; this may have changed
9418                invalidateParentIfNeeded();
9419            }
9420        }
9421    }
9422
9423    /**
9424     * Hit rectangle in parent's coordinates
9425     *
9426     * @param outRect The hit rectangle of the view.
9427     */
9428    public void getHitRect(Rect outRect) {
9429        updateMatrix();
9430        final TransformationInfo info = mTransformationInfo;
9431        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9432            outRect.set(mLeft, mTop, mRight, mBottom);
9433        } else {
9434            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9435            tmpRect.set(-info.mPivotX, -info.mPivotY,
9436                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9437            info.mMatrix.mapRect(tmpRect);
9438            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9439                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9440        }
9441    }
9442
9443    /**
9444     * Determines whether the given point, in local coordinates is inside the view.
9445     */
9446    /*package*/ final boolean pointInView(float localX, float localY) {
9447        return localX >= 0 && localX < (mRight - mLeft)
9448                && localY >= 0 && localY < (mBottom - mTop);
9449    }
9450
9451    /**
9452     * Utility method to determine whether the given point, in local coordinates,
9453     * is inside the view, where the area of the view is expanded by the slop factor.
9454     * This method is called while processing touch-move events to determine if the event
9455     * is still within the view.
9456     */
9457    private boolean pointInView(float localX, float localY, float slop) {
9458        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9459                localY < ((mBottom - mTop) + slop);
9460    }
9461
9462    /**
9463     * When a view has focus and the user navigates away from it, the next view is searched for
9464     * starting from the rectangle filled in by this method.
9465     *
9466     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9467     * of the view.  However, if your view maintains some idea of internal selection,
9468     * such as a cursor, or a selected row or column, you should override this method and
9469     * fill in a more specific rectangle.
9470     *
9471     * @param r The rectangle to fill in, in this view's coordinates.
9472     */
9473    public void getFocusedRect(Rect r) {
9474        getDrawingRect(r);
9475    }
9476
9477    /**
9478     * If some part of this view is not clipped by any of its parents, then
9479     * return that area in r in global (root) coordinates. To convert r to local
9480     * coordinates (without taking possible View rotations into account), offset
9481     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9482     * If the view is completely clipped or translated out, return false.
9483     *
9484     * @param r If true is returned, r holds the global coordinates of the
9485     *        visible portion of this view.
9486     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9487     *        between this view and its root. globalOffet may be null.
9488     * @return true if r is non-empty (i.e. part of the view is visible at the
9489     *         root level.
9490     */
9491    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9492        int width = mRight - mLeft;
9493        int height = mBottom - mTop;
9494        if (width > 0 && height > 0) {
9495            r.set(0, 0, width, height);
9496            if (globalOffset != null) {
9497                globalOffset.set(-mScrollX, -mScrollY);
9498            }
9499            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9500        }
9501        return false;
9502    }
9503
9504    public final boolean getGlobalVisibleRect(Rect r) {
9505        return getGlobalVisibleRect(r, null);
9506    }
9507
9508    public final boolean getLocalVisibleRect(Rect r) {
9509        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9510        if (getGlobalVisibleRect(r, offset)) {
9511            r.offset(-offset.x, -offset.y); // make r local
9512            return true;
9513        }
9514        return false;
9515    }
9516
9517    /**
9518     * Offset this view's vertical location by the specified number of pixels.
9519     *
9520     * @param offset the number of pixels to offset the view by
9521     */
9522    public void offsetTopAndBottom(int offset) {
9523        if (offset != 0) {
9524            updateMatrix();
9525            final boolean matrixIsIdentity = mTransformationInfo == null
9526                    || mTransformationInfo.mMatrixIsIdentity;
9527            if (matrixIsIdentity) {
9528                if (mDisplayList != null) {
9529                    invalidateViewProperty(false, false);
9530                } else {
9531                    final ViewParent p = mParent;
9532                    if (p != null && mAttachInfo != null) {
9533                        final Rect r = mAttachInfo.mTmpInvalRect;
9534                        int minTop;
9535                        int maxBottom;
9536                        int yLoc;
9537                        if (offset < 0) {
9538                            minTop = mTop + offset;
9539                            maxBottom = mBottom;
9540                            yLoc = offset;
9541                        } else {
9542                            minTop = mTop;
9543                            maxBottom = mBottom + offset;
9544                            yLoc = 0;
9545                        }
9546                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9547                        p.invalidateChild(this, r);
9548                    }
9549                }
9550            } else {
9551                invalidateViewProperty(false, false);
9552            }
9553
9554            mTop += offset;
9555            mBottom += offset;
9556            if (mDisplayList != null) {
9557                mDisplayList.offsetTopBottom(offset);
9558                invalidateViewProperty(false, false);
9559            } else {
9560                if (!matrixIsIdentity) {
9561                    invalidateViewProperty(false, true);
9562                }
9563                invalidateParentIfNeeded();
9564            }
9565        }
9566    }
9567
9568    /**
9569     * Offset this view's horizontal location by the specified amount of pixels.
9570     *
9571     * @param offset the numer of pixels to offset the view by
9572     */
9573    public void offsetLeftAndRight(int offset) {
9574        if (offset != 0) {
9575            updateMatrix();
9576            final boolean matrixIsIdentity = mTransformationInfo == null
9577                    || mTransformationInfo.mMatrixIsIdentity;
9578            if (matrixIsIdentity) {
9579                if (mDisplayList != null) {
9580                    invalidateViewProperty(false, false);
9581                } else {
9582                    final ViewParent p = mParent;
9583                    if (p != null && mAttachInfo != null) {
9584                        final Rect r = mAttachInfo.mTmpInvalRect;
9585                        int minLeft;
9586                        int maxRight;
9587                        if (offset < 0) {
9588                            minLeft = mLeft + offset;
9589                            maxRight = mRight;
9590                        } else {
9591                            minLeft = mLeft;
9592                            maxRight = mRight + offset;
9593                        }
9594                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9595                        p.invalidateChild(this, r);
9596                    }
9597                }
9598            } else {
9599                invalidateViewProperty(false, false);
9600            }
9601
9602            mLeft += offset;
9603            mRight += offset;
9604            if (mDisplayList != null) {
9605                mDisplayList.offsetLeftRight(offset);
9606                invalidateViewProperty(false, false);
9607            } else {
9608                if (!matrixIsIdentity) {
9609                    invalidateViewProperty(false, true);
9610                }
9611                invalidateParentIfNeeded();
9612            }
9613        }
9614    }
9615
9616    /**
9617     * Get the LayoutParams associated with this view. All views should have
9618     * layout parameters. These supply parameters to the <i>parent</i> of this
9619     * view specifying how it should be arranged. There are many subclasses of
9620     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9621     * of ViewGroup that are responsible for arranging their children.
9622     *
9623     * This method may return null if this View is not attached to a parent
9624     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9625     * was not invoked successfully. When a View is attached to a parent
9626     * ViewGroup, this method must not return null.
9627     *
9628     * @return The LayoutParams associated with this view, or null if no
9629     *         parameters have been set yet
9630     */
9631    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9632    public ViewGroup.LayoutParams getLayoutParams() {
9633        return mLayoutParams;
9634    }
9635
9636    /**
9637     * Set the layout parameters associated with this view. These supply
9638     * parameters to the <i>parent</i> of this view specifying how it should be
9639     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9640     * correspond to the different subclasses of ViewGroup that are responsible
9641     * for arranging their children.
9642     *
9643     * @param params The layout parameters for this view, cannot be null
9644     */
9645    public void setLayoutParams(ViewGroup.LayoutParams params) {
9646        if (params == null) {
9647            throw new NullPointerException("Layout parameters cannot be null");
9648        }
9649        mLayoutParams = params;
9650        if (mParent instanceof ViewGroup) {
9651            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9652        }
9653        requestLayout();
9654    }
9655
9656    /**
9657     * Set the scrolled position of your view. This will cause a call to
9658     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9659     * invalidated.
9660     * @param x the x position to scroll to
9661     * @param y the y position to scroll to
9662     */
9663    public void scrollTo(int x, int y) {
9664        if (mScrollX != x || mScrollY != y) {
9665            int oldX = mScrollX;
9666            int oldY = mScrollY;
9667            mScrollX = x;
9668            mScrollY = y;
9669            invalidateParentCaches();
9670            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9671            if (!awakenScrollBars()) {
9672                postInvalidateOnAnimation();
9673            }
9674        }
9675    }
9676
9677    /**
9678     * Move the scrolled position of your view. This will cause a call to
9679     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9680     * invalidated.
9681     * @param x the amount of pixels to scroll by horizontally
9682     * @param y the amount of pixels to scroll by vertically
9683     */
9684    public void scrollBy(int x, int y) {
9685        scrollTo(mScrollX + x, mScrollY + y);
9686    }
9687
9688    /**
9689     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9690     * animation to fade the scrollbars out after a default delay. If a subclass
9691     * provides animated scrolling, the start delay should equal the duration
9692     * of the scrolling animation.</p>
9693     *
9694     * <p>The animation starts only if at least one of the scrollbars is
9695     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9696     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9697     * this method returns true, and false otherwise. If the animation is
9698     * started, this method calls {@link #invalidate()}; in that case the
9699     * caller should not call {@link #invalidate()}.</p>
9700     *
9701     * <p>This method should be invoked every time a subclass directly updates
9702     * the scroll parameters.</p>
9703     *
9704     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9705     * and {@link #scrollTo(int, int)}.</p>
9706     *
9707     * @return true if the animation is played, false otherwise
9708     *
9709     * @see #awakenScrollBars(int)
9710     * @see #scrollBy(int, int)
9711     * @see #scrollTo(int, int)
9712     * @see #isHorizontalScrollBarEnabled()
9713     * @see #isVerticalScrollBarEnabled()
9714     * @see #setHorizontalScrollBarEnabled(boolean)
9715     * @see #setVerticalScrollBarEnabled(boolean)
9716     */
9717    protected boolean awakenScrollBars() {
9718        return mScrollCache != null &&
9719                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9720    }
9721
9722    /**
9723     * Trigger the scrollbars to draw.
9724     * This method differs from awakenScrollBars() only in its default duration.
9725     * initialAwakenScrollBars() will show the scroll bars for longer than
9726     * usual to give the user more of a chance to notice them.
9727     *
9728     * @return true if the animation is played, false otherwise.
9729     */
9730    private boolean initialAwakenScrollBars() {
9731        return mScrollCache != null &&
9732                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9733    }
9734
9735    /**
9736     * <p>
9737     * Trigger the scrollbars to draw. When invoked this method starts an
9738     * animation to fade the scrollbars out after a fixed delay. If a subclass
9739     * provides animated scrolling, the start delay should equal the duration of
9740     * the scrolling animation.
9741     * </p>
9742     *
9743     * <p>
9744     * The animation starts only if at least one of the scrollbars is enabled,
9745     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9746     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9747     * this method returns true, and false otherwise. If the animation is
9748     * started, this method calls {@link #invalidate()}; in that case the caller
9749     * should not call {@link #invalidate()}.
9750     * </p>
9751     *
9752     * <p>
9753     * This method should be invoked everytime a subclass directly updates the
9754     * scroll parameters.
9755     * </p>
9756     *
9757     * @param startDelay the delay, in milliseconds, after which the animation
9758     *        should start; when the delay is 0, the animation starts
9759     *        immediately
9760     * @return true if the animation is played, false otherwise
9761     *
9762     * @see #scrollBy(int, int)
9763     * @see #scrollTo(int, int)
9764     * @see #isHorizontalScrollBarEnabled()
9765     * @see #isVerticalScrollBarEnabled()
9766     * @see #setHorizontalScrollBarEnabled(boolean)
9767     * @see #setVerticalScrollBarEnabled(boolean)
9768     */
9769    protected boolean awakenScrollBars(int startDelay) {
9770        return awakenScrollBars(startDelay, true);
9771    }
9772
9773    /**
9774     * <p>
9775     * Trigger the scrollbars to draw. When invoked this method starts an
9776     * animation to fade the scrollbars out after a fixed delay. If a subclass
9777     * provides animated scrolling, the start delay should equal the duration of
9778     * the scrolling animation.
9779     * </p>
9780     *
9781     * <p>
9782     * The animation starts only if at least one of the scrollbars is enabled,
9783     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9784     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9785     * this method returns true, and false otherwise. If the animation is
9786     * started, this method calls {@link #invalidate()} if the invalidate parameter
9787     * is set to true; in that case the caller
9788     * should not call {@link #invalidate()}.
9789     * </p>
9790     *
9791     * <p>
9792     * This method should be invoked everytime a subclass directly updates the
9793     * scroll parameters.
9794     * </p>
9795     *
9796     * @param startDelay the delay, in milliseconds, after which the animation
9797     *        should start; when the delay is 0, the animation starts
9798     *        immediately
9799     *
9800     * @param invalidate Wheter this method should call invalidate
9801     *
9802     * @return true if the animation is played, false otherwise
9803     *
9804     * @see #scrollBy(int, int)
9805     * @see #scrollTo(int, int)
9806     * @see #isHorizontalScrollBarEnabled()
9807     * @see #isVerticalScrollBarEnabled()
9808     * @see #setHorizontalScrollBarEnabled(boolean)
9809     * @see #setVerticalScrollBarEnabled(boolean)
9810     */
9811    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9812        final ScrollabilityCache scrollCache = mScrollCache;
9813
9814        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9815            return false;
9816        }
9817
9818        if (scrollCache.scrollBar == null) {
9819            scrollCache.scrollBar = new ScrollBarDrawable();
9820        }
9821
9822        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9823
9824            if (invalidate) {
9825                // Invalidate to show the scrollbars
9826                postInvalidateOnAnimation();
9827            }
9828
9829            if (scrollCache.state == ScrollabilityCache.OFF) {
9830                // FIXME: this is copied from WindowManagerService.
9831                // We should get this value from the system when it
9832                // is possible to do so.
9833                final int KEY_REPEAT_FIRST_DELAY = 750;
9834                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9835            }
9836
9837            // Tell mScrollCache when we should start fading. This may
9838            // extend the fade start time if one was already scheduled
9839            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9840            scrollCache.fadeStartTime = fadeStartTime;
9841            scrollCache.state = ScrollabilityCache.ON;
9842
9843            // Schedule our fader to run, unscheduling any old ones first
9844            if (mAttachInfo != null) {
9845                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9846                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9847            }
9848
9849            return true;
9850        }
9851
9852        return false;
9853    }
9854
9855    /**
9856     * Do not invalidate views which are not visible and which are not running an animation. They
9857     * will not get drawn and they should not set dirty flags as if they will be drawn
9858     */
9859    private boolean skipInvalidate() {
9860        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9861                (!(mParent instanceof ViewGroup) ||
9862                        !((ViewGroup) mParent).isViewTransitioning(this));
9863    }
9864    /**
9865     * Mark the area defined by dirty as needing to be drawn. If the view is
9866     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9867     * in the future. This must be called from a UI thread. To call from a non-UI
9868     * thread, call {@link #postInvalidate()}.
9869     *
9870     * WARNING: This method is destructive to dirty.
9871     * @param dirty the rectangle representing the bounds of the dirty region
9872     */
9873    public void invalidate(Rect dirty) {
9874        if (ViewDebug.TRACE_HIERARCHY) {
9875            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9876        }
9877
9878        if (skipInvalidate()) {
9879            return;
9880        }
9881        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9882                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9883                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9884            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9885            mPrivateFlags |= INVALIDATED;
9886            mPrivateFlags |= DIRTY;
9887            final ViewParent p = mParent;
9888            final AttachInfo ai = mAttachInfo;
9889            //noinspection PointlessBooleanExpression,ConstantConditions
9890            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9891                if (p != null && ai != null && ai.mHardwareAccelerated) {
9892                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9893                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9894                    p.invalidateChild(this, null);
9895                    return;
9896                }
9897            }
9898            if (p != null && ai != null) {
9899                final int scrollX = mScrollX;
9900                final int scrollY = mScrollY;
9901                final Rect r = ai.mTmpInvalRect;
9902                r.set(dirty.left - scrollX, dirty.top - scrollY,
9903                        dirty.right - scrollX, dirty.bottom - scrollY);
9904                mParent.invalidateChild(this, r);
9905            }
9906        }
9907    }
9908
9909    /**
9910     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9911     * The coordinates of the dirty rect are relative to the view.
9912     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9913     * will be called at some point in the future. This must be called from
9914     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9915     * @param l the left position of the dirty region
9916     * @param t the top position of the dirty region
9917     * @param r the right position of the dirty region
9918     * @param b the bottom position of the dirty region
9919     */
9920    public void invalidate(int l, int t, int r, int b) {
9921        if (ViewDebug.TRACE_HIERARCHY) {
9922            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9923        }
9924
9925        if (skipInvalidate()) {
9926            return;
9927        }
9928        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9929                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9930                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9931            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9932            mPrivateFlags |= INVALIDATED;
9933            mPrivateFlags |= DIRTY;
9934            final ViewParent p = mParent;
9935            final AttachInfo ai = mAttachInfo;
9936            //noinspection PointlessBooleanExpression,ConstantConditions
9937            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9938                if (p != null && ai != null && ai.mHardwareAccelerated) {
9939                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9940                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9941                    p.invalidateChild(this, null);
9942                    return;
9943                }
9944            }
9945            if (p != null && ai != null && l < r && t < b) {
9946                final int scrollX = mScrollX;
9947                final int scrollY = mScrollY;
9948                final Rect tmpr = ai.mTmpInvalRect;
9949                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9950                p.invalidateChild(this, tmpr);
9951            }
9952        }
9953    }
9954
9955    /**
9956     * Invalidate the whole view. If the view is visible,
9957     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9958     * the future. This must be called from a UI thread. To call from a non-UI thread,
9959     * call {@link #postInvalidate()}.
9960     */
9961    public void invalidate() {
9962        invalidate(true);
9963    }
9964
9965    /**
9966     * This is where the invalidate() work actually happens. A full invalidate()
9967     * causes the drawing cache to be invalidated, but this function can be called with
9968     * invalidateCache set to false to skip that invalidation step for cases that do not
9969     * need it (for example, a component that remains at the same dimensions with the same
9970     * content).
9971     *
9972     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9973     * well. This is usually true for a full invalidate, but may be set to false if the
9974     * View's contents or dimensions have not changed.
9975     */
9976    void invalidate(boolean invalidateCache) {
9977        if (ViewDebug.TRACE_HIERARCHY) {
9978            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9979        }
9980
9981        if (skipInvalidate()) {
9982            return;
9983        }
9984        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9985                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9986                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9987            mLastIsOpaque = isOpaque();
9988            mPrivateFlags &= ~DRAWN;
9989            mPrivateFlags |= DIRTY;
9990            if (invalidateCache) {
9991                mPrivateFlags |= INVALIDATED;
9992                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9993            }
9994            final AttachInfo ai = mAttachInfo;
9995            final ViewParent p = mParent;
9996            //noinspection PointlessBooleanExpression,ConstantConditions
9997            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9998                if (p != null && ai != null && ai.mHardwareAccelerated) {
9999                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10000                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10001                    p.invalidateChild(this, null);
10002                    return;
10003                }
10004            }
10005
10006            if (p != null && ai != null) {
10007                final Rect r = ai.mTmpInvalRect;
10008                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10009                // Don't call invalidate -- we don't want to internally scroll
10010                // our own bounds
10011                p.invalidateChild(this, r);
10012            }
10013        }
10014    }
10015
10016    /**
10017     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10018     * set any flags or handle all of the cases handled by the default invalidation methods.
10019     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10020     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10021     * walk up the hierarchy, transforming the dirty rect as necessary.
10022     *
10023     * The method also handles normal invalidation logic if display list properties are not
10024     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10025     * backup approach, to handle these cases used in the various property-setting methods.
10026     *
10027     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10028     * are not being used in this view
10029     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10030     * list properties are not being used in this view
10031     */
10032    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10033        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10034            if (invalidateParent) {
10035                invalidateParentCaches();
10036            }
10037            if (forceRedraw) {
10038                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10039            }
10040            invalidate(false);
10041        } else {
10042            final AttachInfo ai = mAttachInfo;
10043            final ViewParent p = mParent;
10044            if (p != null && ai != null) {
10045                final Rect r = ai.mTmpInvalRect;
10046                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10047                if (mParent instanceof ViewGroup) {
10048                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10049                } else {
10050                    mParent.invalidateChild(this, r);
10051                }
10052            }
10053        }
10054    }
10055
10056    /**
10057     * Utility method to transform a given Rect by the current matrix of this view.
10058     */
10059    void transformRect(final Rect rect) {
10060        if (!getMatrix().isIdentity()) {
10061            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10062            boundingRect.set(rect);
10063            getMatrix().mapRect(boundingRect);
10064            rect.set((int) (boundingRect.left - 0.5f),
10065                    (int) (boundingRect.top - 0.5f),
10066                    (int) (boundingRect.right + 0.5f),
10067                    (int) (boundingRect.bottom + 0.5f));
10068        }
10069    }
10070
10071    /**
10072     * Used to indicate that the parent of this view should clear its caches. This functionality
10073     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10074     * which is necessary when various parent-managed properties of the view change, such as
10075     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10076     * clears the parent caches and does not causes an invalidate event.
10077     *
10078     * @hide
10079     */
10080    protected void invalidateParentCaches() {
10081        if (mParent instanceof View) {
10082            ((View) mParent).mPrivateFlags |= INVALIDATED;
10083        }
10084    }
10085
10086    /**
10087     * Used to indicate that the parent of this view should be invalidated. This functionality
10088     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10089     * which is necessary when various parent-managed properties of the view change, such as
10090     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10091     * an invalidation event to the parent.
10092     *
10093     * @hide
10094     */
10095    protected void invalidateParentIfNeeded() {
10096        if (isHardwareAccelerated() && mParent instanceof View) {
10097            ((View) mParent).invalidate(true);
10098        }
10099    }
10100
10101    /**
10102     * Indicates whether this View is opaque. An opaque View guarantees that it will
10103     * draw all the pixels overlapping its bounds using a fully opaque color.
10104     *
10105     * Subclasses of View should override this method whenever possible to indicate
10106     * whether an instance is opaque. Opaque Views are treated in a special way by
10107     * the View hierarchy, possibly allowing it to perform optimizations during
10108     * invalidate/draw passes.
10109     *
10110     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10111     */
10112    @ViewDebug.ExportedProperty(category = "drawing")
10113    public boolean isOpaque() {
10114        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10115                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10116                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10117    }
10118
10119    /**
10120     * @hide
10121     */
10122    protected void computeOpaqueFlags() {
10123        // Opaque if:
10124        //   - Has a background
10125        //   - Background is opaque
10126        //   - Doesn't have scrollbars or scrollbars are inside overlay
10127
10128        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10129            mPrivateFlags |= OPAQUE_BACKGROUND;
10130        } else {
10131            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10132        }
10133
10134        final int flags = mViewFlags;
10135        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10136                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10137            mPrivateFlags |= OPAQUE_SCROLLBARS;
10138        } else {
10139            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10140        }
10141    }
10142
10143    /**
10144     * @hide
10145     */
10146    protected boolean hasOpaqueScrollbars() {
10147        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10148    }
10149
10150    /**
10151     * @return A handler associated with the thread running the View. This
10152     * handler can be used to pump events in the UI events queue.
10153     */
10154    public Handler getHandler() {
10155        if (mAttachInfo != null) {
10156            return mAttachInfo.mHandler;
10157        }
10158        return null;
10159    }
10160
10161    /**
10162     * Gets the view root associated with the View.
10163     * @return The view root, or null if none.
10164     * @hide
10165     */
10166    public ViewRootImpl getViewRootImpl() {
10167        if (mAttachInfo != null) {
10168            return mAttachInfo.mViewRootImpl;
10169        }
10170        return null;
10171    }
10172
10173    /**
10174     * <p>Causes the Runnable to be added to the message queue.
10175     * The runnable will be run on the user interface thread.</p>
10176     *
10177     * <p>This method can be invoked from outside of the UI thread
10178     * only when this View is attached to a window.</p>
10179     *
10180     * @param action The Runnable that will be executed.
10181     *
10182     * @return Returns true if the Runnable was successfully placed in to the
10183     *         message queue.  Returns false on failure, usually because the
10184     *         looper processing the message queue is exiting.
10185     *
10186     * @see #postDelayed
10187     * @see #removeCallbacks
10188     */
10189    public boolean post(Runnable action) {
10190        final AttachInfo attachInfo = mAttachInfo;
10191        if (attachInfo != null) {
10192            return attachInfo.mHandler.post(action);
10193        }
10194        // Assume that post will succeed later
10195        ViewRootImpl.getRunQueue().post(action);
10196        return true;
10197    }
10198
10199    /**
10200     * <p>Causes the Runnable to be added to the message queue, to be run
10201     * after the specified amount of time elapses.
10202     * The runnable will be run on the user interface thread.</p>
10203     *
10204     * <p>This method can be invoked from outside of the UI thread
10205     * only when this View is attached to a window.</p>
10206     *
10207     * @param action The Runnable that will be executed.
10208     * @param delayMillis The delay (in milliseconds) until the Runnable
10209     *        will be executed.
10210     *
10211     * @return true if the Runnable was successfully placed in to the
10212     *         message queue.  Returns false on failure, usually because the
10213     *         looper processing the message queue is exiting.  Note that a
10214     *         result of true does not mean the Runnable will be processed --
10215     *         if the looper is quit before the delivery time of the message
10216     *         occurs then the message will be dropped.
10217     *
10218     * @see #post
10219     * @see #removeCallbacks
10220     */
10221    public boolean postDelayed(Runnable action, long delayMillis) {
10222        final AttachInfo attachInfo = mAttachInfo;
10223        if (attachInfo != null) {
10224            return attachInfo.mHandler.postDelayed(action, delayMillis);
10225        }
10226        // Assume that post will succeed later
10227        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10228        return true;
10229    }
10230
10231    /**
10232     * <p>Causes the Runnable to execute on the next animation time step.
10233     * The runnable will be run on the user interface thread.</p>
10234     *
10235     * <p>This method can be invoked from outside of the UI thread
10236     * only when this View is attached to a window.</p>
10237     *
10238     * @param action The Runnable that will be executed.
10239     *
10240     * @see #postOnAnimationDelayed
10241     * @see #removeCallbacks
10242     */
10243    public void postOnAnimation(Runnable action) {
10244        final AttachInfo attachInfo = mAttachInfo;
10245        if (attachInfo != null) {
10246            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10247                    Choreographer.CALLBACK_ANIMATION, action, null);
10248        } else {
10249            // Assume that post will succeed later
10250            ViewRootImpl.getRunQueue().post(action);
10251        }
10252    }
10253
10254    /**
10255     * <p>Causes the Runnable to execute on the next animation time step,
10256     * after the specified amount of time elapses.
10257     * The runnable will be run on the user interface thread.</p>
10258     *
10259     * <p>This method can be invoked from outside of the UI thread
10260     * only when this View is attached to a window.</p>
10261     *
10262     * @param action The Runnable that will be executed.
10263     * @param delayMillis The delay (in milliseconds) until the Runnable
10264     *        will be executed.
10265     *
10266     * @see #postOnAnimation
10267     * @see #removeCallbacks
10268     */
10269    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10270        final AttachInfo attachInfo = mAttachInfo;
10271        if (attachInfo != null) {
10272            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10273                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10274        } else {
10275            // Assume that post will succeed later
10276            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10277        }
10278    }
10279
10280    /**
10281     * <p>Removes the specified Runnable from the message queue.</p>
10282     *
10283     * <p>This method can be invoked from outside of the UI thread
10284     * only when this View is attached to a window.</p>
10285     *
10286     * @param action The Runnable to remove from the message handling queue
10287     *
10288     * @return true if this view could ask the Handler to remove the Runnable,
10289     *         false otherwise. When the returned value is true, the Runnable
10290     *         may or may not have been actually removed from the message queue
10291     *         (for instance, if the Runnable was not in the queue already.)
10292     *
10293     * @see #post
10294     * @see #postDelayed
10295     * @see #postOnAnimation
10296     * @see #postOnAnimationDelayed
10297     */
10298    public boolean removeCallbacks(Runnable action) {
10299        if (action != null) {
10300            final AttachInfo attachInfo = mAttachInfo;
10301            if (attachInfo != null) {
10302                attachInfo.mHandler.removeCallbacks(action);
10303                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10304                        Choreographer.CALLBACK_ANIMATION, action, null);
10305            } else {
10306                // Assume that post will succeed later
10307                ViewRootImpl.getRunQueue().removeCallbacks(action);
10308            }
10309        }
10310        return true;
10311    }
10312
10313    /**
10314     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10315     * Use this to invalidate the View from a non-UI thread.</p>
10316     *
10317     * <p>This method can be invoked from outside of the UI thread
10318     * only when this View is attached to a window.</p>
10319     *
10320     * @see #invalidate()
10321     * @see #postInvalidateDelayed(long)
10322     */
10323    public void postInvalidate() {
10324        postInvalidateDelayed(0);
10325    }
10326
10327    /**
10328     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10329     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10330     *
10331     * <p>This method can be invoked from outside of the UI thread
10332     * only when this View is attached to a window.</p>
10333     *
10334     * @param left The left coordinate of the rectangle to invalidate.
10335     * @param top The top coordinate of the rectangle to invalidate.
10336     * @param right The right coordinate of the rectangle to invalidate.
10337     * @param bottom The bottom coordinate of the rectangle to invalidate.
10338     *
10339     * @see #invalidate(int, int, int, int)
10340     * @see #invalidate(Rect)
10341     * @see #postInvalidateDelayed(long, int, int, int, int)
10342     */
10343    public void postInvalidate(int left, int top, int right, int bottom) {
10344        postInvalidateDelayed(0, left, top, right, bottom);
10345    }
10346
10347    /**
10348     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10349     * loop. Waits for the specified amount of time.</p>
10350     *
10351     * <p>This method can be invoked from outside of the UI thread
10352     * only when this View is attached to a window.</p>
10353     *
10354     * @param delayMilliseconds the duration in milliseconds to delay the
10355     *         invalidation by
10356     *
10357     * @see #invalidate()
10358     * @see #postInvalidate()
10359     */
10360    public void postInvalidateDelayed(long delayMilliseconds) {
10361        // We try only with the AttachInfo because there's no point in invalidating
10362        // if we are not attached to our window
10363        final AttachInfo attachInfo = mAttachInfo;
10364        if (attachInfo != null) {
10365            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10366        }
10367    }
10368
10369    /**
10370     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10371     * through the event loop. Waits for the specified amount of time.</p>
10372     *
10373     * <p>This method can be invoked from outside of the UI thread
10374     * only when this View is attached to a window.</p>
10375     *
10376     * @param delayMilliseconds the duration in milliseconds to delay the
10377     *         invalidation by
10378     * @param left The left coordinate of the rectangle to invalidate.
10379     * @param top The top coordinate of the rectangle to invalidate.
10380     * @param right The right coordinate of the rectangle to invalidate.
10381     * @param bottom The bottom coordinate of the rectangle to invalidate.
10382     *
10383     * @see #invalidate(int, int, int, int)
10384     * @see #invalidate(Rect)
10385     * @see #postInvalidate(int, int, int, int)
10386     */
10387    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10388            int right, int bottom) {
10389
10390        // We try only with the AttachInfo because there's no point in invalidating
10391        // if we are not attached to our window
10392        final AttachInfo attachInfo = mAttachInfo;
10393        if (attachInfo != null) {
10394            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10395            info.target = this;
10396            info.left = left;
10397            info.top = top;
10398            info.right = right;
10399            info.bottom = bottom;
10400
10401            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10402        }
10403    }
10404
10405    /**
10406     * <p>Cause an invalidate to happen on the next animation time step, typically the
10407     * next display frame.</p>
10408     *
10409     * <p>This method can be invoked from outside of the UI thread
10410     * only when this View is attached to a window.</p>
10411     *
10412     * @see #invalidate()
10413     */
10414    public void postInvalidateOnAnimation() {
10415        // We try only with the AttachInfo because there's no point in invalidating
10416        // if we are not attached to our window
10417        final AttachInfo attachInfo = mAttachInfo;
10418        if (attachInfo != null) {
10419            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10420        }
10421    }
10422
10423    /**
10424     * <p>Cause an invalidate of the specified area to happen on the next animation
10425     * time step, typically the next display frame.</p>
10426     *
10427     * <p>This method can be invoked from outside of the UI thread
10428     * only when this View is attached to a window.</p>
10429     *
10430     * @param left The left coordinate of the rectangle to invalidate.
10431     * @param top The top coordinate of the rectangle to invalidate.
10432     * @param right The right coordinate of the rectangle to invalidate.
10433     * @param bottom The bottom coordinate of the rectangle to invalidate.
10434     *
10435     * @see #invalidate(int, int, int, int)
10436     * @see #invalidate(Rect)
10437     */
10438    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10439        // We try only with the AttachInfo because there's no point in invalidating
10440        // if we are not attached to our window
10441        final AttachInfo attachInfo = mAttachInfo;
10442        if (attachInfo != null) {
10443            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10444            info.target = this;
10445            info.left = left;
10446            info.top = top;
10447            info.right = right;
10448            info.bottom = bottom;
10449
10450            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10451        }
10452    }
10453
10454    /**
10455     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10456     * This event is sent at most once every
10457     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10458     */
10459    private void postSendViewScrolledAccessibilityEventCallback() {
10460        if (mSendViewScrolledAccessibilityEvent == null) {
10461            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10462        }
10463        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10464            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10465            postDelayed(mSendViewScrolledAccessibilityEvent,
10466                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10467        }
10468    }
10469
10470    /**
10471     * Called by a parent to request that a child update its values for mScrollX
10472     * and mScrollY if necessary. This will typically be done if the child is
10473     * animating a scroll using a {@link android.widget.Scroller Scroller}
10474     * object.
10475     */
10476    public void computeScroll() {
10477    }
10478
10479    /**
10480     * <p>Indicate whether the horizontal edges are faded when the view is
10481     * scrolled horizontally.</p>
10482     *
10483     * @return true if the horizontal edges should are faded on scroll, false
10484     *         otherwise
10485     *
10486     * @see #setHorizontalFadingEdgeEnabled(boolean)
10487     *
10488     * @attr ref android.R.styleable#View_requiresFadingEdge
10489     */
10490    public boolean isHorizontalFadingEdgeEnabled() {
10491        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10492    }
10493
10494    /**
10495     * <p>Define whether the horizontal edges should be faded when this view
10496     * is scrolled horizontally.</p>
10497     *
10498     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10499     *                                    be faded when the view is scrolled
10500     *                                    horizontally
10501     *
10502     * @see #isHorizontalFadingEdgeEnabled()
10503     *
10504     * @attr ref android.R.styleable#View_requiresFadingEdge
10505     */
10506    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10507        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10508            if (horizontalFadingEdgeEnabled) {
10509                initScrollCache();
10510            }
10511
10512            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10513        }
10514    }
10515
10516    /**
10517     * <p>Indicate whether the vertical edges are faded when the view is
10518     * scrolled horizontally.</p>
10519     *
10520     * @return true if the vertical edges should are faded on scroll, false
10521     *         otherwise
10522     *
10523     * @see #setVerticalFadingEdgeEnabled(boolean)
10524     *
10525     * @attr ref android.R.styleable#View_requiresFadingEdge
10526     */
10527    public boolean isVerticalFadingEdgeEnabled() {
10528        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10529    }
10530
10531    /**
10532     * <p>Define whether the vertical edges should be faded when this view
10533     * is scrolled vertically.</p>
10534     *
10535     * @param verticalFadingEdgeEnabled true if the vertical edges should
10536     *                                  be faded when the view is scrolled
10537     *                                  vertically
10538     *
10539     * @see #isVerticalFadingEdgeEnabled()
10540     *
10541     * @attr ref android.R.styleable#View_requiresFadingEdge
10542     */
10543    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10544        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10545            if (verticalFadingEdgeEnabled) {
10546                initScrollCache();
10547            }
10548
10549            mViewFlags ^= FADING_EDGE_VERTICAL;
10550        }
10551    }
10552
10553    /**
10554     * Returns the strength, or intensity, of the top faded edge. The strength is
10555     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10556     * returns 0.0 or 1.0 but no value in between.
10557     *
10558     * Subclasses should override this method to provide a smoother fade transition
10559     * when scrolling occurs.
10560     *
10561     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10562     */
10563    protected float getTopFadingEdgeStrength() {
10564        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10565    }
10566
10567    /**
10568     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10569     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10570     * returns 0.0 or 1.0 but no value in between.
10571     *
10572     * Subclasses should override this method to provide a smoother fade transition
10573     * when scrolling occurs.
10574     *
10575     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10576     */
10577    protected float getBottomFadingEdgeStrength() {
10578        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10579                computeVerticalScrollRange() ? 1.0f : 0.0f;
10580    }
10581
10582    /**
10583     * Returns the strength, or intensity, of the left faded edge. The strength is
10584     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10585     * returns 0.0 or 1.0 but no value in between.
10586     *
10587     * Subclasses should override this method to provide a smoother fade transition
10588     * when scrolling occurs.
10589     *
10590     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10591     */
10592    protected float getLeftFadingEdgeStrength() {
10593        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10594    }
10595
10596    /**
10597     * Returns the strength, or intensity, of the right faded edge. The strength is
10598     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10599     * returns 0.0 or 1.0 but no value in between.
10600     *
10601     * Subclasses should override this method to provide a smoother fade transition
10602     * when scrolling occurs.
10603     *
10604     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10605     */
10606    protected float getRightFadingEdgeStrength() {
10607        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10608                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10609    }
10610
10611    /**
10612     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10613     * scrollbar is not drawn by default.</p>
10614     *
10615     * @return true if the horizontal scrollbar should be painted, false
10616     *         otherwise
10617     *
10618     * @see #setHorizontalScrollBarEnabled(boolean)
10619     */
10620    public boolean isHorizontalScrollBarEnabled() {
10621        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10622    }
10623
10624    /**
10625     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10626     * scrollbar is not drawn by default.</p>
10627     *
10628     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10629     *                                   be painted
10630     *
10631     * @see #isHorizontalScrollBarEnabled()
10632     */
10633    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10634        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10635            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10636            computeOpaqueFlags();
10637            resolvePadding();
10638        }
10639    }
10640
10641    /**
10642     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10643     * scrollbar is not drawn by default.</p>
10644     *
10645     * @return true if the vertical scrollbar should be painted, false
10646     *         otherwise
10647     *
10648     * @see #setVerticalScrollBarEnabled(boolean)
10649     */
10650    public boolean isVerticalScrollBarEnabled() {
10651        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10652    }
10653
10654    /**
10655     * <p>Define whether the vertical scrollbar should be drawn or not. The
10656     * scrollbar is not drawn by default.</p>
10657     *
10658     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10659     *                                 be painted
10660     *
10661     * @see #isVerticalScrollBarEnabled()
10662     */
10663    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10664        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10665            mViewFlags ^= SCROLLBARS_VERTICAL;
10666            computeOpaqueFlags();
10667            resolvePadding();
10668        }
10669    }
10670
10671    /**
10672     * @hide
10673     */
10674    protected void recomputePadding() {
10675        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10676    }
10677
10678    /**
10679     * Define whether scrollbars will fade when the view is not scrolling.
10680     *
10681     * @param fadeScrollbars wheter to enable fading
10682     *
10683     * @attr ref android.R.styleable#View_fadeScrollbars
10684     */
10685    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10686        initScrollCache();
10687        final ScrollabilityCache scrollabilityCache = mScrollCache;
10688        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10689        if (fadeScrollbars) {
10690            scrollabilityCache.state = ScrollabilityCache.OFF;
10691        } else {
10692            scrollabilityCache.state = ScrollabilityCache.ON;
10693        }
10694    }
10695
10696    /**
10697     *
10698     * Returns true if scrollbars will fade when this view is not scrolling
10699     *
10700     * @return true if scrollbar fading is enabled
10701     *
10702     * @attr ref android.R.styleable#View_fadeScrollbars
10703     */
10704    public boolean isScrollbarFadingEnabled() {
10705        return mScrollCache != null && mScrollCache.fadeScrollBars;
10706    }
10707
10708    /**
10709     *
10710     * Returns the delay before scrollbars fade.
10711     *
10712     * @return the delay before scrollbars fade
10713     *
10714     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10715     */
10716    public int getScrollBarDefaultDelayBeforeFade() {
10717        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10718                mScrollCache.scrollBarDefaultDelayBeforeFade;
10719    }
10720
10721    /**
10722     * Define the delay before scrollbars fade.
10723     *
10724     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10725     *
10726     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10727     */
10728    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10729        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10730    }
10731
10732    /**
10733     *
10734     * Returns the scrollbar fade duration.
10735     *
10736     * @return the scrollbar fade duration
10737     *
10738     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10739     */
10740    public int getScrollBarFadeDuration() {
10741        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10742                mScrollCache.scrollBarFadeDuration;
10743    }
10744
10745    /**
10746     * Define the scrollbar fade duration.
10747     *
10748     * @param scrollBarFadeDuration - the scrollbar fade duration
10749     *
10750     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10751     */
10752    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10753        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10754    }
10755
10756    /**
10757     *
10758     * Returns the scrollbar size.
10759     *
10760     * @return the scrollbar size
10761     *
10762     * @attr ref android.R.styleable#View_scrollbarSize
10763     */
10764    public int getScrollBarSize() {
10765        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10766                mScrollCache.scrollBarSize;
10767    }
10768
10769    /**
10770     * Define the scrollbar size.
10771     *
10772     * @param scrollBarSize - the scrollbar size
10773     *
10774     * @attr ref android.R.styleable#View_scrollbarSize
10775     */
10776    public void setScrollBarSize(int scrollBarSize) {
10777        getScrollCache().scrollBarSize = scrollBarSize;
10778    }
10779
10780    /**
10781     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10782     * inset. When inset, they add to the padding of the view. And the scrollbars
10783     * can be drawn inside the padding area or on the edge of the view. For example,
10784     * if a view has a background drawable and you want to draw the scrollbars
10785     * inside the padding specified by the drawable, you can use
10786     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10787     * appear at the edge of the view, ignoring the padding, then you can use
10788     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10789     * @param style the style of the scrollbars. Should be one of
10790     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10791     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10792     * @see #SCROLLBARS_INSIDE_OVERLAY
10793     * @see #SCROLLBARS_INSIDE_INSET
10794     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10795     * @see #SCROLLBARS_OUTSIDE_INSET
10796     *
10797     * @attr ref android.R.styleable#View_scrollbarStyle
10798     */
10799    public void setScrollBarStyle(int style) {
10800        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10801            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10802            computeOpaqueFlags();
10803            resolvePadding();
10804        }
10805    }
10806
10807    /**
10808     * <p>Returns the current scrollbar style.</p>
10809     * @return the current scrollbar style
10810     * @see #SCROLLBARS_INSIDE_OVERLAY
10811     * @see #SCROLLBARS_INSIDE_INSET
10812     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10813     * @see #SCROLLBARS_OUTSIDE_INSET
10814     *
10815     * @attr ref android.R.styleable#View_scrollbarStyle
10816     */
10817    @ViewDebug.ExportedProperty(mapping = {
10818            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10819            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10820            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10821            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10822    })
10823    public int getScrollBarStyle() {
10824        return mViewFlags & SCROLLBARS_STYLE_MASK;
10825    }
10826
10827    /**
10828     * <p>Compute the horizontal range that the horizontal scrollbar
10829     * represents.</p>
10830     *
10831     * <p>The range is expressed in arbitrary units that must be the same as the
10832     * units used by {@link #computeHorizontalScrollExtent()} and
10833     * {@link #computeHorizontalScrollOffset()}.</p>
10834     *
10835     * <p>The default range is the drawing width of this view.</p>
10836     *
10837     * @return the total horizontal range represented by the horizontal
10838     *         scrollbar
10839     *
10840     * @see #computeHorizontalScrollExtent()
10841     * @see #computeHorizontalScrollOffset()
10842     * @see android.widget.ScrollBarDrawable
10843     */
10844    protected int computeHorizontalScrollRange() {
10845        return getWidth();
10846    }
10847
10848    /**
10849     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10850     * within the horizontal range. This value is used to compute the position
10851     * of the thumb within the scrollbar's track.</p>
10852     *
10853     * <p>The range is expressed in arbitrary units that must be the same as the
10854     * units used by {@link #computeHorizontalScrollRange()} and
10855     * {@link #computeHorizontalScrollExtent()}.</p>
10856     *
10857     * <p>The default offset is the scroll offset of this view.</p>
10858     *
10859     * @return the horizontal offset of the scrollbar's thumb
10860     *
10861     * @see #computeHorizontalScrollRange()
10862     * @see #computeHorizontalScrollExtent()
10863     * @see android.widget.ScrollBarDrawable
10864     */
10865    protected int computeHorizontalScrollOffset() {
10866        return mScrollX;
10867    }
10868
10869    /**
10870     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10871     * within the horizontal range. This value is used to compute the length
10872     * of the thumb within the scrollbar's track.</p>
10873     *
10874     * <p>The range is expressed in arbitrary units that must be the same as the
10875     * units used by {@link #computeHorizontalScrollRange()} and
10876     * {@link #computeHorizontalScrollOffset()}.</p>
10877     *
10878     * <p>The default extent is the drawing width of this view.</p>
10879     *
10880     * @return the horizontal extent of the scrollbar's thumb
10881     *
10882     * @see #computeHorizontalScrollRange()
10883     * @see #computeHorizontalScrollOffset()
10884     * @see android.widget.ScrollBarDrawable
10885     */
10886    protected int computeHorizontalScrollExtent() {
10887        return getWidth();
10888    }
10889
10890    /**
10891     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10892     *
10893     * <p>The range is expressed in arbitrary units that must be the same as the
10894     * units used by {@link #computeVerticalScrollExtent()} and
10895     * {@link #computeVerticalScrollOffset()}.</p>
10896     *
10897     * @return the total vertical range represented by the vertical scrollbar
10898     *
10899     * <p>The default range is the drawing height of this view.</p>
10900     *
10901     * @see #computeVerticalScrollExtent()
10902     * @see #computeVerticalScrollOffset()
10903     * @see android.widget.ScrollBarDrawable
10904     */
10905    protected int computeVerticalScrollRange() {
10906        return getHeight();
10907    }
10908
10909    /**
10910     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10911     * within the horizontal range. This value is used to compute the position
10912     * of the thumb within the scrollbar's track.</p>
10913     *
10914     * <p>The range is expressed in arbitrary units that must be the same as the
10915     * units used by {@link #computeVerticalScrollRange()} and
10916     * {@link #computeVerticalScrollExtent()}.</p>
10917     *
10918     * <p>The default offset is the scroll offset of this view.</p>
10919     *
10920     * @return the vertical offset of the scrollbar's thumb
10921     *
10922     * @see #computeVerticalScrollRange()
10923     * @see #computeVerticalScrollExtent()
10924     * @see android.widget.ScrollBarDrawable
10925     */
10926    protected int computeVerticalScrollOffset() {
10927        return mScrollY;
10928    }
10929
10930    /**
10931     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10932     * within the vertical range. This value is used to compute the length
10933     * of the thumb within the scrollbar's track.</p>
10934     *
10935     * <p>The range is expressed in arbitrary units that must be the same as the
10936     * units used by {@link #computeVerticalScrollRange()} and
10937     * {@link #computeVerticalScrollOffset()}.</p>
10938     *
10939     * <p>The default extent is the drawing height of this view.</p>
10940     *
10941     * @return the vertical extent of the scrollbar's thumb
10942     *
10943     * @see #computeVerticalScrollRange()
10944     * @see #computeVerticalScrollOffset()
10945     * @see android.widget.ScrollBarDrawable
10946     */
10947    protected int computeVerticalScrollExtent() {
10948        return getHeight();
10949    }
10950
10951    /**
10952     * Check if this view can be scrolled horizontally in a certain direction.
10953     *
10954     * @param direction Negative to check scrolling left, positive to check scrolling right.
10955     * @return true if this view can be scrolled in the specified direction, false otherwise.
10956     */
10957    public boolean canScrollHorizontally(int direction) {
10958        final int offset = computeHorizontalScrollOffset();
10959        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10960        if (range == 0) return false;
10961        if (direction < 0) {
10962            return offset > 0;
10963        } else {
10964            return offset < range - 1;
10965        }
10966    }
10967
10968    /**
10969     * Check if this view can be scrolled vertically in a certain direction.
10970     *
10971     * @param direction Negative to check scrolling up, positive to check scrolling down.
10972     * @return true if this view can be scrolled in the specified direction, false otherwise.
10973     */
10974    public boolean canScrollVertically(int direction) {
10975        final int offset = computeVerticalScrollOffset();
10976        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10977        if (range == 0) return false;
10978        if (direction < 0) {
10979            return offset > 0;
10980        } else {
10981            return offset < range - 1;
10982        }
10983    }
10984
10985    /**
10986     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10987     * scrollbars are painted only if they have been awakened first.</p>
10988     *
10989     * @param canvas the canvas on which to draw the scrollbars
10990     *
10991     * @see #awakenScrollBars(int)
10992     */
10993    protected final void onDrawScrollBars(Canvas canvas) {
10994        // scrollbars are drawn only when the animation is running
10995        final ScrollabilityCache cache = mScrollCache;
10996        if (cache != null) {
10997
10998            int state = cache.state;
10999
11000            if (state == ScrollabilityCache.OFF) {
11001                return;
11002            }
11003
11004            boolean invalidate = false;
11005
11006            if (state == ScrollabilityCache.FADING) {
11007                // We're fading -- get our fade interpolation
11008                if (cache.interpolatorValues == null) {
11009                    cache.interpolatorValues = new float[1];
11010                }
11011
11012                float[] values = cache.interpolatorValues;
11013
11014                // Stops the animation if we're done
11015                if (cache.scrollBarInterpolator.timeToValues(values) ==
11016                        Interpolator.Result.FREEZE_END) {
11017                    cache.state = ScrollabilityCache.OFF;
11018                } else {
11019                    cache.scrollBar.setAlpha(Math.round(values[0]));
11020                }
11021
11022                // This will make the scroll bars inval themselves after
11023                // drawing. We only want this when we're fading so that
11024                // we prevent excessive redraws
11025                invalidate = true;
11026            } else {
11027                // We're just on -- but we may have been fading before so
11028                // reset alpha
11029                cache.scrollBar.setAlpha(255);
11030            }
11031
11032
11033            final int viewFlags = mViewFlags;
11034
11035            final boolean drawHorizontalScrollBar =
11036                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11037            final boolean drawVerticalScrollBar =
11038                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11039                && !isVerticalScrollBarHidden();
11040
11041            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11042                final int width = mRight - mLeft;
11043                final int height = mBottom - mTop;
11044
11045                final ScrollBarDrawable scrollBar = cache.scrollBar;
11046
11047                final int scrollX = mScrollX;
11048                final int scrollY = mScrollY;
11049                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11050
11051                int left, top, right, bottom;
11052
11053                if (drawHorizontalScrollBar) {
11054                    int size = scrollBar.getSize(false);
11055                    if (size <= 0) {
11056                        size = cache.scrollBarSize;
11057                    }
11058
11059                    scrollBar.setParameters(computeHorizontalScrollRange(),
11060                                            computeHorizontalScrollOffset(),
11061                                            computeHorizontalScrollExtent(), false);
11062                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11063                            getVerticalScrollbarWidth() : 0;
11064                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11065                    left = scrollX + (mPaddingLeft & inside);
11066                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11067                    bottom = top + size;
11068                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11069                    if (invalidate) {
11070                        invalidate(left, top, right, bottom);
11071                    }
11072                }
11073
11074                if (drawVerticalScrollBar) {
11075                    int size = scrollBar.getSize(true);
11076                    if (size <= 0) {
11077                        size = cache.scrollBarSize;
11078                    }
11079
11080                    scrollBar.setParameters(computeVerticalScrollRange(),
11081                                            computeVerticalScrollOffset(),
11082                                            computeVerticalScrollExtent(), true);
11083                    switch (mVerticalScrollbarPosition) {
11084                        default:
11085                        case SCROLLBAR_POSITION_DEFAULT:
11086                        case SCROLLBAR_POSITION_RIGHT:
11087                            left = scrollX + width - size - (mUserPaddingRight & inside);
11088                            break;
11089                        case SCROLLBAR_POSITION_LEFT:
11090                            left = scrollX + (mUserPaddingLeft & inside);
11091                            break;
11092                    }
11093                    top = scrollY + (mPaddingTop & inside);
11094                    right = left + size;
11095                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11096                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11097                    if (invalidate) {
11098                        invalidate(left, top, right, bottom);
11099                    }
11100                }
11101            }
11102        }
11103    }
11104
11105    /**
11106     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11107     * FastScroller is visible.
11108     * @return whether to temporarily hide the vertical scrollbar
11109     * @hide
11110     */
11111    protected boolean isVerticalScrollBarHidden() {
11112        return false;
11113    }
11114
11115    /**
11116     * <p>Draw the horizontal scrollbar if
11117     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11118     *
11119     * @param canvas the canvas on which to draw the scrollbar
11120     * @param scrollBar the scrollbar's drawable
11121     *
11122     * @see #isHorizontalScrollBarEnabled()
11123     * @see #computeHorizontalScrollRange()
11124     * @see #computeHorizontalScrollExtent()
11125     * @see #computeHorizontalScrollOffset()
11126     * @see android.widget.ScrollBarDrawable
11127     * @hide
11128     */
11129    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11130            int l, int t, int r, int b) {
11131        scrollBar.setBounds(l, t, r, b);
11132        scrollBar.draw(canvas);
11133    }
11134
11135    /**
11136     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11137     * returns true.</p>
11138     *
11139     * @param canvas the canvas on which to draw the scrollbar
11140     * @param scrollBar the scrollbar's drawable
11141     *
11142     * @see #isVerticalScrollBarEnabled()
11143     * @see #computeVerticalScrollRange()
11144     * @see #computeVerticalScrollExtent()
11145     * @see #computeVerticalScrollOffset()
11146     * @see android.widget.ScrollBarDrawable
11147     * @hide
11148     */
11149    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11150            int l, int t, int r, int b) {
11151        scrollBar.setBounds(l, t, r, b);
11152        scrollBar.draw(canvas);
11153    }
11154
11155    /**
11156     * Implement this to do your drawing.
11157     *
11158     * @param canvas the canvas on which the background will be drawn
11159     */
11160    protected void onDraw(Canvas canvas) {
11161    }
11162
11163    /*
11164     * Caller is responsible for calling requestLayout if necessary.
11165     * (This allows addViewInLayout to not request a new layout.)
11166     */
11167    void assignParent(ViewParent parent) {
11168        if (mParent == null) {
11169            mParent = parent;
11170        } else if (parent == null) {
11171            mParent = null;
11172        } else {
11173            throw new RuntimeException("view " + this + " being added, but"
11174                    + " it already has a parent");
11175        }
11176    }
11177
11178    /**
11179     * This is called when the view is attached to a window.  At this point it
11180     * has a Surface and will start drawing.  Note that this function is
11181     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11182     * however it may be called any time before the first onDraw -- including
11183     * before or after {@link #onMeasure(int, int)}.
11184     *
11185     * @see #onDetachedFromWindow()
11186     */
11187    protected void onAttachedToWindow() {
11188        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11189            mParent.requestTransparentRegion(this);
11190        }
11191
11192        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11193            initialAwakenScrollBars();
11194            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11195        }
11196
11197        jumpDrawablesToCurrentState();
11198
11199        // Order is important here: LayoutDirection MUST be resolved before Padding
11200        // and TextDirection
11201        resolveLayoutDirection();
11202        resolvePadding();
11203        resolveTextDirection();
11204        resolveTextAlignment();
11205
11206        clearAccessibilityFocus();
11207        if (isFocused()) {
11208            InputMethodManager imm = InputMethodManager.peekInstance();
11209            imm.focusIn(this);
11210        }
11211
11212        if (mAttachInfo != null && mDisplayList != null) {
11213            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11214        }
11215    }
11216
11217    /**
11218     * @see #onScreenStateChanged(int)
11219     */
11220    void dispatchScreenStateChanged(int screenState) {
11221        onScreenStateChanged(screenState);
11222    }
11223
11224    /**
11225     * This method is called whenever the state of the screen this view is
11226     * attached to changes. A state change will usually occurs when the screen
11227     * turns on or off (whether it happens automatically or the user does it
11228     * manually.)
11229     *
11230     * @param screenState The new state of the screen. Can be either
11231     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11232     */
11233    public void onScreenStateChanged(int screenState) {
11234    }
11235
11236    /**
11237     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11238     */
11239    private boolean hasRtlSupport() {
11240        return mContext.getApplicationInfo().hasRtlSupport();
11241    }
11242
11243    /**
11244     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11245     * that the parent directionality can and will be resolved before its children.
11246     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11247     */
11248    public void resolveLayoutDirection() {
11249        // Clear any previous layout direction resolution
11250        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11251
11252        if (hasRtlSupport()) {
11253            // Set resolved depending on layout direction
11254            switch (getLayoutDirection()) {
11255                case LAYOUT_DIRECTION_INHERIT:
11256                    // If this is root view, no need to look at parent's layout dir.
11257                    if (canResolveLayoutDirection()) {
11258                        ViewGroup viewGroup = ((ViewGroup) mParent);
11259
11260                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11261                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11262                        }
11263                    } else {
11264                        // Nothing to do, LTR by default
11265                    }
11266                    break;
11267                case LAYOUT_DIRECTION_RTL:
11268                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11269                    break;
11270                case LAYOUT_DIRECTION_LOCALE:
11271                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11272                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11273                    }
11274                    break;
11275                default:
11276                    // Nothing to do, LTR by default
11277            }
11278        }
11279
11280        // Set to resolved
11281        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11282        onResolvedLayoutDirectionChanged();
11283        // Resolve padding
11284        resolvePadding();
11285    }
11286
11287    /**
11288     * Called when layout direction has been resolved.
11289     *
11290     * The default implementation does nothing.
11291     */
11292    public void onResolvedLayoutDirectionChanged() {
11293    }
11294
11295    /**
11296     * Resolve padding depending on layout direction.
11297     */
11298    public void resolvePadding() {
11299        // If the user specified the absolute padding (either with android:padding or
11300        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11301        // use the default padding or the padding from the background drawable
11302        // (stored at this point in mPadding*)
11303        int resolvedLayoutDirection = getResolvedLayoutDirection();
11304        switch (resolvedLayoutDirection) {
11305            case LAYOUT_DIRECTION_RTL:
11306                // Start user padding override Right user padding. Otherwise, if Right user
11307                // padding is not defined, use the default Right padding. If Right user padding
11308                // is defined, just use it.
11309                if (mUserPaddingStart >= 0) {
11310                    mUserPaddingRight = mUserPaddingStart;
11311                } else if (mUserPaddingRight < 0) {
11312                    mUserPaddingRight = mPaddingRight;
11313                }
11314                if (mUserPaddingEnd >= 0) {
11315                    mUserPaddingLeft = mUserPaddingEnd;
11316                } else if (mUserPaddingLeft < 0) {
11317                    mUserPaddingLeft = mPaddingLeft;
11318                }
11319                break;
11320            case LAYOUT_DIRECTION_LTR:
11321            default:
11322                // Start user padding override Left user padding. Otherwise, if Left user
11323                // padding is not defined, use the default left padding. If Left user padding
11324                // is defined, just use it.
11325                if (mUserPaddingStart >= 0) {
11326                    mUserPaddingLeft = mUserPaddingStart;
11327                } else if (mUserPaddingLeft < 0) {
11328                    mUserPaddingLeft = mPaddingLeft;
11329                }
11330                if (mUserPaddingEnd >= 0) {
11331                    mUserPaddingRight = mUserPaddingEnd;
11332                } else if (mUserPaddingRight < 0) {
11333                    mUserPaddingRight = mPaddingRight;
11334                }
11335        }
11336
11337        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11338
11339        if(isPaddingRelative()) {
11340            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11341        } else {
11342            recomputePadding();
11343        }
11344        onPaddingChanged(resolvedLayoutDirection);
11345    }
11346
11347    /**
11348     * Resolve padding depending on the layout direction. Subclasses that care about
11349     * padding resolution should override this method. The default implementation does
11350     * nothing.
11351     *
11352     * @param layoutDirection the direction of the layout
11353     *
11354     * @see {@link #LAYOUT_DIRECTION_LTR}
11355     * @see {@link #LAYOUT_DIRECTION_RTL}
11356     */
11357    public void onPaddingChanged(int layoutDirection) {
11358    }
11359
11360    /**
11361     * Check if layout direction resolution can be done.
11362     *
11363     * @return true if layout direction resolution can be done otherwise return false.
11364     */
11365    public boolean canResolveLayoutDirection() {
11366        switch (getLayoutDirection()) {
11367            case LAYOUT_DIRECTION_INHERIT:
11368                return (mParent != null) && (mParent instanceof ViewGroup);
11369            default:
11370                return true;
11371        }
11372    }
11373
11374    /**
11375     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11376     * when reset is done.
11377     */
11378    public void resetResolvedLayoutDirection() {
11379        // Reset the current resolved bits
11380        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11381        onResolvedLayoutDirectionReset();
11382        // Reset also the text direction
11383        resetResolvedTextDirection();
11384    }
11385
11386    /**
11387     * Called during reset of resolved layout direction.
11388     *
11389     * Subclasses need to override this method to clear cached information that depends on the
11390     * resolved layout direction, or to inform child views that inherit their layout direction.
11391     *
11392     * The default implementation does nothing.
11393     */
11394    public void onResolvedLayoutDirectionReset() {
11395    }
11396
11397    /**
11398     * Check if a Locale uses an RTL script.
11399     *
11400     * @param locale Locale to check
11401     * @return true if the Locale uses an RTL script.
11402     */
11403    protected static boolean isLayoutDirectionRtl(Locale locale) {
11404        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11405    }
11406
11407    /**
11408     * This is called when the view is detached from a window.  At this point it
11409     * no longer has a surface for drawing.
11410     *
11411     * @see #onAttachedToWindow()
11412     */
11413    protected void onDetachedFromWindow() {
11414        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11415
11416        removeUnsetPressCallback();
11417        removeLongPressCallback();
11418        removePerformClickCallback();
11419        removeSendViewScrolledAccessibilityEventCallback();
11420
11421        destroyDrawingCache();
11422
11423        destroyLayer(false);
11424
11425        if (mAttachInfo != null) {
11426            if (mDisplayList != null) {
11427                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11428            }
11429            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11430        } else {
11431            if (mDisplayList != null) {
11432                // Should never happen
11433                mDisplayList.invalidate();
11434            }
11435        }
11436
11437        mCurrentAnimation = null;
11438
11439        resetResolvedLayoutDirection();
11440        resetResolvedTextAlignment();
11441        resetAccessibilityStateChanged();
11442    }
11443
11444    /**
11445     * @return The number of times this view has been attached to a window
11446     */
11447    protected int getWindowAttachCount() {
11448        return mWindowAttachCount;
11449    }
11450
11451    /**
11452     * Retrieve a unique token identifying the window this view is attached to.
11453     * @return Return the window's token for use in
11454     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11455     */
11456    public IBinder getWindowToken() {
11457        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11458    }
11459
11460    /**
11461     * Retrieve a unique token identifying the top-level "real" window of
11462     * the window that this view is attached to.  That is, this is like
11463     * {@link #getWindowToken}, except if the window this view in is a panel
11464     * window (attached to another containing window), then the token of
11465     * the containing window is returned instead.
11466     *
11467     * @return Returns the associated window token, either
11468     * {@link #getWindowToken()} or the containing window's token.
11469     */
11470    public IBinder getApplicationWindowToken() {
11471        AttachInfo ai = mAttachInfo;
11472        if (ai != null) {
11473            IBinder appWindowToken = ai.mPanelParentWindowToken;
11474            if (appWindowToken == null) {
11475                appWindowToken = ai.mWindowToken;
11476            }
11477            return appWindowToken;
11478        }
11479        return null;
11480    }
11481
11482    /**
11483     * Retrieve private session object this view hierarchy is using to
11484     * communicate with the window manager.
11485     * @return the session object to communicate with the window manager
11486     */
11487    /*package*/ IWindowSession getWindowSession() {
11488        return mAttachInfo != null ? mAttachInfo.mSession : null;
11489    }
11490
11491    /**
11492     * @param info the {@link android.view.View.AttachInfo} to associated with
11493     *        this view
11494     */
11495    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11496        //System.out.println("Attached! " + this);
11497        mAttachInfo = info;
11498        mWindowAttachCount++;
11499        // We will need to evaluate the drawable state at least once.
11500        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11501        if (mFloatingTreeObserver != null) {
11502            info.mTreeObserver.merge(mFloatingTreeObserver);
11503            mFloatingTreeObserver = null;
11504        }
11505        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11506            mAttachInfo.mScrollContainers.add(this);
11507            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11508        }
11509        performCollectViewAttributes(mAttachInfo, visibility);
11510        onAttachedToWindow();
11511
11512        ListenerInfo li = mListenerInfo;
11513        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11514                li != null ? li.mOnAttachStateChangeListeners : null;
11515        if (listeners != null && listeners.size() > 0) {
11516            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11517            // perform the dispatching. The iterator is a safe guard against listeners that
11518            // could mutate the list by calling the various add/remove methods. This prevents
11519            // the array from being modified while we iterate it.
11520            for (OnAttachStateChangeListener listener : listeners) {
11521                listener.onViewAttachedToWindow(this);
11522            }
11523        }
11524
11525        int vis = info.mWindowVisibility;
11526        if (vis != GONE) {
11527            onWindowVisibilityChanged(vis);
11528        }
11529        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11530            // If nobody has evaluated the drawable state yet, then do it now.
11531            refreshDrawableState();
11532        }
11533    }
11534
11535    void dispatchDetachedFromWindow() {
11536        AttachInfo info = mAttachInfo;
11537        if (info != null) {
11538            int vis = info.mWindowVisibility;
11539            if (vis != GONE) {
11540                onWindowVisibilityChanged(GONE);
11541            }
11542        }
11543
11544        onDetachedFromWindow();
11545
11546        ListenerInfo li = mListenerInfo;
11547        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11548                li != null ? li.mOnAttachStateChangeListeners : null;
11549        if (listeners != null && listeners.size() > 0) {
11550            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11551            // perform the dispatching. The iterator is a safe guard against listeners that
11552            // could mutate the list by calling the various add/remove methods. This prevents
11553            // the array from being modified while we iterate it.
11554            for (OnAttachStateChangeListener listener : listeners) {
11555                listener.onViewDetachedFromWindow(this);
11556            }
11557        }
11558
11559        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11560            mAttachInfo.mScrollContainers.remove(this);
11561            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11562        }
11563
11564        mAttachInfo = null;
11565    }
11566
11567    /**
11568     * Store this view hierarchy's frozen state into the given container.
11569     *
11570     * @param container The SparseArray in which to save the view's state.
11571     *
11572     * @see #restoreHierarchyState(android.util.SparseArray)
11573     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11574     * @see #onSaveInstanceState()
11575     */
11576    public void saveHierarchyState(SparseArray<Parcelable> container) {
11577        dispatchSaveInstanceState(container);
11578    }
11579
11580    /**
11581     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11582     * this view and its children. May be overridden to modify how freezing happens to a
11583     * view's children; for example, some views may want to not store state for their children.
11584     *
11585     * @param container The SparseArray in which to save the view's state.
11586     *
11587     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11588     * @see #saveHierarchyState(android.util.SparseArray)
11589     * @see #onSaveInstanceState()
11590     */
11591    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11592        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11593            mPrivateFlags &= ~SAVE_STATE_CALLED;
11594            Parcelable state = onSaveInstanceState();
11595            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11596                throw new IllegalStateException(
11597                        "Derived class did not call super.onSaveInstanceState()");
11598            }
11599            if (state != null) {
11600                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11601                // + ": " + state);
11602                container.put(mID, state);
11603            }
11604        }
11605    }
11606
11607    /**
11608     * Hook allowing a view to generate a representation of its internal state
11609     * that can later be used to create a new instance with that same state.
11610     * This state should only contain information that is not persistent or can
11611     * not be reconstructed later. For example, you will never store your
11612     * current position on screen because that will be computed again when a
11613     * new instance of the view is placed in its view hierarchy.
11614     * <p>
11615     * Some examples of things you may store here: the current cursor position
11616     * in a text view (but usually not the text itself since that is stored in a
11617     * content provider or other persistent storage), the currently selected
11618     * item in a list view.
11619     *
11620     * @return Returns a Parcelable object containing the view's current dynamic
11621     *         state, or null if there is nothing interesting to save. The
11622     *         default implementation returns null.
11623     * @see #onRestoreInstanceState(android.os.Parcelable)
11624     * @see #saveHierarchyState(android.util.SparseArray)
11625     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11626     * @see #setSaveEnabled(boolean)
11627     */
11628    protected Parcelable onSaveInstanceState() {
11629        mPrivateFlags |= SAVE_STATE_CALLED;
11630        return BaseSavedState.EMPTY_STATE;
11631    }
11632
11633    /**
11634     * Restore this view hierarchy's frozen state from the given container.
11635     *
11636     * @param container The SparseArray which holds previously frozen states.
11637     *
11638     * @see #saveHierarchyState(android.util.SparseArray)
11639     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11640     * @see #onRestoreInstanceState(android.os.Parcelable)
11641     */
11642    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11643        dispatchRestoreInstanceState(container);
11644    }
11645
11646    /**
11647     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11648     * state for this view and its children. May be overridden to modify how restoring
11649     * happens to a view's children; for example, some views may want to not store state
11650     * for their children.
11651     *
11652     * @param container The SparseArray which holds previously saved state.
11653     *
11654     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11655     * @see #restoreHierarchyState(android.util.SparseArray)
11656     * @see #onRestoreInstanceState(android.os.Parcelable)
11657     */
11658    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11659        if (mID != NO_ID) {
11660            Parcelable state = container.get(mID);
11661            if (state != null) {
11662                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11663                // + ": " + state);
11664                mPrivateFlags &= ~SAVE_STATE_CALLED;
11665                onRestoreInstanceState(state);
11666                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11667                    throw new IllegalStateException(
11668                            "Derived class did not call super.onRestoreInstanceState()");
11669                }
11670            }
11671        }
11672    }
11673
11674    /**
11675     * Hook allowing a view to re-apply a representation of its internal state that had previously
11676     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11677     * null state.
11678     *
11679     * @param state The frozen state that had previously been returned by
11680     *        {@link #onSaveInstanceState}.
11681     *
11682     * @see #onSaveInstanceState()
11683     * @see #restoreHierarchyState(android.util.SparseArray)
11684     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11685     */
11686    protected void onRestoreInstanceState(Parcelable state) {
11687        mPrivateFlags |= SAVE_STATE_CALLED;
11688        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11689            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11690                    + "received " + state.getClass().toString() + " instead. This usually happens "
11691                    + "when two views of different type have the same id in the same hierarchy. "
11692                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11693                    + "other views do not use the same id.");
11694        }
11695    }
11696
11697    /**
11698     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11699     *
11700     * @return the drawing start time in milliseconds
11701     */
11702    public long getDrawingTime() {
11703        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11704    }
11705
11706    /**
11707     * <p>Enables or disables the duplication of the parent's state into this view. When
11708     * duplication is enabled, this view gets its drawable state from its parent rather
11709     * than from its own internal properties.</p>
11710     *
11711     * <p>Note: in the current implementation, setting this property to true after the
11712     * view was added to a ViewGroup might have no effect at all. This property should
11713     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11714     *
11715     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11716     * property is enabled, an exception will be thrown.</p>
11717     *
11718     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11719     * parent, these states should not be affected by this method.</p>
11720     *
11721     * @param enabled True to enable duplication of the parent's drawable state, false
11722     *                to disable it.
11723     *
11724     * @see #getDrawableState()
11725     * @see #isDuplicateParentStateEnabled()
11726     */
11727    public void setDuplicateParentStateEnabled(boolean enabled) {
11728        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11729    }
11730
11731    /**
11732     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11733     *
11734     * @return True if this view's drawable state is duplicated from the parent,
11735     *         false otherwise
11736     *
11737     * @see #getDrawableState()
11738     * @see #setDuplicateParentStateEnabled(boolean)
11739     */
11740    public boolean isDuplicateParentStateEnabled() {
11741        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11742    }
11743
11744    /**
11745     * <p>Specifies the type of layer backing this view. The layer can be
11746     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11747     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11748     *
11749     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11750     * instance that controls how the layer is composed on screen. The following
11751     * properties of the paint are taken into account when composing the layer:</p>
11752     * <ul>
11753     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11754     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11755     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11756     * </ul>
11757     *
11758     * <p>If this view has an alpha value set to < 1.0 by calling
11759     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11760     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11761     * equivalent to setting a hardware layer on this view and providing a paint with
11762     * the desired alpha value.<p>
11763     *
11764     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11765     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11766     * for more information on when and how to use layers.</p>
11767     *
11768     * @param layerType The ype of layer to use with this view, must be one of
11769     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11770     *        {@link #LAYER_TYPE_HARDWARE}
11771     * @param paint The paint used to compose the layer. This argument is optional
11772     *        and can be null. It is ignored when the layer type is
11773     *        {@link #LAYER_TYPE_NONE}
11774     *
11775     * @see #getLayerType()
11776     * @see #LAYER_TYPE_NONE
11777     * @see #LAYER_TYPE_SOFTWARE
11778     * @see #LAYER_TYPE_HARDWARE
11779     * @see #setAlpha(float)
11780     *
11781     * @attr ref android.R.styleable#View_layerType
11782     */
11783    public void setLayerType(int layerType, Paint paint) {
11784        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11785            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11786                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11787        }
11788
11789        if (layerType == mLayerType) {
11790            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11791                mLayerPaint = paint == null ? new Paint() : paint;
11792                invalidateParentCaches();
11793                invalidate(true);
11794            }
11795            return;
11796        }
11797
11798        // Destroy any previous software drawing cache if needed
11799        switch (mLayerType) {
11800            case LAYER_TYPE_HARDWARE:
11801                destroyLayer(false);
11802                // fall through - non-accelerated views may use software layer mechanism instead
11803            case LAYER_TYPE_SOFTWARE:
11804                destroyDrawingCache();
11805                break;
11806            default:
11807                break;
11808        }
11809
11810        mLayerType = layerType;
11811        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11812        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11813        mLocalDirtyRect = layerDisabled ? null : new Rect();
11814
11815        invalidateParentCaches();
11816        invalidate(true);
11817    }
11818
11819    /**
11820     * Indicates whether this view has a static layer. A view with layer type
11821     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11822     * dynamic.
11823     */
11824    boolean hasStaticLayer() {
11825        return true;
11826    }
11827
11828    /**
11829     * Indicates what type of layer is currently associated with this view. By default
11830     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11831     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11832     * for more information on the different types of layers.
11833     *
11834     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11835     *         {@link #LAYER_TYPE_HARDWARE}
11836     *
11837     * @see #setLayerType(int, android.graphics.Paint)
11838     * @see #buildLayer()
11839     * @see #LAYER_TYPE_NONE
11840     * @see #LAYER_TYPE_SOFTWARE
11841     * @see #LAYER_TYPE_HARDWARE
11842     */
11843    public int getLayerType() {
11844        return mLayerType;
11845    }
11846
11847    /**
11848     * Forces this view's layer to be created and this view to be rendered
11849     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11850     * invoking this method will have no effect.
11851     *
11852     * This method can for instance be used to render a view into its layer before
11853     * starting an animation. If this view is complex, rendering into the layer
11854     * before starting the animation will avoid skipping frames.
11855     *
11856     * @throws IllegalStateException If this view is not attached to a window
11857     *
11858     * @see #setLayerType(int, android.graphics.Paint)
11859     */
11860    public void buildLayer() {
11861        if (mLayerType == LAYER_TYPE_NONE) return;
11862
11863        if (mAttachInfo == null) {
11864            throw new IllegalStateException("This view must be attached to a window first");
11865        }
11866
11867        switch (mLayerType) {
11868            case LAYER_TYPE_HARDWARE:
11869                if (mAttachInfo.mHardwareRenderer != null &&
11870                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11871                        mAttachInfo.mHardwareRenderer.validate()) {
11872                    getHardwareLayer();
11873                }
11874                break;
11875            case LAYER_TYPE_SOFTWARE:
11876                buildDrawingCache(true);
11877                break;
11878        }
11879    }
11880
11881    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11882    void flushLayer() {
11883        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11884            mHardwareLayer.flush();
11885        }
11886    }
11887
11888    /**
11889     * <p>Returns a hardware layer that can be used to draw this view again
11890     * without executing its draw method.</p>
11891     *
11892     * @return A HardwareLayer ready to render, or null if an error occurred.
11893     */
11894    HardwareLayer getHardwareLayer() {
11895        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11896                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11897            return null;
11898        }
11899
11900        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11901
11902        final int width = mRight - mLeft;
11903        final int height = mBottom - mTop;
11904
11905        if (width == 0 || height == 0) {
11906            return null;
11907        }
11908
11909        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11910            if (mHardwareLayer == null) {
11911                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11912                        width, height, isOpaque());
11913                mLocalDirtyRect.set(0, 0, width, height);
11914            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11915                mHardwareLayer.resize(width, height);
11916                mLocalDirtyRect.set(0, 0, width, height);
11917            }
11918
11919            // The layer is not valid if the underlying GPU resources cannot be allocated
11920            if (!mHardwareLayer.isValid()) {
11921                return null;
11922            }
11923
11924            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11925            mLocalDirtyRect.setEmpty();
11926        }
11927
11928        return mHardwareLayer;
11929    }
11930
11931    /**
11932     * Destroys this View's hardware layer if possible.
11933     *
11934     * @return True if the layer was destroyed, false otherwise.
11935     *
11936     * @see #setLayerType(int, android.graphics.Paint)
11937     * @see #LAYER_TYPE_HARDWARE
11938     */
11939    boolean destroyLayer(boolean valid) {
11940        if (mHardwareLayer != null) {
11941            AttachInfo info = mAttachInfo;
11942            if (info != null && info.mHardwareRenderer != null &&
11943                    info.mHardwareRenderer.isEnabled() &&
11944                    (valid || info.mHardwareRenderer.validate())) {
11945                mHardwareLayer.destroy();
11946                mHardwareLayer = null;
11947
11948                invalidate(true);
11949                invalidateParentCaches();
11950            }
11951            return true;
11952        }
11953        return false;
11954    }
11955
11956    /**
11957     * Destroys all hardware rendering resources. This method is invoked
11958     * when the system needs to reclaim resources. Upon execution of this
11959     * method, you should free any OpenGL resources created by the view.
11960     *
11961     * Note: you <strong>must</strong> call
11962     * <code>super.destroyHardwareResources()</code> when overriding
11963     * this method.
11964     *
11965     * @hide
11966     */
11967    protected void destroyHardwareResources() {
11968        destroyLayer(true);
11969    }
11970
11971    /**
11972     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11973     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11974     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11975     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11976     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11977     * null.</p>
11978     *
11979     * <p>Enabling the drawing cache is similar to
11980     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11981     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11982     * drawing cache has no effect on rendering because the system uses a different mechanism
11983     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11984     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11985     * for information on how to enable software and hardware layers.</p>
11986     *
11987     * <p>This API can be used to manually generate
11988     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11989     * {@link #getDrawingCache()}.</p>
11990     *
11991     * @param enabled true to enable the drawing cache, false otherwise
11992     *
11993     * @see #isDrawingCacheEnabled()
11994     * @see #getDrawingCache()
11995     * @see #buildDrawingCache()
11996     * @see #setLayerType(int, android.graphics.Paint)
11997     */
11998    public void setDrawingCacheEnabled(boolean enabled) {
11999        mCachingFailed = false;
12000        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12001    }
12002
12003    /**
12004     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12005     *
12006     * @return true if the drawing cache is enabled
12007     *
12008     * @see #setDrawingCacheEnabled(boolean)
12009     * @see #getDrawingCache()
12010     */
12011    @ViewDebug.ExportedProperty(category = "drawing")
12012    public boolean isDrawingCacheEnabled() {
12013        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12014    }
12015
12016    /**
12017     * Debugging utility which recursively outputs the dirty state of a view and its
12018     * descendants.
12019     *
12020     * @hide
12021     */
12022    @SuppressWarnings({"UnusedDeclaration"})
12023    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12024        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12025                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12026                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12027                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12028        if (clear) {
12029            mPrivateFlags &= clearMask;
12030        }
12031        if (this instanceof ViewGroup) {
12032            ViewGroup parent = (ViewGroup) this;
12033            final int count = parent.getChildCount();
12034            for (int i = 0; i < count; i++) {
12035                final View child = parent.getChildAt(i);
12036                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12037            }
12038        }
12039    }
12040
12041    /**
12042     * This method is used by ViewGroup to cause its children to restore or recreate their
12043     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12044     * to recreate its own display list, which would happen if it went through the normal
12045     * draw/dispatchDraw mechanisms.
12046     *
12047     * @hide
12048     */
12049    protected void dispatchGetDisplayList() {}
12050
12051    /**
12052     * A view that is not attached or hardware accelerated cannot create a display list.
12053     * This method checks these conditions and returns the appropriate result.
12054     *
12055     * @return true if view has the ability to create a display list, false otherwise.
12056     *
12057     * @hide
12058     */
12059    public boolean canHaveDisplayList() {
12060        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12061    }
12062
12063    /**
12064     * @return The HardwareRenderer associated with that view or null if hardware rendering
12065     * is not supported or this this has not been attached to a window.
12066     *
12067     * @hide
12068     */
12069    public HardwareRenderer getHardwareRenderer() {
12070        if (mAttachInfo != null) {
12071            return mAttachInfo.mHardwareRenderer;
12072        }
12073        return null;
12074    }
12075
12076    /**
12077     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12078     * Otherwise, the same display list will be returned (after having been rendered into
12079     * along the way, depending on the invalidation state of the view).
12080     *
12081     * @param displayList The previous version of this displayList, could be null.
12082     * @param isLayer Whether the requester of the display list is a layer. If so,
12083     * the view will avoid creating a layer inside the resulting display list.
12084     * @return A new or reused DisplayList object.
12085     */
12086    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12087        if (!canHaveDisplayList()) {
12088            return null;
12089        }
12090
12091        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12092                displayList == null || !displayList.isValid() ||
12093                (!isLayer && mRecreateDisplayList))) {
12094            // Don't need to recreate the display list, just need to tell our
12095            // children to restore/recreate theirs
12096            if (displayList != null && displayList.isValid() &&
12097                    !isLayer && !mRecreateDisplayList) {
12098                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12099                mPrivateFlags &= ~DIRTY_MASK;
12100                dispatchGetDisplayList();
12101
12102                return displayList;
12103            }
12104
12105            if (!isLayer) {
12106                // If we got here, we're recreating it. Mark it as such to ensure that
12107                // we copy in child display lists into ours in drawChild()
12108                mRecreateDisplayList = true;
12109            }
12110            if (displayList == null) {
12111                final String name = getClass().getSimpleName();
12112                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12113                // If we're creating a new display list, make sure our parent gets invalidated
12114                // since they will need to recreate their display list to account for this
12115                // new child display list.
12116                invalidateParentCaches();
12117            }
12118
12119            boolean caching = false;
12120            final HardwareCanvas canvas = displayList.start();
12121            int width = mRight - mLeft;
12122            int height = mBottom - mTop;
12123
12124            try {
12125                canvas.setViewport(width, height);
12126                // The dirty rect should always be null for a display list
12127                canvas.onPreDraw(null);
12128                int layerType = (
12129                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12130                        getLayerType() : LAYER_TYPE_NONE;
12131                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12132                    if (layerType == LAYER_TYPE_HARDWARE) {
12133                        final HardwareLayer layer = getHardwareLayer();
12134                        if (layer != null && layer.isValid()) {
12135                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12136                        } else {
12137                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12138                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12139                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12140                        }
12141                        caching = true;
12142                    } else {
12143                        buildDrawingCache(true);
12144                        Bitmap cache = getDrawingCache(true);
12145                        if (cache != null) {
12146                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12147                            caching = true;
12148                        }
12149                    }
12150                } else {
12151
12152                    computeScroll();
12153
12154                    canvas.translate(-mScrollX, -mScrollY);
12155                    if (!isLayer) {
12156                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12157                        mPrivateFlags &= ~DIRTY_MASK;
12158                    }
12159
12160                    // Fast path for layouts with no backgrounds
12161                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12162                        dispatchDraw(canvas);
12163                    } else {
12164                        draw(canvas);
12165                    }
12166                }
12167            } finally {
12168                canvas.onPostDraw();
12169
12170                displayList.end();
12171                displayList.setCaching(caching);
12172                if (isLayer) {
12173                    displayList.setLeftTopRightBottom(0, 0, width, height);
12174                } else {
12175                    setDisplayListProperties(displayList);
12176                }
12177            }
12178        } else if (!isLayer) {
12179            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12180            mPrivateFlags &= ~DIRTY_MASK;
12181        }
12182
12183        return displayList;
12184    }
12185
12186    /**
12187     * Get the DisplayList for the HardwareLayer
12188     *
12189     * @param layer The HardwareLayer whose DisplayList we want
12190     * @return A DisplayList fopr the specified HardwareLayer
12191     */
12192    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12193        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12194        layer.setDisplayList(displayList);
12195        return displayList;
12196    }
12197
12198
12199    /**
12200     * <p>Returns a display list that can be used to draw this view again
12201     * without executing its draw method.</p>
12202     *
12203     * @return A DisplayList ready to replay, or null if caching is not enabled.
12204     *
12205     * @hide
12206     */
12207    public DisplayList getDisplayList() {
12208        mDisplayList = getDisplayList(mDisplayList, false);
12209        return mDisplayList;
12210    }
12211
12212    /**
12213     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12214     *
12215     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12216     *
12217     * @see #getDrawingCache(boolean)
12218     */
12219    public Bitmap getDrawingCache() {
12220        return getDrawingCache(false);
12221    }
12222
12223    /**
12224     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12225     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12226     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12227     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12228     * request the drawing cache by calling this method and draw it on screen if the
12229     * returned bitmap is not null.</p>
12230     *
12231     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12232     * this method will create a bitmap of the same size as this view. Because this bitmap
12233     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12234     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12235     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12236     * size than the view. This implies that your application must be able to handle this
12237     * size.</p>
12238     *
12239     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12240     *        the current density of the screen when the application is in compatibility
12241     *        mode.
12242     *
12243     * @return A bitmap representing this view or null if cache is disabled.
12244     *
12245     * @see #setDrawingCacheEnabled(boolean)
12246     * @see #isDrawingCacheEnabled()
12247     * @see #buildDrawingCache(boolean)
12248     * @see #destroyDrawingCache()
12249     */
12250    public Bitmap getDrawingCache(boolean autoScale) {
12251        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12252            return null;
12253        }
12254        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12255            buildDrawingCache(autoScale);
12256        }
12257        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12258    }
12259
12260    /**
12261     * <p>Frees the resources used by the drawing cache. If you call
12262     * {@link #buildDrawingCache()} manually without calling
12263     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12264     * should cleanup the cache with this method afterwards.</p>
12265     *
12266     * @see #setDrawingCacheEnabled(boolean)
12267     * @see #buildDrawingCache()
12268     * @see #getDrawingCache()
12269     */
12270    public void destroyDrawingCache() {
12271        if (mDrawingCache != null) {
12272            mDrawingCache.recycle();
12273            mDrawingCache = null;
12274        }
12275        if (mUnscaledDrawingCache != null) {
12276            mUnscaledDrawingCache.recycle();
12277            mUnscaledDrawingCache = null;
12278        }
12279    }
12280
12281    /**
12282     * Setting a solid background color for the drawing cache's bitmaps will improve
12283     * performance and memory usage. Note, though that this should only be used if this
12284     * view will always be drawn on top of a solid color.
12285     *
12286     * @param color The background color to use for the drawing cache's bitmap
12287     *
12288     * @see #setDrawingCacheEnabled(boolean)
12289     * @see #buildDrawingCache()
12290     * @see #getDrawingCache()
12291     */
12292    public void setDrawingCacheBackgroundColor(int color) {
12293        if (color != mDrawingCacheBackgroundColor) {
12294            mDrawingCacheBackgroundColor = color;
12295            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12296        }
12297    }
12298
12299    /**
12300     * @see #setDrawingCacheBackgroundColor(int)
12301     *
12302     * @return The background color to used for the drawing cache's bitmap
12303     */
12304    public int getDrawingCacheBackgroundColor() {
12305        return mDrawingCacheBackgroundColor;
12306    }
12307
12308    /**
12309     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12310     *
12311     * @see #buildDrawingCache(boolean)
12312     */
12313    public void buildDrawingCache() {
12314        buildDrawingCache(false);
12315    }
12316
12317    /**
12318     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12319     *
12320     * <p>If you call {@link #buildDrawingCache()} manually without calling
12321     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12322     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12323     *
12324     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12325     * this method will create a bitmap of the same size as this view. Because this bitmap
12326     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12327     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12328     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12329     * size than the view. This implies that your application must be able to handle this
12330     * size.</p>
12331     *
12332     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12333     * you do not need the drawing cache bitmap, calling this method will increase memory
12334     * usage and cause the view to be rendered in software once, thus negatively impacting
12335     * performance.</p>
12336     *
12337     * @see #getDrawingCache()
12338     * @see #destroyDrawingCache()
12339     */
12340    public void buildDrawingCache(boolean autoScale) {
12341        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12342                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12343            mCachingFailed = false;
12344
12345            if (ViewDebug.TRACE_HIERARCHY) {
12346                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12347            }
12348
12349            int width = mRight - mLeft;
12350            int height = mBottom - mTop;
12351
12352            final AttachInfo attachInfo = mAttachInfo;
12353            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12354
12355            if (autoScale && scalingRequired) {
12356                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12357                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12358            }
12359
12360            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12361            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12362            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12363
12364            if (width <= 0 || height <= 0 ||
12365                     // Projected bitmap size in bytes
12366                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12367                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12368                destroyDrawingCache();
12369                mCachingFailed = true;
12370                return;
12371            }
12372
12373            boolean clear = true;
12374            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12375
12376            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12377                Bitmap.Config quality;
12378                if (!opaque) {
12379                    // Never pick ARGB_4444 because it looks awful
12380                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12381                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12382                        case DRAWING_CACHE_QUALITY_AUTO:
12383                            quality = Bitmap.Config.ARGB_8888;
12384                            break;
12385                        case DRAWING_CACHE_QUALITY_LOW:
12386                            quality = Bitmap.Config.ARGB_8888;
12387                            break;
12388                        case DRAWING_CACHE_QUALITY_HIGH:
12389                            quality = Bitmap.Config.ARGB_8888;
12390                            break;
12391                        default:
12392                            quality = Bitmap.Config.ARGB_8888;
12393                            break;
12394                    }
12395                } else {
12396                    // Optimization for translucent windows
12397                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12398                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12399                }
12400
12401                // Try to cleanup memory
12402                if (bitmap != null) bitmap.recycle();
12403
12404                try {
12405                    bitmap = Bitmap.createBitmap(width, height, quality);
12406                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12407                    if (autoScale) {
12408                        mDrawingCache = bitmap;
12409                    } else {
12410                        mUnscaledDrawingCache = bitmap;
12411                    }
12412                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12413                } catch (OutOfMemoryError e) {
12414                    // If there is not enough memory to create the bitmap cache, just
12415                    // ignore the issue as bitmap caches are not required to draw the
12416                    // view hierarchy
12417                    if (autoScale) {
12418                        mDrawingCache = null;
12419                    } else {
12420                        mUnscaledDrawingCache = null;
12421                    }
12422                    mCachingFailed = true;
12423                    return;
12424                }
12425
12426                clear = drawingCacheBackgroundColor != 0;
12427            }
12428
12429            Canvas canvas;
12430            if (attachInfo != null) {
12431                canvas = attachInfo.mCanvas;
12432                if (canvas == null) {
12433                    canvas = new Canvas();
12434                }
12435                canvas.setBitmap(bitmap);
12436                // Temporarily clobber the cached Canvas in case one of our children
12437                // is also using a drawing cache. Without this, the children would
12438                // steal the canvas by attaching their own bitmap to it and bad, bad
12439                // thing would happen (invisible views, corrupted drawings, etc.)
12440                attachInfo.mCanvas = null;
12441            } else {
12442                // This case should hopefully never or seldom happen
12443                canvas = new Canvas(bitmap);
12444            }
12445
12446            if (clear) {
12447                bitmap.eraseColor(drawingCacheBackgroundColor);
12448            }
12449
12450            computeScroll();
12451            final int restoreCount = canvas.save();
12452
12453            if (autoScale && scalingRequired) {
12454                final float scale = attachInfo.mApplicationScale;
12455                canvas.scale(scale, scale);
12456            }
12457
12458            canvas.translate(-mScrollX, -mScrollY);
12459
12460            mPrivateFlags |= DRAWN;
12461            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12462                    mLayerType != LAYER_TYPE_NONE) {
12463                mPrivateFlags |= DRAWING_CACHE_VALID;
12464            }
12465
12466            // Fast path for layouts with no backgrounds
12467            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12468                if (ViewDebug.TRACE_HIERARCHY) {
12469                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12470                }
12471                mPrivateFlags &= ~DIRTY_MASK;
12472                dispatchDraw(canvas);
12473            } else {
12474                draw(canvas);
12475            }
12476
12477            canvas.restoreToCount(restoreCount);
12478            canvas.setBitmap(null);
12479
12480            if (attachInfo != null) {
12481                // Restore the cached Canvas for our siblings
12482                attachInfo.mCanvas = canvas;
12483            }
12484        }
12485    }
12486
12487    /**
12488     * Create a snapshot of the view into a bitmap.  We should probably make
12489     * some form of this public, but should think about the API.
12490     */
12491    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12492        int width = mRight - mLeft;
12493        int height = mBottom - mTop;
12494
12495        final AttachInfo attachInfo = mAttachInfo;
12496        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12497        width = (int) ((width * scale) + 0.5f);
12498        height = (int) ((height * scale) + 0.5f);
12499
12500        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12501        if (bitmap == null) {
12502            throw new OutOfMemoryError();
12503        }
12504
12505        Resources resources = getResources();
12506        if (resources != null) {
12507            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12508        }
12509
12510        Canvas canvas;
12511        if (attachInfo != null) {
12512            canvas = attachInfo.mCanvas;
12513            if (canvas == null) {
12514                canvas = new Canvas();
12515            }
12516            canvas.setBitmap(bitmap);
12517            // Temporarily clobber the cached Canvas in case one of our children
12518            // is also using a drawing cache. Without this, the children would
12519            // steal the canvas by attaching their own bitmap to it and bad, bad
12520            // things would happen (invisible views, corrupted drawings, etc.)
12521            attachInfo.mCanvas = null;
12522        } else {
12523            // This case should hopefully never or seldom happen
12524            canvas = new Canvas(bitmap);
12525        }
12526
12527        if ((backgroundColor & 0xff000000) != 0) {
12528            bitmap.eraseColor(backgroundColor);
12529        }
12530
12531        computeScroll();
12532        final int restoreCount = canvas.save();
12533        canvas.scale(scale, scale);
12534        canvas.translate(-mScrollX, -mScrollY);
12535
12536        // Temporarily remove the dirty mask
12537        int flags = mPrivateFlags;
12538        mPrivateFlags &= ~DIRTY_MASK;
12539
12540        // Fast path for layouts with no backgrounds
12541        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12542            dispatchDraw(canvas);
12543        } else {
12544            draw(canvas);
12545        }
12546
12547        mPrivateFlags = flags;
12548
12549        canvas.restoreToCount(restoreCount);
12550        canvas.setBitmap(null);
12551
12552        if (attachInfo != null) {
12553            // Restore the cached Canvas for our siblings
12554            attachInfo.mCanvas = canvas;
12555        }
12556
12557        return bitmap;
12558    }
12559
12560    /**
12561     * Indicates whether this View is currently in edit mode. A View is usually
12562     * in edit mode when displayed within a developer tool. For instance, if
12563     * this View is being drawn by a visual user interface builder, this method
12564     * should return true.
12565     *
12566     * Subclasses should check the return value of this method to provide
12567     * different behaviors if their normal behavior might interfere with the
12568     * host environment. For instance: the class spawns a thread in its
12569     * constructor, the drawing code relies on device-specific features, etc.
12570     *
12571     * This method is usually checked in the drawing code of custom widgets.
12572     *
12573     * @return True if this View is in edit mode, false otherwise.
12574     */
12575    public boolean isInEditMode() {
12576        return false;
12577    }
12578
12579    /**
12580     * If the View draws content inside its padding and enables fading edges,
12581     * it needs to support padding offsets. Padding offsets are added to the
12582     * fading edges to extend the length of the fade so that it covers pixels
12583     * drawn inside the padding.
12584     *
12585     * Subclasses of this class should override this method if they need
12586     * to draw content inside the padding.
12587     *
12588     * @return True if padding offset must be applied, false otherwise.
12589     *
12590     * @see #getLeftPaddingOffset()
12591     * @see #getRightPaddingOffset()
12592     * @see #getTopPaddingOffset()
12593     * @see #getBottomPaddingOffset()
12594     *
12595     * @since CURRENT
12596     */
12597    protected boolean isPaddingOffsetRequired() {
12598        return false;
12599    }
12600
12601    /**
12602     * Amount by which to extend the left fading region. Called only when
12603     * {@link #isPaddingOffsetRequired()} returns true.
12604     *
12605     * @return The left padding offset in pixels.
12606     *
12607     * @see #isPaddingOffsetRequired()
12608     *
12609     * @since CURRENT
12610     */
12611    protected int getLeftPaddingOffset() {
12612        return 0;
12613    }
12614
12615    /**
12616     * Amount by which to extend the right fading region. Called only when
12617     * {@link #isPaddingOffsetRequired()} returns true.
12618     *
12619     * @return The right padding offset in pixels.
12620     *
12621     * @see #isPaddingOffsetRequired()
12622     *
12623     * @since CURRENT
12624     */
12625    protected int getRightPaddingOffset() {
12626        return 0;
12627    }
12628
12629    /**
12630     * Amount by which to extend the top fading region. Called only when
12631     * {@link #isPaddingOffsetRequired()} returns true.
12632     *
12633     * @return The top padding offset in pixels.
12634     *
12635     * @see #isPaddingOffsetRequired()
12636     *
12637     * @since CURRENT
12638     */
12639    protected int getTopPaddingOffset() {
12640        return 0;
12641    }
12642
12643    /**
12644     * Amount by which to extend the bottom fading region. Called only when
12645     * {@link #isPaddingOffsetRequired()} returns true.
12646     *
12647     * @return The bottom padding offset in pixels.
12648     *
12649     * @see #isPaddingOffsetRequired()
12650     *
12651     * @since CURRENT
12652     */
12653    protected int getBottomPaddingOffset() {
12654        return 0;
12655    }
12656
12657    /**
12658     * @hide
12659     * @param offsetRequired
12660     */
12661    protected int getFadeTop(boolean offsetRequired) {
12662        int top = mPaddingTop;
12663        if (offsetRequired) top += getTopPaddingOffset();
12664        return top;
12665    }
12666
12667    /**
12668     * @hide
12669     * @param offsetRequired
12670     */
12671    protected int getFadeHeight(boolean offsetRequired) {
12672        int padding = mPaddingTop;
12673        if (offsetRequired) padding += getTopPaddingOffset();
12674        return mBottom - mTop - mPaddingBottom - padding;
12675    }
12676
12677    /**
12678     * <p>Indicates whether this view is attached to a hardware accelerated
12679     * window or not.</p>
12680     *
12681     * <p>Even if this method returns true, it does not mean that every call
12682     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12683     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12684     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12685     * window is hardware accelerated,
12686     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12687     * return false, and this method will return true.</p>
12688     *
12689     * @return True if the view is attached to a window and the window is
12690     *         hardware accelerated; false in any other case.
12691     */
12692    public boolean isHardwareAccelerated() {
12693        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12694    }
12695
12696    /**
12697     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12698     * case of an active Animation being run on the view.
12699     */
12700    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12701            Animation a, boolean scalingRequired) {
12702        Transformation invalidationTransform;
12703        final int flags = parent.mGroupFlags;
12704        final boolean initialized = a.isInitialized();
12705        if (!initialized) {
12706            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12707            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12708            onAnimationStart();
12709        }
12710
12711        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12712        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12713            if (parent.mInvalidationTransformation == null) {
12714                parent.mInvalidationTransformation = new Transformation();
12715            }
12716            invalidationTransform = parent.mInvalidationTransformation;
12717            a.getTransformation(drawingTime, invalidationTransform, 1f);
12718        } else {
12719            invalidationTransform = parent.mChildTransformation;
12720        }
12721        if (more) {
12722            if (!a.willChangeBounds()) {
12723                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12724                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12725                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12726                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12727                    // The child need to draw an animation, potentially offscreen, so
12728                    // make sure we do not cancel invalidate requests
12729                    parent.mPrivateFlags |= DRAW_ANIMATION;
12730                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12731                }
12732            } else {
12733                if (parent.mInvalidateRegion == null) {
12734                    parent.mInvalidateRegion = new RectF();
12735                }
12736                final RectF region = parent.mInvalidateRegion;
12737                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12738                        invalidationTransform);
12739
12740                // The child need to draw an animation, potentially offscreen, so
12741                // make sure we do not cancel invalidate requests
12742                parent.mPrivateFlags |= DRAW_ANIMATION;
12743
12744                final int left = mLeft + (int) region.left;
12745                final int top = mTop + (int) region.top;
12746                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12747                        top + (int) (region.height() + .5f));
12748            }
12749        }
12750        return more;
12751    }
12752
12753    /**
12754     * This method is called by getDisplayList() when a display list is created or re-rendered.
12755     * It sets or resets the current value of all properties on that display list (resetting is
12756     * necessary when a display list is being re-created, because we need to make sure that
12757     * previously-set transform values
12758     */
12759    void setDisplayListProperties(DisplayList displayList) {
12760        if (displayList != null) {
12761            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12762            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12763            if (mParent instanceof ViewGroup) {
12764                displayList.setClipChildren(
12765                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12766            }
12767            float alpha = 1;
12768            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12769                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12770                ViewGroup parentVG = (ViewGroup) mParent;
12771                final boolean hasTransform =
12772                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12773                if (hasTransform) {
12774                    Transformation transform = parentVG.mChildTransformation;
12775                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12776                    if (transformType != Transformation.TYPE_IDENTITY) {
12777                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12778                            alpha = transform.getAlpha();
12779                        }
12780                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12781                            displayList.setStaticMatrix(transform.getMatrix());
12782                        }
12783                    }
12784                }
12785            }
12786            if (mTransformationInfo != null) {
12787                alpha *= mTransformationInfo.mAlpha;
12788                if (alpha < 1) {
12789                    final int multipliedAlpha = (int) (255 * alpha);
12790                    if (onSetAlpha(multipliedAlpha)) {
12791                        alpha = 1;
12792                    }
12793                }
12794                displayList.setTransformationInfo(alpha,
12795                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12796                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12797                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12798                        mTransformationInfo.mScaleY);
12799                if (mTransformationInfo.mCamera == null) {
12800                    mTransformationInfo.mCamera = new Camera();
12801                    mTransformationInfo.matrix3D = new Matrix();
12802                }
12803                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12804                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12805                    displayList.setPivotX(getPivotX());
12806                    displayList.setPivotY(getPivotY());
12807                }
12808            } else if (alpha < 1) {
12809                displayList.setAlpha(alpha);
12810            }
12811        }
12812    }
12813
12814    /**
12815     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12816     * This draw() method is an implementation detail and is not intended to be overridden or
12817     * to be called from anywhere else other than ViewGroup.drawChild().
12818     */
12819    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12820        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12821        boolean more = false;
12822        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12823        final int flags = parent.mGroupFlags;
12824
12825        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12826            parent.mChildTransformation.clear();
12827            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12828        }
12829
12830        Transformation transformToApply = null;
12831        boolean concatMatrix = false;
12832
12833        boolean scalingRequired = false;
12834        boolean caching;
12835        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12836
12837        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12838        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12839                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12840            caching = true;
12841            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12842            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12843        } else {
12844            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12845        }
12846
12847        final Animation a = getAnimation();
12848        if (a != null) {
12849            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12850            concatMatrix = a.willChangeTransformationMatrix();
12851            if (concatMatrix) {
12852                mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM;
12853            }
12854            transformToApply = parent.mChildTransformation;
12855        } else {
12856            if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12857                    mDisplayList != null) {
12858                // No longer animating: clear out old animation matrix
12859                mDisplayList.setAnimationMatrix(null);
12860                mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12861            }
12862            if (!useDisplayListProperties &&
12863                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12864                final boolean hasTransform =
12865                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12866                if (hasTransform) {
12867                    final int transformType = parent.mChildTransformation.getTransformationType();
12868                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12869                            parent.mChildTransformation : null;
12870                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12871                }
12872            }
12873        }
12874
12875        concatMatrix |= !childHasIdentityMatrix;
12876
12877        // Sets the flag as early as possible to allow draw() implementations
12878        // to call invalidate() successfully when doing animations
12879        mPrivateFlags |= DRAWN;
12880
12881        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12882                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12883            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12884            return more;
12885        }
12886        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12887
12888        if (hardwareAccelerated) {
12889            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12890            // retain the flag's value temporarily in the mRecreateDisplayList flag
12891            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12892            mPrivateFlags &= ~INVALIDATED;
12893        }
12894
12895        computeScroll();
12896
12897        final int sx = mScrollX;
12898        final int sy = mScrollY;
12899
12900        DisplayList displayList = null;
12901        Bitmap cache = null;
12902        boolean hasDisplayList = false;
12903        if (caching) {
12904            if (!hardwareAccelerated) {
12905                if (layerType != LAYER_TYPE_NONE) {
12906                    layerType = LAYER_TYPE_SOFTWARE;
12907                    buildDrawingCache(true);
12908                }
12909                cache = getDrawingCache(true);
12910            } else {
12911                switch (layerType) {
12912                    case LAYER_TYPE_SOFTWARE:
12913                        if (useDisplayListProperties) {
12914                            hasDisplayList = canHaveDisplayList();
12915                        } else {
12916                            buildDrawingCache(true);
12917                            cache = getDrawingCache(true);
12918                        }
12919                        break;
12920                    case LAYER_TYPE_HARDWARE:
12921                        if (useDisplayListProperties) {
12922                            hasDisplayList = canHaveDisplayList();
12923                        }
12924                        break;
12925                    case LAYER_TYPE_NONE:
12926                        // Delay getting the display list until animation-driven alpha values are
12927                        // set up and possibly passed on to the view
12928                        hasDisplayList = canHaveDisplayList();
12929                        break;
12930                }
12931            }
12932        }
12933        useDisplayListProperties &= hasDisplayList;
12934        if (useDisplayListProperties) {
12935            displayList = getDisplayList();
12936            if (!displayList.isValid()) {
12937                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12938                // to getDisplayList(), the display list will be marked invalid and we should not
12939                // try to use it again.
12940                displayList = null;
12941                hasDisplayList = false;
12942                useDisplayListProperties = false;
12943            }
12944        }
12945
12946        final boolean hasNoCache = cache == null || hasDisplayList;
12947        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12948                layerType != LAYER_TYPE_HARDWARE;
12949
12950        int restoreTo = -1;
12951        if (!useDisplayListProperties || transformToApply != null) {
12952            restoreTo = canvas.save();
12953        }
12954        if (offsetForScroll) {
12955            canvas.translate(mLeft - sx, mTop - sy);
12956        } else {
12957            if (!useDisplayListProperties) {
12958                canvas.translate(mLeft, mTop);
12959            }
12960            if (scalingRequired) {
12961                if (useDisplayListProperties) {
12962                    // TODO: Might not need this if we put everything inside the DL
12963                    restoreTo = canvas.save();
12964                }
12965                // mAttachInfo cannot be null, otherwise scalingRequired == false
12966                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12967                canvas.scale(scale, scale);
12968            }
12969        }
12970
12971        float alpha = useDisplayListProperties ? 1 : getAlpha();
12972        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12973            if (transformToApply != null || !childHasIdentityMatrix) {
12974                int transX = 0;
12975                int transY = 0;
12976
12977                if (offsetForScroll) {
12978                    transX = -sx;
12979                    transY = -sy;
12980                }
12981
12982                if (transformToApply != null) {
12983                    if (concatMatrix) {
12984                        if (useDisplayListProperties) {
12985                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12986                        } else {
12987                            // Undo the scroll translation, apply the transformation matrix,
12988                            // then redo the scroll translate to get the correct result.
12989                            canvas.translate(-transX, -transY);
12990                            canvas.concat(transformToApply.getMatrix());
12991                            canvas.translate(transX, transY);
12992                        }
12993                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12994                    }
12995
12996                    float transformAlpha = transformToApply.getAlpha();
12997                    if (transformAlpha < 1) {
12998                        alpha *= transformToApply.getAlpha();
12999                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13000                    }
13001                }
13002
13003                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13004                    canvas.translate(-transX, -transY);
13005                    canvas.concat(getMatrix());
13006                    canvas.translate(transX, transY);
13007                }
13008            }
13009
13010            if (alpha < 1) {
13011                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13012                if (hasNoCache) {
13013                    final int multipliedAlpha = (int) (255 * alpha);
13014                    if (!onSetAlpha(multipliedAlpha)) {
13015                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13016                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13017                                layerType != LAYER_TYPE_NONE) {
13018                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13019                        }
13020                        if (useDisplayListProperties) {
13021                            displayList.setAlpha(alpha * getAlpha());
13022                        } else  if (layerType == LAYER_TYPE_NONE) {
13023                            final int scrollX = hasDisplayList ? 0 : sx;
13024                            final int scrollY = hasDisplayList ? 0 : sy;
13025                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13026                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13027                        }
13028                    } else {
13029                        // Alpha is handled by the child directly, clobber the layer's alpha
13030                        mPrivateFlags |= ALPHA_SET;
13031                    }
13032                }
13033            }
13034        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13035            onSetAlpha(255);
13036            mPrivateFlags &= ~ALPHA_SET;
13037        }
13038
13039        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13040                !useDisplayListProperties) {
13041            if (offsetForScroll) {
13042                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13043            } else {
13044                if (!scalingRequired || cache == null) {
13045                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13046                } else {
13047                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13048                }
13049            }
13050        }
13051
13052        if (!useDisplayListProperties && hasDisplayList) {
13053            displayList = getDisplayList();
13054            if (!displayList.isValid()) {
13055                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13056                // to getDisplayList(), the display list will be marked invalid and we should not
13057                // try to use it again.
13058                displayList = null;
13059                hasDisplayList = false;
13060            }
13061        }
13062
13063        if (hasNoCache) {
13064            boolean layerRendered = false;
13065            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13066                final HardwareLayer layer = getHardwareLayer();
13067                if (layer != null && layer.isValid()) {
13068                    mLayerPaint.setAlpha((int) (alpha * 255));
13069                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13070                    layerRendered = true;
13071                } else {
13072                    final int scrollX = hasDisplayList ? 0 : sx;
13073                    final int scrollY = hasDisplayList ? 0 : sy;
13074                    canvas.saveLayer(scrollX, scrollY,
13075                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13076                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13077                }
13078            }
13079
13080            if (!layerRendered) {
13081                if (!hasDisplayList) {
13082                    // Fast path for layouts with no backgrounds
13083                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13084                        if (ViewDebug.TRACE_HIERARCHY) {
13085                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
13086                        }
13087                        mPrivateFlags &= ~DIRTY_MASK;
13088                        dispatchDraw(canvas);
13089                    } else {
13090                        draw(canvas);
13091                    }
13092                } else {
13093                    mPrivateFlags &= ~DIRTY_MASK;
13094                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13095                }
13096            }
13097        } else if (cache != null) {
13098            mPrivateFlags &= ~DIRTY_MASK;
13099            Paint cachePaint;
13100
13101            if (layerType == LAYER_TYPE_NONE) {
13102                cachePaint = parent.mCachePaint;
13103                if (cachePaint == null) {
13104                    cachePaint = new Paint();
13105                    cachePaint.setDither(false);
13106                    parent.mCachePaint = cachePaint;
13107                }
13108                if (alpha < 1) {
13109                    cachePaint.setAlpha((int) (alpha * 255));
13110                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13111                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13112                    cachePaint.setAlpha(255);
13113                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13114                }
13115            } else {
13116                cachePaint = mLayerPaint;
13117                cachePaint.setAlpha((int) (alpha * 255));
13118            }
13119            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13120        }
13121
13122        if (restoreTo >= 0) {
13123            canvas.restoreToCount(restoreTo);
13124        }
13125
13126        if (a != null && !more) {
13127            if (!hardwareAccelerated && !a.getFillAfter()) {
13128                onSetAlpha(255);
13129            }
13130            parent.finishAnimatingView(this, a);
13131        }
13132
13133        if (more && hardwareAccelerated) {
13134            // invalidation is the trigger to recreate display lists, so if we're using
13135            // display lists to render, force an invalidate to allow the animation to
13136            // continue drawing another frame
13137            parent.invalidate(true);
13138            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13139                // alpha animations should cause the child to recreate its display list
13140                invalidate(true);
13141            }
13142        }
13143
13144        mRecreateDisplayList = false;
13145
13146        return more;
13147    }
13148
13149    /**
13150     * Manually render this view (and all of its children) to the given Canvas.
13151     * The view must have already done a full layout before this function is
13152     * called.  When implementing a view, implement
13153     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13154     * If you do need to override this method, call the superclass version.
13155     *
13156     * @param canvas The Canvas to which the View is rendered.
13157     */
13158    public void draw(Canvas canvas) {
13159        if (ViewDebug.TRACE_HIERARCHY) {
13160            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
13161        }
13162
13163        final int privateFlags = mPrivateFlags;
13164        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13165                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13166        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13167
13168        /*
13169         * Draw traversal performs several drawing steps which must be executed
13170         * in the appropriate order:
13171         *
13172         *      1. Draw the background
13173         *      2. If necessary, save the canvas' layers to prepare for fading
13174         *      3. Draw view's content
13175         *      4. Draw children
13176         *      5. If necessary, draw the fading edges and restore layers
13177         *      6. Draw decorations (scrollbars for instance)
13178         */
13179
13180        // Step 1, draw the background, if needed
13181        int saveCount;
13182
13183        if (!dirtyOpaque) {
13184            final Drawable background = mBackground;
13185            if (background != null) {
13186                final int scrollX = mScrollX;
13187                final int scrollY = mScrollY;
13188
13189                if (mBackgroundSizeChanged) {
13190                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13191                    mBackgroundSizeChanged = false;
13192                }
13193
13194                if ((scrollX | scrollY) == 0) {
13195                    background.draw(canvas);
13196                } else {
13197                    canvas.translate(scrollX, scrollY);
13198                    background.draw(canvas);
13199                    canvas.translate(-scrollX, -scrollY);
13200                }
13201            }
13202        }
13203
13204        // skip step 2 & 5 if possible (common case)
13205        final int viewFlags = mViewFlags;
13206        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13207        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13208        if (!verticalEdges && !horizontalEdges) {
13209            // Step 3, draw the content
13210            if (!dirtyOpaque) onDraw(canvas);
13211
13212            // Step 4, draw the children
13213            dispatchDraw(canvas);
13214
13215            // Step 6, draw decorations (scrollbars)
13216            onDrawScrollBars(canvas);
13217
13218            // we're done...
13219            return;
13220        }
13221
13222        /*
13223         * Here we do the full fledged routine...
13224         * (this is an uncommon case where speed matters less,
13225         * this is why we repeat some of the tests that have been
13226         * done above)
13227         */
13228
13229        boolean drawTop = false;
13230        boolean drawBottom = false;
13231        boolean drawLeft = false;
13232        boolean drawRight = false;
13233
13234        float topFadeStrength = 0.0f;
13235        float bottomFadeStrength = 0.0f;
13236        float leftFadeStrength = 0.0f;
13237        float rightFadeStrength = 0.0f;
13238
13239        // Step 2, save the canvas' layers
13240        int paddingLeft = mPaddingLeft;
13241
13242        final boolean offsetRequired = isPaddingOffsetRequired();
13243        if (offsetRequired) {
13244            paddingLeft += getLeftPaddingOffset();
13245        }
13246
13247        int left = mScrollX + paddingLeft;
13248        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13249        int top = mScrollY + getFadeTop(offsetRequired);
13250        int bottom = top + getFadeHeight(offsetRequired);
13251
13252        if (offsetRequired) {
13253            right += getRightPaddingOffset();
13254            bottom += getBottomPaddingOffset();
13255        }
13256
13257        final ScrollabilityCache scrollabilityCache = mScrollCache;
13258        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13259        int length = (int) fadeHeight;
13260
13261        // clip the fade length if top and bottom fades overlap
13262        // overlapping fades produce odd-looking artifacts
13263        if (verticalEdges && (top + length > bottom - length)) {
13264            length = (bottom - top) / 2;
13265        }
13266
13267        // also clip horizontal fades if necessary
13268        if (horizontalEdges && (left + length > right - length)) {
13269            length = (right - left) / 2;
13270        }
13271
13272        if (verticalEdges) {
13273            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13274            drawTop = topFadeStrength * fadeHeight > 1.0f;
13275            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13276            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13277        }
13278
13279        if (horizontalEdges) {
13280            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13281            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13282            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13283            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13284        }
13285
13286        saveCount = canvas.getSaveCount();
13287
13288        int solidColor = getSolidColor();
13289        if (solidColor == 0) {
13290            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13291
13292            if (drawTop) {
13293                canvas.saveLayer(left, top, right, top + length, null, flags);
13294            }
13295
13296            if (drawBottom) {
13297                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13298            }
13299
13300            if (drawLeft) {
13301                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13302            }
13303
13304            if (drawRight) {
13305                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13306            }
13307        } else {
13308            scrollabilityCache.setFadeColor(solidColor);
13309        }
13310
13311        // Step 3, draw the content
13312        if (!dirtyOpaque) onDraw(canvas);
13313
13314        // Step 4, draw the children
13315        dispatchDraw(canvas);
13316
13317        // Step 5, draw the fade effect and restore layers
13318        final Paint p = scrollabilityCache.paint;
13319        final Matrix matrix = scrollabilityCache.matrix;
13320        final Shader fade = scrollabilityCache.shader;
13321
13322        if (drawTop) {
13323            matrix.setScale(1, fadeHeight * topFadeStrength);
13324            matrix.postTranslate(left, top);
13325            fade.setLocalMatrix(matrix);
13326            canvas.drawRect(left, top, right, top + length, p);
13327        }
13328
13329        if (drawBottom) {
13330            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13331            matrix.postRotate(180);
13332            matrix.postTranslate(left, bottom);
13333            fade.setLocalMatrix(matrix);
13334            canvas.drawRect(left, bottom - length, right, bottom, p);
13335        }
13336
13337        if (drawLeft) {
13338            matrix.setScale(1, fadeHeight * leftFadeStrength);
13339            matrix.postRotate(-90);
13340            matrix.postTranslate(left, top);
13341            fade.setLocalMatrix(matrix);
13342            canvas.drawRect(left, top, left + length, bottom, p);
13343        }
13344
13345        if (drawRight) {
13346            matrix.setScale(1, fadeHeight * rightFadeStrength);
13347            matrix.postRotate(90);
13348            matrix.postTranslate(right, top);
13349            fade.setLocalMatrix(matrix);
13350            canvas.drawRect(right - length, top, right, bottom, p);
13351        }
13352
13353        canvas.restoreToCount(saveCount);
13354
13355        // Step 6, draw decorations (scrollbars)
13356        onDrawScrollBars(canvas);
13357    }
13358
13359    /**
13360     * Override this if your view is known to always be drawn on top of a solid color background,
13361     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13362     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13363     * should be set to 0xFF.
13364     *
13365     * @see #setVerticalFadingEdgeEnabled(boolean)
13366     * @see #setHorizontalFadingEdgeEnabled(boolean)
13367     *
13368     * @return The known solid color background for this view, or 0 if the color may vary
13369     */
13370    @ViewDebug.ExportedProperty(category = "drawing")
13371    public int getSolidColor() {
13372        return 0;
13373    }
13374
13375    /**
13376     * Build a human readable string representation of the specified view flags.
13377     *
13378     * @param flags the view flags to convert to a string
13379     * @return a String representing the supplied flags
13380     */
13381    private static String printFlags(int flags) {
13382        String output = "";
13383        int numFlags = 0;
13384        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13385            output += "TAKES_FOCUS";
13386            numFlags++;
13387        }
13388
13389        switch (flags & VISIBILITY_MASK) {
13390        case INVISIBLE:
13391            if (numFlags > 0) {
13392                output += " ";
13393            }
13394            output += "INVISIBLE";
13395            // USELESS HERE numFlags++;
13396            break;
13397        case GONE:
13398            if (numFlags > 0) {
13399                output += " ";
13400            }
13401            output += "GONE";
13402            // USELESS HERE numFlags++;
13403            break;
13404        default:
13405            break;
13406        }
13407        return output;
13408    }
13409
13410    /**
13411     * Build a human readable string representation of the specified private
13412     * view flags.
13413     *
13414     * @param privateFlags the private view flags to convert to a string
13415     * @return a String representing the supplied flags
13416     */
13417    private static String printPrivateFlags(int privateFlags) {
13418        String output = "";
13419        int numFlags = 0;
13420
13421        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13422            output += "WANTS_FOCUS";
13423            numFlags++;
13424        }
13425
13426        if ((privateFlags & FOCUSED) == FOCUSED) {
13427            if (numFlags > 0) {
13428                output += " ";
13429            }
13430            output += "FOCUSED";
13431            numFlags++;
13432        }
13433
13434        if ((privateFlags & SELECTED) == SELECTED) {
13435            if (numFlags > 0) {
13436                output += " ";
13437            }
13438            output += "SELECTED";
13439            numFlags++;
13440        }
13441
13442        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13443            if (numFlags > 0) {
13444                output += " ";
13445            }
13446            output += "IS_ROOT_NAMESPACE";
13447            numFlags++;
13448        }
13449
13450        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13451            if (numFlags > 0) {
13452                output += " ";
13453            }
13454            output += "HAS_BOUNDS";
13455            numFlags++;
13456        }
13457
13458        if ((privateFlags & DRAWN) == DRAWN) {
13459            if (numFlags > 0) {
13460                output += " ";
13461            }
13462            output += "DRAWN";
13463            // USELESS HERE numFlags++;
13464        }
13465        return output;
13466    }
13467
13468    /**
13469     * <p>Indicates whether or not this view's layout will be requested during
13470     * the next hierarchy layout pass.</p>
13471     *
13472     * @return true if the layout will be forced during next layout pass
13473     */
13474    public boolean isLayoutRequested() {
13475        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13476    }
13477
13478    /**
13479     * Assign a size and position to a view and all of its
13480     * descendants
13481     *
13482     * <p>This is the second phase of the layout mechanism.
13483     * (The first is measuring). In this phase, each parent calls
13484     * layout on all of its children to position them.
13485     * This is typically done using the child measurements
13486     * that were stored in the measure pass().</p>
13487     *
13488     * <p>Derived classes should not override this method.
13489     * Derived classes with children should override
13490     * onLayout. In that method, they should
13491     * call layout on each of their children.</p>
13492     *
13493     * @param l Left position, relative to parent
13494     * @param t Top position, relative to parent
13495     * @param r Right position, relative to parent
13496     * @param b Bottom position, relative to parent
13497     */
13498    @SuppressWarnings({"unchecked"})
13499    public void layout(int l, int t, int r, int b) {
13500        int oldL = mLeft;
13501        int oldT = mTop;
13502        int oldB = mBottom;
13503        int oldR = mRight;
13504        boolean changed = setFrame(l, t, r, b);
13505        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13506            if (ViewDebug.TRACE_HIERARCHY) {
13507                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13508            }
13509
13510            onLayout(changed, l, t, r, b);
13511            mPrivateFlags &= ~LAYOUT_REQUIRED;
13512
13513            ListenerInfo li = mListenerInfo;
13514            if (li != null && li.mOnLayoutChangeListeners != null) {
13515                ArrayList<OnLayoutChangeListener> listenersCopy =
13516                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13517                int numListeners = listenersCopy.size();
13518                for (int i = 0; i < numListeners; ++i) {
13519                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13520                }
13521            }
13522        }
13523        mPrivateFlags &= ~FORCE_LAYOUT;
13524    }
13525
13526    /**
13527     * Called from layout when this view should
13528     * assign a size and position to each of its children.
13529     *
13530     * Derived classes with children should override
13531     * this method and call layout on each of
13532     * their children.
13533     * @param changed This is a new size or position for this view
13534     * @param left Left position, relative to parent
13535     * @param top Top position, relative to parent
13536     * @param right Right position, relative to parent
13537     * @param bottom Bottom position, relative to parent
13538     */
13539    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13540    }
13541
13542    /**
13543     * Assign a size and position to this view.
13544     *
13545     * This is called from layout.
13546     *
13547     * @param left Left position, relative to parent
13548     * @param top Top position, relative to parent
13549     * @param right Right position, relative to parent
13550     * @param bottom Bottom position, relative to parent
13551     * @return true if the new size and position are different than the
13552     *         previous ones
13553     * {@hide}
13554     */
13555    protected boolean setFrame(int left, int top, int right, int bottom) {
13556        boolean changed = false;
13557
13558        if (DBG) {
13559            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13560                    + right + "," + bottom + ")");
13561        }
13562
13563        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13564            changed = true;
13565
13566            // Remember our drawn bit
13567            int drawn = mPrivateFlags & DRAWN;
13568
13569            int oldWidth = mRight - mLeft;
13570            int oldHeight = mBottom - mTop;
13571            int newWidth = right - left;
13572            int newHeight = bottom - top;
13573            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13574
13575            // Invalidate our old position
13576            invalidate(sizeChanged);
13577
13578            mLeft = left;
13579            mTop = top;
13580            mRight = right;
13581            mBottom = bottom;
13582            if (mDisplayList != null) {
13583                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13584            }
13585
13586            mPrivateFlags |= HAS_BOUNDS;
13587
13588
13589            if (sizeChanged) {
13590                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13591                    // A change in dimension means an auto-centered pivot point changes, too
13592                    if (mTransformationInfo != null) {
13593                        mTransformationInfo.mMatrixDirty = true;
13594                    }
13595                }
13596                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13597            }
13598
13599            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13600                // If we are visible, force the DRAWN bit to on so that
13601                // this invalidate will go through (at least to our parent).
13602                // This is because someone may have invalidated this view
13603                // before this call to setFrame came in, thereby clearing
13604                // the DRAWN bit.
13605                mPrivateFlags |= DRAWN;
13606                invalidate(sizeChanged);
13607                // parent display list may need to be recreated based on a change in the bounds
13608                // of any child
13609                invalidateParentCaches();
13610            }
13611
13612            // Reset drawn bit to original value (invalidate turns it off)
13613            mPrivateFlags |= drawn;
13614
13615            mBackgroundSizeChanged = true;
13616        }
13617        return changed;
13618    }
13619
13620    /**
13621     * Finalize inflating a view from XML.  This is called as the last phase
13622     * of inflation, after all child views have been added.
13623     *
13624     * <p>Even if the subclass overrides onFinishInflate, they should always be
13625     * sure to call the super method, so that we get called.
13626     */
13627    protected void onFinishInflate() {
13628    }
13629
13630    /**
13631     * Returns the resources associated with this view.
13632     *
13633     * @return Resources object.
13634     */
13635    public Resources getResources() {
13636        return mResources;
13637    }
13638
13639    /**
13640     * Invalidates the specified Drawable.
13641     *
13642     * @param drawable the drawable to invalidate
13643     */
13644    public void invalidateDrawable(Drawable drawable) {
13645        if (verifyDrawable(drawable)) {
13646            final Rect dirty = drawable.getBounds();
13647            final int scrollX = mScrollX;
13648            final int scrollY = mScrollY;
13649
13650            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13651                    dirty.right + scrollX, dirty.bottom + scrollY);
13652        }
13653    }
13654
13655    /**
13656     * Schedules an action on a drawable to occur at a specified time.
13657     *
13658     * @param who the recipient of the action
13659     * @param what the action to run on the drawable
13660     * @param when the time at which the action must occur. Uses the
13661     *        {@link SystemClock#uptimeMillis} timebase.
13662     */
13663    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13664        if (verifyDrawable(who) && what != null) {
13665            final long delay = when - SystemClock.uptimeMillis();
13666            if (mAttachInfo != null) {
13667                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13668                        Choreographer.CALLBACK_ANIMATION, what, who,
13669                        Choreographer.subtractFrameDelay(delay));
13670            } else {
13671                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13672            }
13673        }
13674    }
13675
13676    /**
13677     * Cancels a scheduled action on a drawable.
13678     *
13679     * @param who the recipient of the action
13680     * @param what the action to cancel
13681     */
13682    public void unscheduleDrawable(Drawable who, Runnable what) {
13683        if (verifyDrawable(who) && what != null) {
13684            if (mAttachInfo != null) {
13685                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13686                        Choreographer.CALLBACK_ANIMATION, what, who);
13687            } else {
13688                ViewRootImpl.getRunQueue().removeCallbacks(what);
13689            }
13690        }
13691    }
13692
13693    /**
13694     * Unschedule any events associated with the given Drawable.  This can be
13695     * used when selecting a new Drawable into a view, so that the previous
13696     * one is completely unscheduled.
13697     *
13698     * @param who The Drawable to unschedule.
13699     *
13700     * @see #drawableStateChanged
13701     */
13702    public void unscheduleDrawable(Drawable who) {
13703        if (mAttachInfo != null && who != null) {
13704            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13705                    Choreographer.CALLBACK_ANIMATION, null, who);
13706        }
13707    }
13708
13709    /**
13710    * Return the layout direction of a given Drawable.
13711    *
13712    * @param who the Drawable to query
13713    */
13714    public int getResolvedLayoutDirection(Drawable who) {
13715        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13716    }
13717
13718    /**
13719     * If your view subclass is displaying its own Drawable objects, it should
13720     * override this function and return true for any Drawable it is
13721     * displaying.  This allows animations for those drawables to be
13722     * scheduled.
13723     *
13724     * <p>Be sure to call through to the super class when overriding this
13725     * function.
13726     *
13727     * @param who The Drawable to verify.  Return true if it is one you are
13728     *            displaying, else return the result of calling through to the
13729     *            super class.
13730     *
13731     * @return boolean If true than the Drawable is being displayed in the
13732     *         view; else false and it is not allowed to animate.
13733     *
13734     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13735     * @see #drawableStateChanged()
13736     */
13737    protected boolean verifyDrawable(Drawable who) {
13738        return who == mBackground;
13739    }
13740
13741    /**
13742     * This function is called whenever the state of the view changes in such
13743     * a way that it impacts the state of drawables being shown.
13744     *
13745     * <p>Be sure to call through to the superclass when overriding this
13746     * function.
13747     *
13748     * @see Drawable#setState(int[])
13749     */
13750    protected void drawableStateChanged() {
13751        Drawable d = mBackground;
13752        if (d != null && d.isStateful()) {
13753            d.setState(getDrawableState());
13754        }
13755    }
13756
13757    /**
13758     * Call this to force a view to update its drawable state. This will cause
13759     * drawableStateChanged to be called on this view. Views that are interested
13760     * in the new state should call getDrawableState.
13761     *
13762     * @see #drawableStateChanged
13763     * @see #getDrawableState
13764     */
13765    public void refreshDrawableState() {
13766        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13767        drawableStateChanged();
13768
13769        ViewParent parent = mParent;
13770        if (parent != null) {
13771            parent.childDrawableStateChanged(this);
13772        }
13773    }
13774
13775    /**
13776     * Return an array of resource IDs of the drawable states representing the
13777     * current state of the view.
13778     *
13779     * @return The current drawable state
13780     *
13781     * @see Drawable#setState(int[])
13782     * @see #drawableStateChanged()
13783     * @see #onCreateDrawableState(int)
13784     */
13785    public final int[] getDrawableState() {
13786        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13787            return mDrawableState;
13788        } else {
13789            mDrawableState = onCreateDrawableState(0);
13790            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13791            return mDrawableState;
13792        }
13793    }
13794
13795    /**
13796     * Generate the new {@link android.graphics.drawable.Drawable} state for
13797     * this view. This is called by the view
13798     * system when the cached Drawable state is determined to be invalid.  To
13799     * retrieve the current state, you should use {@link #getDrawableState}.
13800     *
13801     * @param extraSpace if non-zero, this is the number of extra entries you
13802     * would like in the returned array in which you can place your own
13803     * states.
13804     *
13805     * @return Returns an array holding the current {@link Drawable} state of
13806     * the view.
13807     *
13808     * @see #mergeDrawableStates(int[], int[])
13809     */
13810    protected int[] onCreateDrawableState(int extraSpace) {
13811        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13812                mParent instanceof View) {
13813            return ((View) mParent).onCreateDrawableState(extraSpace);
13814        }
13815
13816        int[] drawableState;
13817
13818        int privateFlags = mPrivateFlags;
13819
13820        int viewStateIndex = 0;
13821        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13822        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13823        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13824        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13825        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13826        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13827        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13828                HardwareRenderer.isAvailable()) {
13829            // This is set if HW acceleration is requested, even if the current
13830            // process doesn't allow it.  This is just to allow app preview
13831            // windows to better match their app.
13832            viewStateIndex |= VIEW_STATE_ACCELERATED;
13833        }
13834        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13835
13836        final int privateFlags2 = mPrivateFlags2;
13837        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13838        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13839
13840        drawableState = VIEW_STATE_SETS[viewStateIndex];
13841
13842        //noinspection ConstantIfStatement
13843        if (false) {
13844            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13845            Log.i("View", toString()
13846                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13847                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13848                    + " fo=" + hasFocus()
13849                    + " sl=" + ((privateFlags & SELECTED) != 0)
13850                    + " wf=" + hasWindowFocus()
13851                    + ": " + Arrays.toString(drawableState));
13852        }
13853
13854        if (extraSpace == 0) {
13855            return drawableState;
13856        }
13857
13858        final int[] fullState;
13859        if (drawableState != null) {
13860            fullState = new int[drawableState.length + extraSpace];
13861            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13862        } else {
13863            fullState = new int[extraSpace];
13864        }
13865
13866        return fullState;
13867    }
13868
13869    /**
13870     * Merge your own state values in <var>additionalState</var> into the base
13871     * state values <var>baseState</var> that were returned by
13872     * {@link #onCreateDrawableState(int)}.
13873     *
13874     * @param baseState The base state values returned by
13875     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13876     * own additional state values.
13877     *
13878     * @param additionalState The additional state values you would like
13879     * added to <var>baseState</var>; this array is not modified.
13880     *
13881     * @return As a convenience, the <var>baseState</var> array you originally
13882     * passed into the function is returned.
13883     *
13884     * @see #onCreateDrawableState(int)
13885     */
13886    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13887        final int N = baseState.length;
13888        int i = N - 1;
13889        while (i >= 0 && baseState[i] == 0) {
13890            i--;
13891        }
13892        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13893        return baseState;
13894    }
13895
13896    /**
13897     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13898     * on all Drawable objects associated with this view.
13899     */
13900    public void jumpDrawablesToCurrentState() {
13901        if (mBackground != null) {
13902            mBackground.jumpToCurrentState();
13903        }
13904    }
13905
13906    /**
13907     * Sets the background color for this view.
13908     * @param color the color of the background
13909     */
13910    @RemotableViewMethod
13911    public void setBackgroundColor(int color) {
13912        if (mBackground instanceof ColorDrawable) {
13913            ((ColorDrawable) mBackground).setColor(color);
13914        } else {
13915            setBackground(new ColorDrawable(color));
13916        }
13917    }
13918
13919    /**
13920     * Set the background to a given resource. The resource should refer to
13921     * a Drawable object or 0 to remove the background.
13922     * @param resid The identifier of the resource.
13923     *
13924     * @attr ref android.R.styleable#View_background
13925     */
13926    @RemotableViewMethod
13927    public void setBackgroundResource(int resid) {
13928        if (resid != 0 && resid == mBackgroundResource) {
13929            return;
13930        }
13931
13932        Drawable d= null;
13933        if (resid != 0) {
13934            d = mResources.getDrawable(resid);
13935        }
13936        setBackground(d);
13937
13938        mBackgroundResource = resid;
13939    }
13940
13941    /**
13942     * Set the background to a given Drawable, or remove the background. If the
13943     * background has padding, this View's padding is set to the background's
13944     * padding. However, when a background is removed, this View's padding isn't
13945     * touched. If setting the padding is desired, please use
13946     * {@link #setPadding(int, int, int, int)}.
13947     *
13948     * @param background The Drawable to use as the background, or null to remove the
13949     *        background
13950     */
13951    public void setBackground(Drawable background) {
13952        //noinspection deprecation
13953        setBackgroundDrawable(background);
13954    }
13955
13956    /**
13957     * @deprecated use {@link #setBackground(Drawable)} instead
13958     */
13959    @Deprecated
13960    public void setBackgroundDrawable(Drawable background) {
13961        if (background == mBackground) {
13962            return;
13963        }
13964
13965        boolean requestLayout = false;
13966
13967        mBackgroundResource = 0;
13968
13969        /*
13970         * Regardless of whether we're setting a new background or not, we want
13971         * to clear the previous drawable.
13972         */
13973        if (mBackground != null) {
13974            mBackground.setCallback(null);
13975            unscheduleDrawable(mBackground);
13976        }
13977
13978        if (background != null) {
13979            Rect padding = sThreadLocal.get();
13980            if (padding == null) {
13981                padding = new Rect();
13982                sThreadLocal.set(padding);
13983            }
13984            if (background.getPadding(padding)) {
13985                switch (background.getResolvedLayoutDirectionSelf()) {
13986                    case LAYOUT_DIRECTION_RTL:
13987                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13988                        break;
13989                    case LAYOUT_DIRECTION_LTR:
13990                    default:
13991                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13992                }
13993            }
13994
13995            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13996            // if it has a different minimum size, we should layout again
13997            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13998                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13999                requestLayout = true;
14000            }
14001
14002            background.setCallback(this);
14003            if (background.isStateful()) {
14004                background.setState(getDrawableState());
14005            }
14006            background.setVisible(getVisibility() == VISIBLE, false);
14007            mBackground = background;
14008
14009            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14010                mPrivateFlags &= ~SKIP_DRAW;
14011                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14012                requestLayout = true;
14013            }
14014        } else {
14015            /* Remove the background */
14016            mBackground = null;
14017
14018            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14019                /*
14020                 * This view ONLY drew the background before and we're removing
14021                 * the background, so now it won't draw anything
14022                 * (hence we SKIP_DRAW)
14023                 */
14024                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14025                mPrivateFlags |= SKIP_DRAW;
14026            }
14027
14028            /*
14029             * When the background is set, we try to apply its padding to this
14030             * View. When the background is removed, we don't touch this View's
14031             * padding. This is noted in the Javadocs. Hence, we don't need to
14032             * requestLayout(), the invalidate() below is sufficient.
14033             */
14034
14035            // The old background's minimum size could have affected this
14036            // View's layout, so let's requestLayout
14037            requestLayout = true;
14038        }
14039
14040        computeOpaqueFlags();
14041
14042        if (requestLayout) {
14043            requestLayout();
14044        }
14045
14046        mBackgroundSizeChanged = true;
14047        invalidate(true);
14048    }
14049
14050    /**
14051     * Gets the background drawable
14052     *
14053     * @return The drawable used as the background for this view, if any.
14054     *
14055     * @see #setBackground(Drawable)
14056     *
14057     * @attr ref android.R.styleable#View_background
14058     */
14059    public Drawable getBackground() {
14060        return mBackground;
14061    }
14062
14063    /**
14064     * Sets the padding. The view may add on the space required to display
14065     * the scrollbars, depending on the style and visibility of the scrollbars.
14066     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14067     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14068     * from the values set in this call.
14069     *
14070     * @attr ref android.R.styleable#View_padding
14071     * @attr ref android.R.styleable#View_paddingBottom
14072     * @attr ref android.R.styleable#View_paddingLeft
14073     * @attr ref android.R.styleable#View_paddingRight
14074     * @attr ref android.R.styleable#View_paddingTop
14075     * @param left the left padding in pixels
14076     * @param top the top padding in pixels
14077     * @param right the right padding in pixels
14078     * @param bottom the bottom padding in pixels
14079     */
14080    public void setPadding(int left, int top, int right, int bottom) {
14081        mUserPaddingStart = -1;
14082        mUserPaddingEnd = -1;
14083        mUserPaddingRelative = false;
14084
14085        internalSetPadding(left, top, right, bottom);
14086    }
14087
14088    private void internalSetPadding(int left, int top, int right, int bottom) {
14089        mUserPaddingLeft = left;
14090        mUserPaddingRight = right;
14091        mUserPaddingBottom = bottom;
14092
14093        final int viewFlags = mViewFlags;
14094        boolean changed = false;
14095
14096        // Common case is there are no scroll bars.
14097        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14098            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14099                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14100                        ? 0 : getVerticalScrollbarWidth();
14101                switch (mVerticalScrollbarPosition) {
14102                    case SCROLLBAR_POSITION_DEFAULT:
14103                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14104                            left += offset;
14105                        } else {
14106                            right += offset;
14107                        }
14108                        break;
14109                    case SCROLLBAR_POSITION_RIGHT:
14110                        right += offset;
14111                        break;
14112                    case SCROLLBAR_POSITION_LEFT:
14113                        left += offset;
14114                        break;
14115                }
14116            }
14117            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14118                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14119                        ? 0 : getHorizontalScrollbarHeight();
14120            }
14121        }
14122
14123        if (mPaddingLeft != left) {
14124            changed = true;
14125            mPaddingLeft = left;
14126        }
14127        if (mPaddingTop != top) {
14128            changed = true;
14129            mPaddingTop = top;
14130        }
14131        if (mPaddingRight != right) {
14132            changed = true;
14133            mPaddingRight = right;
14134        }
14135        if (mPaddingBottom != bottom) {
14136            changed = true;
14137            mPaddingBottom = bottom;
14138        }
14139
14140        if (changed) {
14141            requestLayout();
14142        }
14143    }
14144
14145    /**
14146     * Sets the relative padding. The view may add on the space required to display
14147     * the scrollbars, depending on the style and visibility of the scrollbars.
14148     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14149     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14150     * from the values set in this call.
14151     *
14152     * @attr ref android.R.styleable#View_padding
14153     * @attr ref android.R.styleable#View_paddingBottom
14154     * @attr ref android.R.styleable#View_paddingStart
14155     * @attr ref android.R.styleable#View_paddingEnd
14156     * @attr ref android.R.styleable#View_paddingTop
14157     * @param start the start padding in pixels
14158     * @param top the top padding in pixels
14159     * @param end the end padding in pixels
14160     * @param bottom the bottom padding in pixels
14161     */
14162    public void setPaddingRelative(int start, int top, int end, int bottom) {
14163        mUserPaddingStart = start;
14164        mUserPaddingEnd = end;
14165        mUserPaddingRelative = true;
14166
14167        switch(getResolvedLayoutDirection()) {
14168            case LAYOUT_DIRECTION_RTL:
14169                internalSetPadding(end, top, start, bottom);
14170                break;
14171            case LAYOUT_DIRECTION_LTR:
14172            default:
14173                internalSetPadding(start, top, end, bottom);
14174        }
14175    }
14176
14177    /**
14178     * Returns the top padding of this view.
14179     *
14180     * @return the top padding in pixels
14181     */
14182    public int getPaddingTop() {
14183        return mPaddingTop;
14184    }
14185
14186    /**
14187     * Returns the bottom padding of this view. If there are inset and enabled
14188     * scrollbars, this value may include the space required to display the
14189     * scrollbars as well.
14190     *
14191     * @return the bottom padding in pixels
14192     */
14193    public int getPaddingBottom() {
14194        return mPaddingBottom;
14195    }
14196
14197    /**
14198     * Returns the left padding of this view. If there are inset and enabled
14199     * scrollbars, this value may include the space required to display the
14200     * scrollbars as well.
14201     *
14202     * @return the left padding in pixels
14203     */
14204    public int getPaddingLeft() {
14205        return mPaddingLeft;
14206    }
14207
14208    /**
14209     * Returns the start padding of this view depending on its resolved layout direction.
14210     * If there are inset and enabled scrollbars, this value may include the space
14211     * required to display the scrollbars as well.
14212     *
14213     * @return the start padding in pixels
14214     */
14215    public int getPaddingStart() {
14216        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14217                mPaddingRight : mPaddingLeft;
14218    }
14219
14220    /**
14221     * Returns the right padding of this view. If there are inset and enabled
14222     * scrollbars, this value may include the space required to display the
14223     * scrollbars as well.
14224     *
14225     * @return the right padding in pixels
14226     */
14227    public int getPaddingRight() {
14228        return mPaddingRight;
14229    }
14230
14231    /**
14232     * Returns the end padding of this view depending on its resolved layout direction.
14233     * If there are inset and enabled scrollbars, this value may include the space
14234     * required to display the scrollbars as well.
14235     *
14236     * @return the end padding in pixels
14237     */
14238    public int getPaddingEnd() {
14239        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14240                mPaddingLeft : mPaddingRight;
14241    }
14242
14243    /**
14244     * Return if the padding as been set thru relative values
14245     * {@link #setPaddingRelative(int, int, int, int)} or thru
14246     * @attr ref android.R.styleable#View_paddingStart or
14247     * @attr ref android.R.styleable#View_paddingEnd
14248     *
14249     * @return true if the padding is relative or false if it is not.
14250     */
14251    public boolean isPaddingRelative() {
14252        return mUserPaddingRelative;
14253    }
14254
14255    /**
14256     * @hide
14257     */
14258    public Insets getOpticalInsets() {
14259        if (mLayoutInsets == null) {
14260            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14261        }
14262        return mLayoutInsets;
14263    }
14264
14265    /**
14266     * @hide
14267     */
14268    public void setLayoutInsets(Insets layoutInsets) {
14269        mLayoutInsets = layoutInsets;
14270    }
14271
14272    /**
14273     * Changes the selection state of this view. A view can be selected or not.
14274     * Note that selection is not the same as focus. Views are typically
14275     * selected in the context of an AdapterView like ListView or GridView;
14276     * the selected view is the view that is highlighted.
14277     *
14278     * @param selected true if the view must be selected, false otherwise
14279     */
14280    public void setSelected(boolean selected) {
14281        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14282            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14283            if (!selected) resetPressedState();
14284            invalidate(true);
14285            refreshDrawableState();
14286            dispatchSetSelected(selected);
14287            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14288                notifyAccessibilityStateChanged();
14289            }
14290        }
14291    }
14292
14293    /**
14294     * Dispatch setSelected to all of this View's children.
14295     *
14296     * @see #setSelected(boolean)
14297     *
14298     * @param selected The new selected state
14299     */
14300    protected void dispatchSetSelected(boolean selected) {
14301    }
14302
14303    /**
14304     * Indicates the selection state of this view.
14305     *
14306     * @return true if the view is selected, false otherwise
14307     */
14308    @ViewDebug.ExportedProperty
14309    public boolean isSelected() {
14310        return (mPrivateFlags & SELECTED) != 0;
14311    }
14312
14313    /**
14314     * Changes the activated state of this view. A view can be activated or not.
14315     * Note that activation is not the same as selection.  Selection is
14316     * a transient property, representing the view (hierarchy) the user is
14317     * currently interacting with.  Activation is a longer-term state that the
14318     * user can move views in and out of.  For example, in a list view with
14319     * single or multiple selection enabled, the views in the current selection
14320     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14321     * here.)  The activated state is propagated down to children of the view it
14322     * is set on.
14323     *
14324     * @param activated true if the view must be activated, false otherwise
14325     */
14326    public void setActivated(boolean activated) {
14327        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14328            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14329            invalidate(true);
14330            refreshDrawableState();
14331            dispatchSetActivated(activated);
14332        }
14333    }
14334
14335    /**
14336     * Dispatch setActivated to all of this View's children.
14337     *
14338     * @see #setActivated(boolean)
14339     *
14340     * @param activated The new activated state
14341     */
14342    protected void dispatchSetActivated(boolean activated) {
14343    }
14344
14345    /**
14346     * Indicates the activation state of this view.
14347     *
14348     * @return true if the view is activated, false otherwise
14349     */
14350    @ViewDebug.ExportedProperty
14351    public boolean isActivated() {
14352        return (mPrivateFlags & ACTIVATED) != 0;
14353    }
14354
14355    /**
14356     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14357     * observer can be used to get notifications when global events, like
14358     * layout, happen.
14359     *
14360     * The returned ViewTreeObserver observer is not guaranteed to remain
14361     * valid for the lifetime of this View. If the caller of this method keeps
14362     * a long-lived reference to ViewTreeObserver, it should always check for
14363     * the return value of {@link ViewTreeObserver#isAlive()}.
14364     *
14365     * @return The ViewTreeObserver for this view's hierarchy.
14366     */
14367    public ViewTreeObserver getViewTreeObserver() {
14368        if (mAttachInfo != null) {
14369            return mAttachInfo.mTreeObserver;
14370        }
14371        if (mFloatingTreeObserver == null) {
14372            mFloatingTreeObserver = new ViewTreeObserver();
14373        }
14374        return mFloatingTreeObserver;
14375    }
14376
14377    /**
14378     * <p>Finds the topmost view in the current view hierarchy.</p>
14379     *
14380     * @return the topmost view containing this view
14381     */
14382    public View getRootView() {
14383        if (mAttachInfo != null) {
14384            final View v = mAttachInfo.mRootView;
14385            if (v != null) {
14386                return v;
14387            }
14388        }
14389
14390        View parent = this;
14391
14392        while (parent.mParent != null && parent.mParent instanceof View) {
14393            parent = (View) parent.mParent;
14394        }
14395
14396        return parent;
14397    }
14398
14399    /**
14400     * <p>Computes the coordinates of this view on the screen. 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 getLocationOnScreen(int[] location) {
14407        getLocationInWindow(location);
14408
14409        final AttachInfo info = mAttachInfo;
14410        if (info != null) {
14411            location[0] += info.mWindowLeft;
14412            location[1] += info.mWindowTop;
14413        }
14414    }
14415
14416    /**
14417     * <p>Computes the coordinates of this view in its window. The argument
14418     * must be an array of two integers. After the method returns, the array
14419     * contains the x and y location in that order.</p>
14420     *
14421     * @param location an array of two integers in which to hold the coordinates
14422     */
14423    public void getLocationInWindow(int[] location) {
14424        if (location == null || location.length < 2) {
14425            throw new IllegalArgumentException("location must be an array of two integers");
14426        }
14427
14428        if (mAttachInfo == null) {
14429            // When the view is not attached to a window, this method does not make sense
14430            location[0] = location[1] = 0;
14431            return;
14432        }
14433
14434        float[] position = mAttachInfo.mTmpTransformLocation;
14435        position[0] = position[1] = 0.0f;
14436
14437        if (!hasIdentityMatrix()) {
14438            getMatrix().mapPoints(position);
14439        }
14440
14441        position[0] += mLeft;
14442        position[1] += mTop;
14443
14444        ViewParent viewParent = mParent;
14445        while (viewParent instanceof View) {
14446            final View view = (View) viewParent;
14447
14448            position[0] -= view.mScrollX;
14449            position[1] -= view.mScrollY;
14450
14451            if (!view.hasIdentityMatrix()) {
14452                view.getMatrix().mapPoints(position);
14453            }
14454
14455            position[0] += view.mLeft;
14456            position[1] += view.mTop;
14457
14458            viewParent = view.mParent;
14459         }
14460
14461        if (viewParent instanceof ViewRootImpl) {
14462            // *cough*
14463            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14464            position[1] -= vr.mCurScrollY;
14465        }
14466
14467        location[0] = (int) (position[0] + 0.5f);
14468        location[1] = (int) (position[1] + 0.5f);
14469    }
14470
14471    /**
14472     * {@hide}
14473     * @param id the id of the view to be found
14474     * @return the view of the specified id, null if cannot be found
14475     */
14476    protected View findViewTraversal(int id) {
14477        if (id == mID) {
14478            return this;
14479        }
14480        return null;
14481    }
14482
14483    /**
14484     * {@hide}
14485     * @param tag the tag of the view to be found
14486     * @return the view of specified tag, null if cannot be found
14487     */
14488    protected View findViewWithTagTraversal(Object tag) {
14489        if (tag != null && tag.equals(mTag)) {
14490            return this;
14491        }
14492        return null;
14493    }
14494
14495    /**
14496     * {@hide}
14497     * @param predicate The predicate to evaluate.
14498     * @param childToSkip If not null, ignores this child during the recursive traversal.
14499     * @return The first view that matches the predicate or null.
14500     */
14501    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14502        if (predicate.apply(this)) {
14503            return this;
14504        }
14505        return null;
14506    }
14507
14508    /**
14509     * Look for a child view with the given id.  If this view has the given
14510     * id, return this view.
14511     *
14512     * @param id The id to search for.
14513     * @return The view that has the given id in the hierarchy or null
14514     */
14515    public final View findViewById(int id) {
14516        if (id < 0) {
14517            return null;
14518        }
14519        return findViewTraversal(id);
14520    }
14521
14522    /**
14523     * Finds a view by its unuque and stable accessibility id.
14524     *
14525     * @param accessibilityId The searched accessibility id.
14526     * @return The found view.
14527     */
14528    final View findViewByAccessibilityId(int accessibilityId) {
14529        if (accessibilityId < 0) {
14530            return null;
14531        }
14532        return findViewByAccessibilityIdTraversal(accessibilityId);
14533    }
14534
14535    /**
14536     * Performs the traversal to find a view by its unuque and stable accessibility id.
14537     *
14538     * <strong>Note:</strong>This method does not stop at the root namespace
14539     * boundary since the user can touch the screen at an arbitrary location
14540     * potentially crossing the root namespace bounday which will send an
14541     * accessibility event to accessibility services and they should be able
14542     * to obtain the event source. Also accessibility ids are guaranteed to be
14543     * unique in the window.
14544     *
14545     * @param accessibilityId The accessibility id.
14546     * @return The found view.
14547     */
14548    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14549        if (getAccessibilityViewId() == accessibilityId) {
14550            return this;
14551        }
14552        return null;
14553    }
14554
14555    /**
14556     * Look for a child view with the given tag.  If this view has the given
14557     * tag, return this view.
14558     *
14559     * @param tag The tag to search for, using "tag.equals(getTag())".
14560     * @return The View that has the given tag in the hierarchy or null
14561     */
14562    public final View findViewWithTag(Object tag) {
14563        if (tag == null) {
14564            return null;
14565        }
14566        return findViewWithTagTraversal(tag);
14567    }
14568
14569    /**
14570     * {@hide}
14571     * Look for a child view that matches the specified predicate.
14572     * If this view matches the predicate, return this view.
14573     *
14574     * @param predicate The predicate to evaluate.
14575     * @return The first view that matches the predicate or null.
14576     */
14577    public final View findViewByPredicate(Predicate<View> predicate) {
14578        return findViewByPredicateTraversal(predicate, null);
14579    }
14580
14581    /**
14582     * {@hide}
14583     * Look for a child view that matches the specified predicate,
14584     * starting with the specified view and its descendents and then
14585     * recusively searching the ancestors and siblings of that view
14586     * until this view is reached.
14587     *
14588     * This method is useful in cases where the predicate does not match
14589     * a single unique view (perhaps multiple views use the same id)
14590     * and we are trying to find the view that is "closest" in scope to the
14591     * starting view.
14592     *
14593     * @param start The view to start from.
14594     * @param predicate The predicate to evaluate.
14595     * @return The first view that matches the predicate or null.
14596     */
14597    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14598        View childToSkip = null;
14599        for (;;) {
14600            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14601            if (view != null || start == this) {
14602                return view;
14603            }
14604
14605            ViewParent parent = start.getParent();
14606            if (parent == null || !(parent instanceof View)) {
14607                return null;
14608            }
14609
14610            childToSkip = start;
14611            start = (View) parent;
14612        }
14613    }
14614
14615    /**
14616     * Sets the identifier for this view. The identifier does not have to be
14617     * unique in this view's hierarchy. The identifier should be a positive
14618     * number.
14619     *
14620     * @see #NO_ID
14621     * @see #getId()
14622     * @see #findViewById(int)
14623     *
14624     * @param id a number used to identify the view
14625     *
14626     * @attr ref android.R.styleable#View_id
14627     */
14628    public void setId(int id) {
14629        mID = id;
14630    }
14631
14632    /**
14633     * {@hide}
14634     *
14635     * @param isRoot true if the view belongs to the root namespace, false
14636     *        otherwise
14637     */
14638    public void setIsRootNamespace(boolean isRoot) {
14639        if (isRoot) {
14640            mPrivateFlags |= IS_ROOT_NAMESPACE;
14641        } else {
14642            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14643        }
14644    }
14645
14646    /**
14647     * {@hide}
14648     *
14649     * @return true if the view belongs to the root namespace, false otherwise
14650     */
14651    public boolean isRootNamespace() {
14652        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14653    }
14654
14655    /**
14656     * Returns this view's identifier.
14657     *
14658     * @return a positive integer used to identify the view or {@link #NO_ID}
14659     *         if the view has no ID
14660     *
14661     * @see #setId(int)
14662     * @see #findViewById(int)
14663     * @attr ref android.R.styleable#View_id
14664     */
14665    @ViewDebug.CapturedViewProperty
14666    public int getId() {
14667        return mID;
14668    }
14669
14670    /**
14671     * Returns this view's tag.
14672     *
14673     * @return the Object stored in this view as a tag
14674     *
14675     * @see #setTag(Object)
14676     * @see #getTag(int)
14677     */
14678    @ViewDebug.ExportedProperty
14679    public Object getTag() {
14680        return mTag;
14681    }
14682
14683    /**
14684     * Sets the tag associated with this view. A tag can be used to mark
14685     * a view in its hierarchy and does not have to be unique within the
14686     * hierarchy. Tags can also be used to store data within a view without
14687     * resorting to another data structure.
14688     *
14689     * @param tag an Object to tag the view with
14690     *
14691     * @see #getTag()
14692     * @see #setTag(int, Object)
14693     */
14694    public void setTag(final Object tag) {
14695        mTag = tag;
14696    }
14697
14698    /**
14699     * Returns the tag associated with this view and the specified key.
14700     *
14701     * @param key The key identifying the tag
14702     *
14703     * @return the Object stored in this view as a tag
14704     *
14705     * @see #setTag(int, Object)
14706     * @see #getTag()
14707     */
14708    public Object getTag(int key) {
14709        if (mKeyedTags != null) return mKeyedTags.get(key);
14710        return null;
14711    }
14712
14713    /**
14714     * Sets a tag associated with this view and a key. A tag can be used
14715     * to mark a view in its hierarchy and does not have to be unique within
14716     * the hierarchy. Tags can also be used to store data within a view
14717     * without resorting to another data structure.
14718     *
14719     * The specified key should be an id declared in the resources of the
14720     * application to ensure it is unique (see the <a
14721     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14722     * Keys identified as belonging to
14723     * the Android framework or not associated with any package will cause
14724     * an {@link IllegalArgumentException} to be thrown.
14725     *
14726     * @param key The key identifying the tag
14727     * @param tag An Object to tag the view with
14728     *
14729     * @throws IllegalArgumentException If they specified key is not valid
14730     *
14731     * @see #setTag(Object)
14732     * @see #getTag(int)
14733     */
14734    public void setTag(int key, final Object tag) {
14735        // If the package id is 0x00 or 0x01, it's either an undefined package
14736        // or a framework id
14737        if ((key >>> 24) < 2) {
14738            throw new IllegalArgumentException("The key must be an application-specific "
14739                    + "resource id.");
14740        }
14741
14742        setKeyedTag(key, tag);
14743    }
14744
14745    /**
14746     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14747     * framework id.
14748     *
14749     * @hide
14750     */
14751    public void setTagInternal(int key, Object tag) {
14752        if ((key >>> 24) != 0x1) {
14753            throw new IllegalArgumentException("The key must be a framework-specific "
14754                    + "resource id.");
14755        }
14756
14757        setKeyedTag(key, tag);
14758    }
14759
14760    private void setKeyedTag(int key, Object tag) {
14761        if (mKeyedTags == null) {
14762            mKeyedTags = new SparseArray<Object>();
14763        }
14764
14765        mKeyedTags.put(key, tag);
14766    }
14767
14768    /**
14769     * @param consistency The type of consistency. See ViewDebug for more information.
14770     *
14771     * @hide
14772     */
14773    protected boolean dispatchConsistencyCheck(int consistency) {
14774        return onConsistencyCheck(consistency);
14775    }
14776
14777    /**
14778     * Method that subclasses should implement to check their consistency. The type of
14779     * consistency check is indicated by the bit field passed as a parameter.
14780     *
14781     * @param consistency The type of consistency. See ViewDebug for more information.
14782     *
14783     * @throws IllegalStateException if the view is in an inconsistent state.
14784     *
14785     * @hide
14786     */
14787    protected boolean onConsistencyCheck(int consistency) {
14788        boolean result = true;
14789
14790        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14791        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14792
14793        if (checkLayout) {
14794            if (getParent() == null) {
14795                result = false;
14796                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14797                        "View " + this + " does not have a parent.");
14798            }
14799
14800            if (mAttachInfo == null) {
14801                result = false;
14802                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14803                        "View " + this + " is not attached to a window.");
14804            }
14805        }
14806
14807        if (checkDrawing) {
14808            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14809            // from their draw() method
14810
14811            if ((mPrivateFlags & DRAWN) != DRAWN &&
14812                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14813                result = false;
14814                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14815                        "View " + this + " was invalidated but its drawing cache is valid.");
14816            }
14817        }
14818
14819        return result;
14820    }
14821
14822    /**
14823     * Prints information about this view in the log output, with the tag
14824     * {@link #VIEW_LOG_TAG}.
14825     *
14826     * @hide
14827     */
14828    public void debug() {
14829        debug(0);
14830    }
14831
14832    /**
14833     * Prints information about this view in the log output, with the tag
14834     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14835     * indentation defined by the <code>depth</code>.
14836     *
14837     * @param depth the indentation level
14838     *
14839     * @hide
14840     */
14841    protected void debug(int depth) {
14842        String output = debugIndent(depth - 1);
14843
14844        output += "+ " + this;
14845        int id = getId();
14846        if (id != -1) {
14847            output += " (id=" + id + ")";
14848        }
14849        Object tag = getTag();
14850        if (tag != null) {
14851            output += " (tag=" + tag + ")";
14852        }
14853        Log.d(VIEW_LOG_TAG, output);
14854
14855        if ((mPrivateFlags & FOCUSED) != 0) {
14856            output = debugIndent(depth) + " FOCUSED";
14857            Log.d(VIEW_LOG_TAG, output);
14858        }
14859
14860        output = debugIndent(depth);
14861        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14862                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14863                + "} ";
14864        Log.d(VIEW_LOG_TAG, output);
14865
14866        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14867                || mPaddingBottom != 0) {
14868            output = debugIndent(depth);
14869            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14870                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14871            Log.d(VIEW_LOG_TAG, output);
14872        }
14873
14874        output = debugIndent(depth);
14875        output += "mMeasureWidth=" + mMeasuredWidth +
14876                " mMeasureHeight=" + mMeasuredHeight;
14877        Log.d(VIEW_LOG_TAG, output);
14878
14879        output = debugIndent(depth);
14880        if (mLayoutParams == null) {
14881            output += "BAD! no layout params";
14882        } else {
14883            output = mLayoutParams.debug(output);
14884        }
14885        Log.d(VIEW_LOG_TAG, output);
14886
14887        output = debugIndent(depth);
14888        output += "flags={";
14889        output += View.printFlags(mViewFlags);
14890        output += "}";
14891        Log.d(VIEW_LOG_TAG, output);
14892
14893        output = debugIndent(depth);
14894        output += "privateFlags={";
14895        output += View.printPrivateFlags(mPrivateFlags);
14896        output += "}";
14897        Log.d(VIEW_LOG_TAG, output);
14898    }
14899
14900    /**
14901     * Creates a string of whitespaces used for indentation.
14902     *
14903     * @param depth the indentation level
14904     * @return a String containing (depth * 2 + 3) * 2 white spaces
14905     *
14906     * @hide
14907     */
14908    protected static String debugIndent(int depth) {
14909        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14910        for (int i = 0; i < (depth * 2) + 3; i++) {
14911            spaces.append(' ').append(' ');
14912        }
14913        return spaces.toString();
14914    }
14915
14916    /**
14917     * <p>Return the offset of the widget's text baseline from the widget's top
14918     * boundary. If this widget does not support baseline alignment, this
14919     * method returns -1. </p>
14920     *
14921     * @return the offset of the baseline within the widget's bounds or -1
14922     *         if baseline alignment is not supported
14923     */
14924    @ViewDebug.ExportedProperty(category = "layout")
14925    public int getBaseline() {
14926        return -1;
14927    }
14928
14929    /**
14930     * Call this when something has changed which has invalidated the
14931     * layout of this view. This will schedule a layout pass of the view
14932     * tree.
14933     */
14934    public void requestLayout() {
14935        if (ViewDebug.TRACE_HIERARCHY) {
14936            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14937        }
14938
14939        mPrivateFlags |= FORCE_LAYOUT;
14940        mPrivateFlags |= INVALIDATED;
14941
14942        if (mLayoutParams != null) {
14943            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14944        }
14945
14946        if (mParent != null && !mParent.isLayoutRequested()) {
14947            mParent.requestLayout();
14948        }
14949    }
14950
14951    /**
14952     * Forces this view to be laid out during the next layout pass.
14953     * This method does not call requestLayout() or forceLayout()
14954     * on the parent.
14955     */
14956    public void forceLayout() {
14957        mPrivateFlags |= FORCE_LAYOUT;
14958        mPrivateFlags |= INVALIDATED;
14959    }
14960
14961    /**
14962     * <p>
14963     * This is called to find out how big a view should be. The parent
14964     * supplies constraint information in the width and height parameters.
14965     * </p>
14966     *
14967     * <p>
14968     * The actual measurement work of a view is performed in
14969     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14970     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14971     * </p>
14972     *
14973     *
14974     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14975     *        parent
14976     * @param heightMeasureSpec Vertical space requirements as imposed by the
14977     *        parent
14978     *
14979     * @see #onMeasure(int, int)
14980     */
14981    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14982        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14983                widthMeasureSpec != mOldWidthMeasureSpec ||
14984                heightMeasureSpec != mOldHeightMeasureSpec) {
14985
14986            // first clears the measured dimension flag
14987            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14988
14989            if (ViewDebug.TRACE_HIERARCHY) {
14990                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14991            }
14992
14993            // measure ourselves, this should set the measured dimension flag back
14994            onMeasure(widthMeasureSpec, heightMeasureSpec);
14995
14996            // flag not set, setMeasuredDimension() was not invoked, we raise
14997            // an exception to warn the developer
14998            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14999                throw new IllegalStateException("onMeasure() did not set the"
15000                        + " measured dimension by calling"
15001                        + " setMeasuredDimension()");
15002            }
15003
15004            mPrivateFlags |= LAYOUT_REQUIRED;
15005        }
15006
15007        mOldWidthMeasureSpec = widthMeasureSpec;
15008        mOldHeightMeasureSpec = heightMeasureSpec;
15009    }
15010
15011    /**
15012     * <p>
15013     * Measure the view and its content to determine the measured width and the
15014     * measured height. This method is invoked by {@link #measure(int, int)} and
15015     * should be overriden by subclasses to provide accurate and efficient
15016     * measurement of their contents.
15017     * </p>
15018     *
15019     * <p>
15020     * <strong>CONTRACT:</strong> When overriding this method, you
15021     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15022     * measured width and height of this view. Failure to do so will trigger an
15023     * <code>IllegalStateException</code>, thrown by
15024     * {@link #measure(int, int)}. Calling the superclass'
15025     * {@link #onMeasure(int, int)} is a valid use.
15026     * </p>
15027     *
15028     * <p>
15029     * The base class implementation of measure defaults to the background size,
15030     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15031     * override {@link #onMeasure(int, int)} to provide better measurements of
15032     * their content.
15033     * </p>
15034     *
15035     * <p>
15036     * If this method is overridden, it is the subclass's responsibility to make
15037     * sure the measured height and width are at least the view's minimum height
15038     * and width ({@link #getSuggestedMinimumHeight()} and
15039     * {@link #getSuggestedMinimumWidth()}).
15040     * </p>
15041     *
15042     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15043     *                         The requirements are encoded with
15044     *                         {@link android.view.View.MeasureSpec}.
15045     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15046     *                         The requirements are encoded with
15047     *                         {@link android.view.View.MeasureSpec}.
15048     *
15049     * @see #getMeasuredWidth()
15050     * @see #getMeasuredHeight()
15051     * @see #setMeasuredDimension(int, int)
15052     * @see #getSuggestedMinimumHeight()
15053     * @see #getSuggestedMinimumWidth()
15054     * @see android.view.View.MeasureSpec#getMode(int)
15055     * @see android.view.View.MeasureSpec#getSize(int)
15056     */
15057    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15058        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15059                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15060    }
15061
15062    /**
15063     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15064     * measured width and measured height. Failing to do so will trigger an
15065     * exception at measurement time.</p>
15066     *
15067     * @param measuredWidth The measured width of this view.  May be a complex
15068     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15069     * {@link #MEASURED_STATE_TOO_SMALL}.
15070     * @param measuredHeight The measured height of this view.  May be a complex
15071     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15072     * {@link #MEASURED_STATE_TOO_SMALL}.
15073     */
15074    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15075        mMeasuredWidth = measuredWidth;
15076        mMeasuredHeight = measuredHeight;
15077
15078        mPrivateFlags |= MEASURED_DIMENSION_SET;
15079    }
15080
15081    /**
15082     * Merge two states as returned by {@link #getMeasuredState()}.
15083     * @param curState The current state as returned from a view or the result
15084     * of combining multiple views.
15085     * @param newState The new view state to combine.
15086     * @return Returns a new integer reflecting the combination of the two
15087     * states.
15088     */
15089    public static int combineMeasuredStates(int curState, int newState) {
15090        return curState | newState;
15091    }
15092
15093    /**
15094     * Version of {@link #resolveSizeAndState(int, int, int)}
15095     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15096     */
15097    public static int resolveSize(int size, int measureSpec) {
15098        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15099    }
15100
15101    /**
15102     * Utility to reconcile a desired size and state, with constraints imposed
15103     * by a MeasureSpec.  Will take the desired size, unless a different size
15104     * is imposed by the constraints.  The returned value is a compound integer,
15105     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15106     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15107     * size is smaller than the size the view wants to be.
15108     *
15109     * @param size How big the view wants to be
15110     * @param measureSpec Constraints imposed by the parent
15111     * @return Size information bit mask as defined by
15112     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15113     */
15114    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15115        int result = size;
15116        int specMode = MeasureSpec.getMode(measureSpec);
15117        int specSize =  MeasureSpec.getSize(measureSpec);
15118        switch (specMode) {
15119        case MeasureSpec.UNSPECIFIED:
15120            result = size;
15121            break;
15122        case MeasureSpec.AT_MOST:
15123            if (specSize < size) {
15124                result = specSize | MEASURED_STATE_TOO_SMALL;
15125            } else {
15126                result = size;
15127            }
15128            break;
15129        case MeasureSpec.EXACTLY:
15130            result = specSize;
15131            break;
15132        }
15133        return result | (childMeasuredState&MEASURED_STATE_MASK);
15134    }
15135
15136    /**
15137     * Utility to return a default size. Uses the supplied size if the
15138     * MeasureSpec imposed no constraints. Will get larger if allowed
15139     * by the MeasureSpec.
15140     *
15141     * @param size Default size for this view
15142     * @param measureSpec Constraints imposed by the parent
15143     * @return The size this view should be.
15144     */
15145    public static int getDefaultSize(int size, int measureSpec) {
15146        int result = size;
15147        int specMode = MeasureSpec.getMode(measureSpec);
15148        int specSize = MeasureSpec.getSize(measureSpec);
15149
15150        switch (specMode) {
15151        case MeasureSpec.UNSPECIFIED:
15152            result = size;
15153            break;
15154        case MeasureSpec.AT_MOST:
15155        case MeasureSpec.EXACTLY:
15156            result = specSize;
15157            break;
15158        }
15159        return result;
15160    }
15161
15162    /**
15163     * Returns the suggested minimum height that the view should use. This
15164     * returns the maximum of the view's minimum height
15165     * and the background's minimum height
15166     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15167     * <p>
15168     * When being used in {@link #onMeasure(int, int)}, the caller should still
15169     * ensure the returned height is within the requirements of the parent.
15170     *
15171     * @return The suggested minimum height of the view.
15172     */
15173    protected int getSuggestedMinimumHeight() {
15174        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15175
15176    }
15177
15178    /**
15179     * Returns the suggested minimum width that the view should use. This
15180     * returns the maximum of the view's minimum width)
15181     * and the background's minimum width
15182     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15183     * <p>
15184     * When being used in {@link #onMeasure(int, int)}, the caller should still
15185     * ensure the returned width is within the requirements of the parent.
15186     *
15187     * @return The suggested minimum width of the view.
15188     */
15189    protected int getSuggestedMinimumWidth() {
15190        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15191    }
15192
15193    /**
15194     * Returns the minimum height of the view.
15195     *
15196     * @return the minimum height the view will try to be.
15197     *
15198     * @see #setMinimumHeight(int)
15199     *
15200     * @attr ref android.R.styleable#View_minHeight
15201     */
15202    public int getMinimumHeight() {
15203        return mMinHeight;
15204    }
15205
15206    /**
15207     * Sets the minimum height of the view. It is not guaranteed the view will
15208     * be able to achieve this minimum height (for example, if its parent layout
15209     * constrains it with less available height).
15210     *
15211     * @param minHeight The minimum height the view will try to be.
15212     *
15213     * @see #getMinimumHeight()
15214     *
15215     * @attr ref android.R.styleable#View_minHeight
15216     */
15217    public void setMinimumHeight(int minHeight) {
15218        mMinHeight = minHeight;
15219        requestLayout();
15220    }
15221
15222    /**
15223     * Returns the minimum width of the view.
15224     *
15225     * @return the minimum width the view will try to be.
15226     *
15227     * @see #setMinimumWidth(int)
15228     *
15229     * @attr ref android.R.styleable#View_minWidth
15230     */
15231    public int getMinimumWidth() {
15232        return mMinWidth;
15233    }
15234
15235    /**
15236     * Sets the minimum width of the view. It is not guaranteed the view will
15237     * be able to achieve this minimum width (for example, if its parent layout
15238     * constrains it with less available width).
15239     *
15240     * @param minWidth The minimum width the view will try to be.
15241     *
15242     * @see #getMinimumWidth()
15243     *
15244     * @attr ref android.R.styleable#View_minWidth
15245     */
15246    public void setMinimumWidth(int minWidth) {
15247        mMinWidth = minWidth;
15248        requestLayout();
15249
15250    }
15251
15252    /**
15253     * Get the animation currently associated with this view.
15254     *
15255     * @return The animation that is currently playing or
15256     *         scheduled to play for this view.
15257     */
15258    public Animation getAnimation() {
15259        return mCurrentAnimation;
15260    }
15261
15262    /**
15263     * Start the specified animation now.
15264     *
15265     * @param animation the animation to start now
15266     */
15267    public void startAnimation(Animation animation) {
15268        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15269        setAnimation(animation);
15270        invalidateParentCaches();
15271        invalidate(true);
15272    }
15273
15274    /**
15275     * Cancels any animations for this view.
15276     */
15277    public void clearAnimation() {
15278        if (mCurrentAnimation != null) {
15279            mCurrentAnimation.detach();
15280        }
15281        mCurrentAnimation = null;
15282        invalidateParentIfNeeded();
15283    }
15284
15285    /**
15286     * Sets the next animation to play for this view.
15287     * If you want the animation to play immediately, use
15288     * {@link #startAnimation(android.view.animation.Animation)} instead.
15289     * This method provides allows fine-grained
15290     * control over the start time and invalidation, but you
15291     * must make sure that 1) the animation has a start time set, and
15292     * 2) the view's parent (which controls animations on its children)
15293     * will be invalidated when the animation is supposed to
15294     * start.
15295     *
15296     * @param animation The next animation, or null.
15297     */
15298    public void setAnimation(Animation animation) {
15299        mCurrentAnimation = animation;
15300
15301        if (animation != null) {
15302            // If the screen is off assume the animation start time is now instead of
15303            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15304            // would cause the animation to start when the screen turns back on
15305            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15306                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15307                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15308            }
15309            animation.reset();
15310        }
15311    }
15312
15313    /**
15314     * Invoked by a parent ViewGroup to notify the start of the animation
15315     * currently associated with this view. If you override this method,
15316     * always call super.onAnimationStart();
15317     *
15318     * @see #setAnimation(android.view.animation.Animation)
15319     * @see #getAnimation()
15320     */
15321    protected void onAnimationStart() {
15322        mPrivateFlags |= ANIMATION_STARTED;
15323    }
15324
15325    /**
15326     * Invoked by a parent ViewGroup to notify the end of the animation
15327     * currently associated with this view. If you override this method,
15328     * always call super.onAnimationEnd();
15329     *
15330     * @see #setAnimation(android.view.animation.Animation)
15331     * @see #getAnimation()
15332     */
15333    protected void onAnimationEnd() {
15334        mPrivateFlags &= ~ANIMATION_STARTED;
15335    }
15336
15337    /**
15338     * Invoked if there is a Transform that involves alpha. Subclass that can
15339     * draw themselves with the specified alpha should return true, and then
15340     * respect that alpha when their onDraw() is called. If this returns false
15341     * then the view may be redirected to draw into an offscreen buffer to
15342     * fulfill the request, which will look fine, but may be slower than if the
15343     * subclass handles it internally. The default implementation returns false.
15344     *
15345     * @param alpha The alpha (0..255) to apply to the view's drawing
15346     * @return true if the view can draw with the specified alpha.
15347     */
15348    protected boolean onSetAlpha(int alpha) {
15349        return false;
15350    }
15351
15352    /**
15353     * This is used by the RootView to perform an optimization when
15354     * the view hierarchy contains one or several SurfaceView.
15355     * SurfaceView is always considered transparent, but its children are not,
15356     * therefore all View objects remove themselves from the global transparent
15357     * region (passed as a parameter to this function).
15358     *
15359     * @param region The transparent region for this ViewAncestor (window).
15360     *
15361     * @return Returns true if the effective visibility of the view at this
15362     * point is opaque, regardless of the transparent region; returns false
15363     * if it is possible for underlying windows to be seen behind the view.
15364     *
15365     * {@hide}
15366     */
15367    public boolean gatherTransparentRegion(Region region) {
15368        final AttachInfo attachInfo = mAttachInfo;
15369        if (region != null && attachInfo != null) {
15370            final int pflags = mPrivateFlags;
15371            if ((pflags & SKIP_DRAW) == 0) {
15372                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15373                // remove it from the transparent region.
15374                final int[] location = attachInfo.mTransparentLocation;
15375                getLocationInWindow(location);
15376                region.op(location[0], location[1], location[0] + mRight - mLeft,
15377                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15378            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15379                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15380                // exists, so we remove the background drawable's non-transparent
15381                // parts from this transparent region.
15382                applyDrawableToTransparentRegion(mBackground, region);
15383            }
15384        }
15385        return true;
15386    }
15387
15388    /**
15389     * Play a sound effect for this view.
15390     *
15391     * <p>The framework will play sound effects for some built in actions, such as
15392     * clicking, but you may wish to play these effects in your widget,
15393     * for instance, for internal navigation.
15394     *
15395     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15396     * {@link #isSoundEffectsEnabled()} is true.
15397     *
15398     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15399     */
15400    public void playSoundEffect(int soundConstant) {
15401        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15402            return;
15403        }
15404        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15405    }
15406
15407    /**
15408     * BZZZTT!!1!
15409     *
15410     * <p>Provide haptic feedback to the user for this view.
15411     *
15412     * <p>The framework will provide haptic feedback for some built in actions,
15413     * such as long presses, but you may wish to provide feedback for your
15414     * own widget.
15415     *
15416     * <p>The feedback will only be performed if
15417     * {@link #isHapticFeedbackEnabled()} is true.
15418     *
15419     * @param feedbackConstant One of the constants defined in
15420     * {@link HapticFeedbackConstants}
15421     */
15422    public boolean performHapticFeedback(int feedbackConstant) {
15423        return performHapticFeedback(feedbackConstant, 0);
15424    }
15425
15426    /**
15427     * BZZZTT!!1!
15428     *
15429     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15430     *
15431     * @param feedbackConstant One of the constants defined in
15432     * {@link HapticFeedbackConstants}
15433     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15434     */
15435    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15436        if (mAttachInfo == null) {
15437            return false;
15438        }
15439        //noinspection SimplifiableIfStatement
15440        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15441                && !isHapticFeedbackEnabled()) {
15442            return false;
15443        }
15444        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15445                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15446    }
15447
15448    /**
15449     * Request that the visibility of the status bar or other screen/window
15450     * decorations be changed.
15451     *
15452     * <p>This method is used to put the over device UI into temporary modes
15453     * where the user's attention is focused more on the application content,
15454     * by dimming or hiding surrounding system affordances.  This is typically
15455     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15456     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15457     * to be placed behind the action bar (and with these flags other system
15458     * affordances) so that smooth transitions between hiding and showing them
15459     * can be done.
15460     *
15461     * <p>Two representative examples of the use of system UI visibility is
15462     * implementing a content browsing application (like a magazine reader)
15463     * and a video playing application.
15464     *
15465     * <p>The first code shows a typical implementation of a View in a content
15466     * browsing application.  In this implementation, the application goes
15467     * into a content-oriented mode by hiding the status bar and action bar,
15468     * and putting the navigation elements into lights out mode.  The user can
15469     * then interact with content while in this mode.  Such an application should
15470     * provide an easy way for the user to toggle out of the mode (such as to
15471     * check information in the status bar or access notifications).  In the
15472     * implementation here, this is done simply by tapping on the content.
15473     *
15474     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15475     *      content}
15476     *
15477     * <p>This second code sample shows a typical implementation of a View
15478     * in a video playing application.  In this situation, while the video is
15479     * playing the application would like to go into a complete full-screen mode,
15480     * to use as much of the display as possible for the video.  When in this state
15481     * the user can not interact with the application; the system intercepts
15482     * touching on the screen to pop the UI out of full screen mode.  See
15483     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15484     *
15485     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15486     *      content}
15487     *
15488     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15489     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15490     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15491     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15492     */
15493    public void setSystemUiVisibility(int visibility) {
15494        if (visibility != mSystemUiVisibility) {
15495            mSystemUiVisibility = visibility;
15496            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15497                mParent.recomputeViewAttributes(this);
15498            }
15499        }
15500    }
15501
15502    /**
15503     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15504     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15505     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15506     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15507     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15508     */
15509    public int getSystemUiVisibility() {
15510        return mSystemUiVisibility;
15511    }
15512
15513    /**
15514     * Returns the current system UI visibility that is currently set for
15515     * the entire window.  This is the combination of the
15516     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15517     * views in the window.
15518     */
15519    public int getWindowSystemUiVisibility() {
15520        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15521    }
15522
15523    /**
15524     * Override to find out when the window's requested system UI visibility
15525     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15526     * This is different from the callbacks recieved through
15527     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15528     * in that this is only telling you about the local request of the window,
15529     * not the actual values applied by the system.
15530     */
15531    public void onWindowSystemUiVisibilityChanged(int visible) {
15532    }
15533
15534    /**
15535     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15536     * the view hierarchy.
15537     */
15538    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15539        onWindowSystemUiVisibilityChanged(visible);
15540    }
15541
15542    /**
15543     * Set a listener to receive callbacks when the visibility of the system bar changes.
15544     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15545     */
15546    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15547        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15548        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15549            mParent.recomputeViewAttributes(this);
15550        }
15551    }
15552
15553    /**
15554     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15555     * the view hierarchy.
15556     */
15557    public void dispatchSystemUiVisibilityChanged(int visibility) {
15558        ListenerInfo li = mListenerInfo;
15559        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15560            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15561                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15562        }
15563    }
15564
15565    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15566        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15567        if (val != mSystemUiVisibility) {
15568            setSystemUiVisibility(val);
15569            return true;
15570        }
15571        return false;
15572    }
15573
15574    /** @hide */
15575    public void setDisabledSystemUiVisibility(int flags) {
15576        if (mAttachInfo != null) {
15577            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15578                mAttachInfo.mDisabledSystemUiVisibility = flags;
15579                if (mParent != null) {
15580                    mParent.recomputeViewAttributes(this);
15581                }
15582            }
15583        }
15584    }
15585
15586    /**
15587     * Creates an image that the system displays during the drag and drop
15588     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15589     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15590     * appearance as the given View. The default also positions the center of the drag shadow
15591     * directly under the touch point. If no View is provided (the constructor with no parameters
15592     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15593     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15594     * default is an invisible drag shadow.
15595     * <p>
15596     * You are not required to use the View you provide to the constructor as the basis of the
15597     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15598     * anything you want as the drag shadow.
15599     * </p>
15600     * <p>
15601     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15602     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15603     *  size and position of the drag shadow. It uses this data to construct a
15604     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15605     *  so that your application can draw the shadow image in the Canvas.
15606     * </p>
15607     *
15608     * <div class="special reference">
15609     * <h3>Developer Guides</h3>
15610     * <p>For a guide to implementing drag and drop features, read the
15611     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15612     * </div>
15613     */
15614    public static class DragShadowBuilder {
15615        private final WeakReference<View> mView;
15616
15617        /**
15618         * Constructs a shadow image builder based on a View. By default, the resulting drag
15619         * shadow will have the same appearance and dimensions as the View, with the touch point
15620         * over the center of the View.
15621         * @param view A View. Any View in scope can be used.
15622         */
15623        public DragShadowBuilder(View view) {
15624            mView = new WeakReference<View>(view);
15625        }
15626
15627        /**
15628         * Construct a shadow builder object with no associated View.  This
15629         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15630         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15631         * to supply the drag shadow's dimensions and appearance without
15632         * reference to any View object. If they are not overridden, then the result is an
15633         * invisible drag shadow.
15634         */
15635        public DragShadowBuilder() {
15636            mView = new WeakReference<View>(null);
15637        }
15638
15639        /**
15640         * Returns the View object that had been passed to the
15641         * {@link #View.DragShadowBuilder(View)}
15642         * constructor.  If that View parameter was {@code null} or if the
15643         * {@link #View.DragShadowBuilder()}
15644         * constructor was used to instantiate the builder object, this method will return
15645         * null.
15646         *
15647         * @return The View object associate with this builder object.
15648         */
15649        @SuppressWarnings({"JavadocReference"})
15650        final public View getView() {
15651            return mView.get();
15652        }
15653
15654        /**
15655         * Provides the metrics for the shadow image. These include the dimensions of
15656         * the shadow image, and the point within that shadow that should
15657         * be centered under the touch location while dragging.
15658         * <p>
15659         * The default implementation sets the dimensions of the shadow to be the
15660         * same as the dimensions of the View itself and centers the shadow under
15661         * the touch point.
15662         * </p>
15663         *
15664         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15665         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15666         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15667         * image.
15668         *
15669         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15670         * shadow image that should be underneath the touch point during the drag and drop
15671         * operation. Your application must set {@link android.graphics.Point#x} to the
15672         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15673         */
15674        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15675            final View view = mView.get();
15676            if (view != null) {
15677                shadowSize.set(view.getWidth(), view.getHeight());
15678                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15679            } else {
15680                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15681            }
15682        }
15683
15684        /**
15685         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15686         * based on the dimensions it received from the
15687         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15688         *
15689         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15690         */
15691        public void onDrawShadow(Canvas canvas) {
15692            final View view = mView.get();
15693            if (view != null) {
15694                view.draw(canvas);
15695            } else {
15696                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15697            }
15698        }
15699    }
15700
15701    /**
15702     * Starts a drag and drop operation. When your application calls this method, it passes a
15703     * {@link android.view.View.DragShadowBuilder} object to the system. The
15704     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15705     * to get metrics for the drag shadow, and then calls the object's
15706     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15707     * <p>
15708     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15709     *  drag events to all the View objects in your application that are currently visible. It does
15710     *  this either by calling the View object's drag listener (an implementation of
15711     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15712     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15713     *  Both are passed a {@link android.view.DragEvent} object that has a
15714     *  {@link android.view.DragEvent#getAction()} value of
15715     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15716     * </p>
15717     * <p>
15718     * Your application can invoke startDrag() on any attached View object. The View object does not
15719     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15720     * be related to the View the user selected for dragging.
15721     * </p>
15722     * @param data A {@link android.content.ClipData} object pointing to the data to be
15723     * transferred by the drag and drop operation.
15724     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15725     * drag shadow.
15726     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15727     * drop operation. This Object is put into every DragEvent object sent by the system during the
15728     * current drag.
15729     * <p>
15730     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15731     * to the target Views. For example, it can contain flags that differentiate between a
15732     * a copy operation and a move operation.
15733     * </p>
15734     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15735     * so the parameter should be set to 0.
15736     * @return {@code true} if the method completes successfully, or
15737     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15738     * do a drag, and so no drag operation is in progress.
15739     */
15740    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15741            Object myLocalState, int flags) {
15742        if (ViewDebug.DEBUG_DRAG) {
15743            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15744        }
15745        boolean okay = false;
15746
15747        Point shadowSize = new Point();
15748        Point shadowTouchPoint = new Point();
15749        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15750
15751        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15752                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15753            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15754        }
15755
15756        if (ViewDebug.DEBUG_DRAG) {
15757            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15758                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15759        }
15760        Surface surface = new Surface();
15761        try {
15762            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15763                    flags, shadowSize.x, shadowSize.y, surface);
15764            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15765                    + " surface=" + surface);
15766            if (token != null) {
15767                Canvas canvas = surface.lockCanvas(null);
15768                try {
15769                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15770                    shadowBuilder.onDrawShadow(canvas);
15771                } finally {
15772                    surface.unlockCanvasAndPost(canvas);
15773                }
15774
15775                final ViewRootImpl root = getViewRootImpl();
15776
15777                // Cache the local state object for delivery with DragEvents
15778                root.setLocalDragState(myLocalState);
15779
15780                // repurpose 'shadowSize' for the last touch point
15781                root.getLastTouchPoint(shadowSize);
15782
15783                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15784                        shadowSize.x, shadowSize.y,
15785                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15786                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15787
15788                // Off and running!  Release our local surface instance; the drag
15789                // shadow surface is now managed by the system process.
15790                surface.release();
15791            }
15792        } catch (Exception e) {
15793            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15794            surface.destroy();
15795        }
15796
15797        return okay;
15798    }
15799
15800    /**
15801     * Handles drag events sent by the system following a call to
15802     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15803     *<p>
15804     * When the system calls this method, it passes a
15805     * {@link android.view.DragEvent} object. A call to
15806     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15807     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15808     * operation.
15809     * @param event The {@link android.view.DragEvent} sent by the system.
15810     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15811     * in DragEvent, indicating the type of drag event represented by this object.
15812     * @return {@code true} if the method was successful, otherwise {@code false}.
15813     * <p>
15814     *  The method should return {@code true} in response to an action type of
15815     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15816     *  operation.
15817     * </p>
15818     * <p>
15819     *  The method should also return {@code true} in response to an action type of
15820     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15821     *  {@code false} if it didn't.
15822     * </p>
15823     */
15824    public boolean onDragEvent(DragEvent event) {
15825        return false;
15826    }
15827
15828    /**
15829     * Detects if this View is enabled and has a drag event listener.
15830     * If both are true, then it calls the drag event listener with the
15831     * {@link android.view.DragEvent} it received. If the drag event listener returns
15832     * {@code true}, then dispatchDragEvent() returns {@code true}.
15833     * <p>
15834     * For all other cases, the method calls the
15835     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15836     * method and returns its result.
15837     * </p>
15838     * <p>
15839     * This ensures that a drag event is always consumed, even if the View does not have a drag
15840     * event listener. However, if the View has a listener and the listener returns true, then
15841     * onDragEvent() is not called.
15842     * </p>
15843     */
15844    public boolean dispatchDragEvent(DragEvent event) {
15845        //noinspection SimplifiableIfStatement
15846        ListenerInfo li = mListenerInfo;
15847        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15848                && li.mOnDragListener.onDrag(this, event)) {
15849            return true;
15850        }
15851        return onDragEvent(event);
15852    }
15853
15854    boolean canAcceptDrag() {
15855        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15856    }
15857
15858    /**
15859     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15860     * it is ever exposed at all.
15861     * @hide
15862     */
15863    public void onCloseSystemDialogs(String reason) {
15864    }
15865
15866    /**
15867     * Given a Drawable whose bounds have been set to draw into this view,
15868     * update a Region being computed for
15869     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15870     * that any non-transparent parts of the Drawable are removed from the
15871     * given transparent region.
15872     *
15873     * @param dr The Drawable whose transparency is to be applied to the region.
15874     * @param region A Region holding the current transparency information,
15875     * where any parts of the region that are set are considered to be
15876     * transparent.  On return, this region will be modified to have the
15877     * transparency information reduced by the corresponding parts of the
15878     * Drawable that are not transparent.
15879     * {@hide}
15880     */
15881    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15882        if (DBG) {
15883            Log.i("View", "Getting transparent region for: " + this);
15884        }
15885        final Region r = dr.getTransparentRegion();
15886        final Rect db = dr.getBounds();
15887        final AttachInfo attachInfo = mAttachInfo;
15888        if (r != null && attachInfo != null) {
15889            final int w = getRight()-getLeft();
15890            final int h = getBottom()-getTop();
15891            if (db.left > 0) {
15892                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15893                r.op(0, 0, db.left, h, Region.Op.UNION);
15894            }
15895            if (db.right < w) {
15896                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15897                r.op(db.right, 0, w, h, Region.Op.UNION);
15898            }
15899            if (db.top > 0) {
15900                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15901                r.op(0, 0, w, db.top, Region.Op.UNION);
15902            }
15903            if (db.bottom < h) {
15904                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15905                r.op(0, db.bottom, w, h, Region.Op.UNION);
15906            }
15907            final int[] location = attachInfo.mTransparentLocation;
15908            getLocationInWindow(location);
15909            r.translate(location[0], location[1]);
15910            region.op(r, Region.Op.INTERSECT);
15911        } else {
15912            region.op(db, Region.Op.DIFFERENCE);
15913        }
15914    }
15915
15916    private void checkForLongClick(int delayOffset) {
15917        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15918            mHasPerformedLongPress = false;
15919
15920            if (mPendingCheckForLongPress == null) {
15921                mPendingCheckForLongPress = new CheckForLongPress();
15922            }
15923            mPendingCheckForLongPress.rememberWindowAttachCount();
15924            postDelayed(mPendingCheckForLongPress,
15925                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15926        }
15927    }
15928
15929    /**
15930     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15931     * LayoutInflater} class, which provides a full range of options for view inflation.
15932     *
15933     * @param context The Context object for your activity or application.
15934     * @param resource The resource ID to inflate
15935     * @param root A view group that will be the parent.  Used to properly inflate the
15936     * layout_* parameters.
15937     * @see LayoutInflater
15938     */
15939    public static View inflate(Context context, int resource, ViewGroup root) {
15940        LayoutInflater factory = LayoutInflater.from(context);
15941        return factory.inflate(resource, root);
15942    }
15943
15944    /**
15945     * Scroll the view with standard behavior for scrolling beyond the normal
15946     * content boundaries. Views that call this method should override
15947     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15948     * results of an over-scroll operation.
15949     *
15950     * Views can use this method to handle any touch or fling-based scrolling.
15951     *
15952     * @param deltaX Change in X in pixels
15953     * @param deltaY Change in Y in pixels
15954     * @param scrollX Current X scroll value in pixels before applying deltaX
15955     * @param scrollY Current Y scroll value in pixels before applying deltaY
15956     * @param scrollRangeX Maximum content scroll range along the X axis
15957     * @param scrollRangeY Maximum content scroll range along the Y axis
15958     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15959     *          along the X axis.
15960     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15961     *          along the Y axis.
15962     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15963     * @return true if scrolling was clamped to an over-scroll boundary along either
15964     *          axis, false otherwise.
15965     */
15966    @SuppressWarnings({"UnusedParameters"})
15967    protected boolean overScrollBy(int deltaX, int deltaY,
15968            int scrollX, int scrollY,
15969            int scrollRangeX, int scrollRangeY,
15970            int maxOverScrollX, int maxOverScrollY,
15971            boolean isTouchEvent) {
15972        final int overScrollMode = mOverScrollMode;
15973        final boolean canScrollHorizontal =
15974                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15975        final boolean canScrollVertical =
15976                computeVerticalScrollRange() > computeVerticalScrollExtent();
15977        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15978                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15979        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15980                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15981
15982        int newScrollX = scrollX + deltaX;
15983        if (!overScrollHorizontal) {
15984            maxOverScrollX = 0;
15985        }
15986
15987        int newScrollY = scrollY + deltaY;
15988        if (!overScrollVertical) {
15989            maxOverScrollY = 0;
15990        }
15991
15992        // Clamp values if at the limits and record
15993        final int left = -maxOverScrollX;
15994        final int right = maxOverScrollX + scrollRangeX;
15995        final int top = -maxOverScrollY;
15996        final int bottom = maxOverScrollY + scrollRangeY;
15997
15998        boolean clampedX = false;
15999        if (newScrollX > right) {
16000            newScrollX = right;
16001            clampedX = true;
16002        } else if (newScrollX < left) {
16003            newScrollX = left;
16004            clampedX = true;
16005        }
16006
16007        boolean clampedY = false;
16008        if (newScrollY > bottom) {
16009            newScrollY = bottom;
16010            clampedY = true;
16011        } else if (newScrollY < top) {
16012            newScrollY = top;
16013            clampedY = true;
16014        }
16015
16016        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16017
16018        return clampedX || clampedY;
16019    }
16020
16021    /**
16022     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16023     * respond to the results of an over-scroll operation.
16024     *
16025     * @param scrollX New X scroll value in pixels
16026     * @param scrollY New Y scroll value in pixels
16027     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16028     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16029     */
16030    protected void onOverScrolled(int scrollX, int scrollY,
16031            boolean clampedX, boolean clampedY) {
16032        // Intentionally empty.
16033    }
16034
16035    /**
16036     * Returns the over-scroll mode for this view. The result will be
16037     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16038     * (allow over-scrolling only if the view content is larger than the container),
16039     * or {@link #OVER_SCROLL_NEVER}.
16040     *
16041     * @return This view's over-scroll mode.
16042     */
16043    public int getOverScrollMode() {
16044        return mOverScrollMode;
16045    }
16046
16047    /**
16048     * Set the over-scroll mode for this view. Valid over-scroll modes are
16049     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16050     * (allow over-scrolling only if the view content is larger than the container),
16051     * or {@link #OVER_SCROLL_NEVER}.
16052     *
16053     * Setting the over-scroll mode of a view will have an effect only if the
16054     * view is capable of scrolling.
16055     *
16056     * @param overScrollMode The new over-scroll mode for this view.
16057     */
16058    public void setOverScrollMode(int overScrollMode) {
16059        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16060                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16061                overScrollMode != OVER_SCROLL_NEVER) {
16062            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16063        }
16064        mOverScrollMode = overScrollMode;
16065    }
16066
16067    /**
16068     * Gets a scale factor that determines the distance the view should scroll
16069     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16070     * @return The vertical scroll scale factor.
16071     * @hide
16072     */
16073    protected float getVerticalScrollFactor() {
16074        if (mVerticalScrollFactor == 0) {
16075            TypedValue outValue = new TypedValue();
16076            if (!mContext.getTheme().resolveAttribute(
16077                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16078                throw new IllegalStateException(
16079                        "Expected theme to define listPreferredItemHeight.");
16080            }
16081            mVerticalScrollFactor = outValue.getDimension(
16082                    mContext.getResources().getDisplayMetrics());
16083        }
16084        return mVerticalScrollFactor;
16085    }
16086
16087    /**
16088     * Gets a scale factor that determines the distance the view should scroll
16089     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16090     * @return The horizontal scroll scale factor.
16091     * @hide
16092     */
16093    protected float getHorizontalScrollFactor() {
16094        // TODO: Should use something else.
16095        return getVerticalScrollFactor();
16096    }
16097
16098    /**
16099     * Return the value specifying the text direction or policy that was set with
16100     * {@link #setTextDirection(int)}.
16101     *
16102     * @return the defined text direction. It can be one of:
16103     *
16104     * {@link #TEXT_DIRECTION_INHERIT},
16105     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16106     * {@link #TEXT_DIRECTION_ANY_RTL},
16107     * {@link #TEXT_DIRECTION_LTR},
16108     * {@link #TEXT_DIRECTION_RTL},
16109     * {@link #TEXT_DIRECTION_LOCALE}
16110     */
16111    @ViewDebug.ExportedProperty(category = "text", mapping = {
16112            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16113            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16114            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16115            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16116            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16117            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16118    })
16119    public int getTextDirection() {
16120        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16121    }
16122
16123    /**
16124     * Set the text direction.
16125     *
16126     * @param textDirection the direction to set. Should be one of:
16127     *
16128     * {@link #TEXT_DIRECTION_INHERIT},
16129     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16130     * {@link #TEXT_DIRECTION_ANY_RTL},
16131     * {@link #TEXT_DIRECTION_LTR},
16132     * {@link #TEXT_DIRECTION_RTL},
16133     * {@link #TEXT_DIRECTION_LOCALE}
16134     */
16135    public void setTextDirection(int textDirection) {
16136        if (getTextDirection() != textDirection) {
16137            // Reset the current text direction and the resolved one
16138            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16139            resetResolvedTextDirection();
16140            // Set the new text direction
16141            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16142            // Refresh
16143            requestLayout();
16144            invalidate(true);
16145        }
16146    }
16147
16148    /**
16149     * Return the resolved text direction.
16150     *
16151     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16152     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16153     * up the parent chain of the view. if there is no parent, then it will return the default
16154     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16155     *
16156     * @return the resolved text direction. Returns one of:
16157     *
16158     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16159     * {@link #TEXT_DIRECTION_ANY_RTL},
16160     * {@link #TEXT_DIRECTION_LTR},
16161     * {@link #TEXT_DIRECTION_RTL},
16162     * {@link #TEXT_DIRECTION_LOCALE}
16163     */
16164    public int getResolvedTextDirection() {
16165        // The text direction will be resolved only if needed
16166        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16167            resolveTextDirection();
16168        }
16169        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16170    }
16171
16172    /**
16173     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16174     * resolution is done.
16175     */
16176    public void resolveTextDirection() {
16177        // Reset any previous text direction resolution
16178        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16179
16180        if (hasRtlSupport()) {
16181            // Set resolved text direction flag depending on text direction flag
16182            final int textDirection = getTextDirection();
16183            switch(textDirection) {
16184                case TEXT_DIRECTION_INHERIT:
16185                    if (canResolveTextDirection()) {
16186                        ViewGroup viewGroup = ((ViewGroup) mParent);
16187
16188                        // Set current resolved direction to the same value as the parent's one
16189                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16190                        switch (parentResolvedDirection) {
16191                            case TEXT_DIRECTION_FIRST_STRONG:
16192                            case TEXT_DIRECTION_ANY_RTL:
16193                            case TEXT_DIRECTION_LTR:
16194                            case TEXT_DIRECTION_RTL:
16195                            case TEXT_DIRECTION_LOCALE:
16196                                mPrivateFlags2 |=
16197                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16198                                break;
16199                            default:
16200                                // Default resolved direction is "first strong" heuristic
16201                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16202                        }
16203                    } else {
16204                        // We cannot do the resolution if there is no parent, so use the default one
16205                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16206                    }
16207                    break;
16208                case TEXT_DIRECTION_FIRST_STRONG:
16209                case TEXT_DIRECTION_ANY_RTL:
16210                case TEXT_DIRECTION_LTR:
16211                case TEXT_DIRECTION_RTL:
16212                case TEXT_DIRECTION_LOCALE:
16213                    // Resolved direction is the same as text direction
16214                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16215                    break;
16216                default:
16217                    // Default resolved direction is "first strong" heuristic
16218                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16219            }
16220        } else {
16221            // Default resolved direction is "first strong" heuristic
16222            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16223        }
16224
16225        // Set to resolved
16226        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16227        onResolvedTextDirectionChanged();
16228    }
16229
16230    /**
16231     * Called when text direction has been resolved. Subclasses that care about text direction
16232     * resolution should override this method.
16233     *
16234     * The default implementation does nothing.
16235     */
16236    public void onResolvedTextDirectionChanged() {
16237    }
16238
16239    /**
16240     * Check if text direction resolution can be done.
16241     *
16242     * @return true if text direction resolution can be done otherwise return false.
16243     */
16244    public boolean canResolveTextDirection() {
16245        switch (getTextDirection()) {
16246            case TEXT_DIRECTION_INHERIT:
16247                return (mParent != null) && (mParent instanceof ViewGroup);
16248            default:
16249                return true;
16250        }
16251    }
16252
16253    /**
16254     * Reset resolved text direction. Text direction can be resolved with a call to
16255     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16256     * reset is done.
16257     */
16258    public void resetResolvedTextDirection() {
16259        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16260        onResolvedTextDirectionReset();
16261    }
16262
16263    /**
16264     * Called when text direction is reset. Subclasses that care about text direction reset should
16265     * override this method and do a reset of the text direction of their children. The default
16266     * implementation does nothing.
16267     */
16268    public void onResolvedTextDirectionReset() {
16269    }
16270
16271    /**
16272     * Return the value specifying the text alignment or policy that was set with
16273     * {@link #setTextAlignment(int)}.
16274     *
16275     * @return the defined text alignment. It can be one of:
16276     *
16277     * {@link #TEXT_ALIGNMENT_INHERIT},
16278     * {@link #TEXT_ALIGNMENT_GRAVITY},
16279     * {@link #TEXT_ALIGNMENT_CENTER},
16280     * {@link #TEXT_ALIGNMENT_TEXT_START},
16281     * {@link #TEXT_ALIGNMENT_TEXT_END},
16282     * {@link #TEXT_ALIGNMENT_VIEW_START},
16283     * {@link #TEXT_ALIGNMENT_VIEW_END}
16284     */
16285    @ViewDebug.ExportedProperty(category = "text", mapping = {
16286            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16287            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16288            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16289            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16290            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16291            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16292            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16293    })
16294    public int getTextAlignment() {
16295        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16296    }
16297
16298    /**
16299     * Set the text alignment.
16300     *
16301     * @param textAlignment The text alignment to set. Should be one of
16302     *
16303     * {@link #TEXT_ALIGNMENT_INHERIT},
16304     * {@link #TEXT_ALIGNMENT_GRAVITY},
16305     * {@link #TEXT_ALIGNMENT_CENTER},
16306     * {@link #TEXT_ALIGNMENT_TEXT_START},
16307     * {@link #TEXT_ALIGNMENT_TEXT_END},
16308     * {@link #TEXT_ALIGNMENT_VIEW_START},
16309     * {@link #TEXT_ALIGNMENT_VIEW_END}
16310     *
16311     * @attr ref android.R.styleable#View_textAlignment
16312     */
16313    public void setTextAlignment(int textAlignment) {
16314        if (textAlignment != getTextAlignment()) {
16315            // Reset the current and resolved text alignment
16316            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16317            resetResolvedTextAlignment();
16318            // Set the new text alignment
16319            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16320            // Refresh
16321            requestLayout();
16322            invalidate(true);
16323        }
16324    }
16325
16326    /**
16327     * Return the resolved text alignment.
16328     *
16329     * The resolved text alignment. This needs resolution if the value is
16330     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16331     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16332     *
16333     * @return the resolved text alignment. Returns one of:
16334     *
16335     * {@link #TEXT_ALIGNMENT_GRAVITY},
16336     * {@link #TEXT_ALIGNMENT_CENTER},
16337     * {@link #TEXT_ALIGNMENT_TEXT_START},
16338     * {@link #TEXT_ALIGNMENT_TEXT_END},
16339     * {@link #TEXT_ALIGNMENT_VIEW_START},
16340     * {@link #TEXT_ALIGNMENT_VIEW_END}
16341     */
16342    @ViewDebug.ExportedProperty(category = "text", mapping = {
16343            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16344            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16345            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16346            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16347            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16348            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16349            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16350    })
16351    public int getResolvedTextAlignment() {
16352        // If text alignment is not resolved, then resolve it
16353        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16354            resolveTextAlignment();
16355        }
16356        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16357    }
16358
16359    /**
16360     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16361     * resolution is done.
16362     */
16363    public void resolveTextAlignment() {
16364        // Reset any previous text alignment resolution
16365        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16366
16367        if (hasRtlSupport()) {
16368            // Set resolved text alignment flag depending on text alignment flag
16369            final int textAlignment = getTextAlignment();
16370            switch (textAlignment) {
16371                case TEXT_ALIGNMENT_INHERIT:
16372                    // Check if we can resolve the text alignment
16373                    if (canResolveLayoutDirection() && mParent instanceof View) {
16374                        View view = (View) mParent;
16375
16376                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16377                        switch (parentResolvedTextAlignment) {
16378                            case TEXT_ALIGNMENT_GRAVITY:
16379                            case TEXT_ALIGNMENT_TEXT_START:
16380                            case TEXT_ALIGNMENT_TEXT_END:
16381                            case TEXT_ALIGNMENT_CENTER:
16382                            case TEXT_ALIGNMENT_VIEW_START:
16383                            case TEXT_ALIGNMENT_VIEW_END:
16384                                // Resolved text alignment is the same as the parent resolved
16385                                // text alignment
16386                                mPrivateFlags2 |=
16387                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16388                                break;
16389                            default:
16390                                // Use default resolved text alignment
16391                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16392                        }
16393                    }
16394                    else {
16395                        // We cannot do the resolution if there is no parent so use the default
16396                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16397                    }
16398                    break;
16399                case TEXT_ALIGNMENT_GRAVITY:
16400                case TEXT_ALIGNMENT_TEXT_START:
16401                case TEXT_ALIGNMENT_TEXT_END:
16402                case TEXT_ALIGNMENT_CENTER:
16403                case TEXT_ALIGNMENT_VIEW_START:
16404                case TEXT_ALIGNMENT_VIEW_END:
16405                    // Resolved text alignment is the same as text alignment
16406                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16407                    break;
16408                default:
16409                    // Use default resolved text alignment
16410                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16411            }
16412        } else {
16413            // Use default resolved text alignment
16414            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16415        }
16416
16417        // Set the resolved
16418        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16419        onResolvedTextAlignmentChanged();
16420    }
16421
16422    /**
16423     * Check if text alignment resolution can be done.
16424     *
16425     * @return true if text alignment resolution can be done otherwise return false.
16426     */
16427    public boolean canResolveTextAlignment() {
16428        switch (getTextAlignment()) {
16429            case TEXT_DIRECTION_INHERIT:
16430                return (mParent != null);
16431            default:
16432                return true;
16433        }
16434    }
16435
16436    /**
16437     * Called when text alignment has been resolved. Subclasses that care about text alignment
16438     * resolution should override this method.
16439     *
16440     * The default implementation does nothing.
16441     */
16442    public void onResolvedTextAlignmentChanged() {
16443    }
16444
16445    /**
16446     * Reset resolved text alignment. Text alignment can be resolved with a call to
16447     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16448     * reset is done.
16449     */
16450    public void resetResolvedTextAlignment() {
16451        // Reset any previous text alignment resolution
16452        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16453        onResolvedTextAlignmentReset();
16454    }
16455
16456    /**
16457     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16458     * override this method and do a reset of the text alignment of their children. The default
16459     * implementation does nothing.
16460     */
16461    public void onResolvedTextAlignmentReset() {
16462    }
16463
16464    //
16465    // Properties
16466    //
16467    /**
16468     * A Property wrapper around the <code>alpha</code> functionality handled by the
16469     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16470     */
16471    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16472        @Override
16473        public void setValue(View object, float value) {
16474            object.setAlpha(value);
16475        }
16476
16477        @Override
16478        public Float get(View object) {
16479            return object.getAlpha();
16480        }
16481    };
16482
16483    /**
16484     * A Property wrapper around the <code>translationX</code> functionality handled by the
16485     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16486     */
16487    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16488        @Override
16489        public void setValue(View object, float value) {
16490            object.setTranslationX(value);
16491        }
16492
16493                @Override
16494        public Float get(View object) {
16495            return object.getTranslationX();
16496        }
16497    };
16498
16499    /**
16500     * A Property wrapper around the <code>translationY</code> functionality handled by the
16501     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16502     */
16503    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16504        @Override
16505        public void setValue(View object, float value) {
16506            object.setTranslationY(value);
16507        }
16508
16509        @Override
16510        public Float get(View object) {
16511            return object.getTranslationY();
16512        }
16513    };
16514
16515    /**
16516     * A Property wrapper around the <code>x</code> functionality handled by the
16517     * {@link View#setX(float)} and {@link View#getX()} methods.
16518     */
16519    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16520        @Override
16521        public void setValue(View object, float value) {
16522            object.setX(value);
16523        }
16524
16525        @Override
16526        public Float get(View object) {
16527            return object.getX();
16528        }
16529    };
16530
16531    /**
16532     * A Property wrapper around the <code>y</code> functionality handled by the
16533     * {@link View#setY(float)} and {@link View#getY()} methods.
16534     */
16535    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16536        @Override
16537        public void setValue(View object, float value) {
16538            object.setY(value);
16539        }
16540
16541        @Override
16542        public Float get(View object) {
16543            return object.getY();
16544        }
16545    };
16546
16547    /**
16548     * A Property wrapper around the <code>rotation</code> functionality handled by the
16549     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16550     */
16551    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16552        @Override
16553        public void setValue(View object, float value) {
16554            object.setRotation(value);
16555        }
16556
16557        @Override
16558        public Float get(View object) {
16559            return object.getRotation();
16560        }
16561    };
16562
16563    /**
16564     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16565     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16566     */
16567    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16568        @Override
16569        public void setValue(View object, float value) {
16570            object.setRotationX(value);
16571        }
16572
16573        @Override
16574        public Float get(View object) {
16575            return object.getRotationX();
16576        }
16577    };
16578
16579    /**
16580     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16581     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16582     */
16583    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16584        @Override
16585        public void setValue(View object, float value) {
16586            object.setRotationY(value);
16587        }
16588
16589        @Override
16590        public Float get(View object) {
16591            return object.getRotationY();
16592        }
16593    };
16594
16595    /**
16596     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16597     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16598     */
16599    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16600        @Override
16601        public void setValue(View object, float value) {
16602            object.setScaleX(value);
16603        }
16604
16605        @Override
16606        public Float get(View object) {
16607            return object.getScaleX();
16608        }
16609    };
16610
16611    /**
16612     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16613     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16614     */
16615    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16616        @Override
16617        public void setValue(View object, float value) {
16618            object.setScaleY(value);
16619        }
16620
16621        @Override
16622        public Float get(View object) {
16623            return object.getScaleY();
16624        }
16625    };
16626
16627    /**
16628     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16629     * Each MeasureSpec represents a requirement for either the width or the height.
16630     * A MeasureSpec is comprised of a size and a mode. There are three possible
16631     * modes:
16632     * <dl>
16633     * <dt>UNSPECIFIED</dt>
16634     * <dd>
16635     * The parent has not imposed any constraint on the child. It can be whatever size
16636     * it wants.
16637     * </dd>
16638     *
16639     * <dt>EXACTLY</dt>
16640     * <dd>
16641     * The parent has determined an exact size for the child. The child is going to be
16642     * given those bounds regardless of how big it wants to be.
16643     * </dd>
16644     *
16645     * <dt>AT_MOST</dt>
16646     * <dd>
16647     * The child can be as large as it wants up to the specified size.
16648     * </dd>
16649     * </dl>
16650     *
16651     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16652     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16653     */
16654    public static class MeasureSpec {
16655        private static final int MODE_SHIFT = 30;
16656        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16657
16658        /**
16659         * Measure specification mode: The parent has not imposed any constraint
16660         * on the child. It can be whatever size it wants.
16661         */
16662        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16663
16664        /**
16665         * Measure specification mode: The parent has determined an exact size
16666         * for the child. The child is going to be given those bounds regardless
16667         * of how big it wants to be.
16668         */
16669        public static final int EXACTLY     = 1 << MODE_SHIFT;
16670
16671        /**
16672         * Measure specification mode: The child can be as large as it wants up
16673         * to the specified size.
16674         */
16675        public static final int AT_MOST     = 2 << MODE_SHIFT;
16676
16677        /**
16678         * Creates a measure specification based on the supplied size and mode.
16679         *
16680         * The mode must always be one of the following:
16681         * <ul>
16682         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16683         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16684         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16685         * </ul>
16686         *
16687         * @param size the size of the measure specification
16688         * @param mode the mode of the measure specification
16689         * @return the measure specification based on size and mode
16690         */
16691        public static int makeMeasureSpec(int size, int mode) {
16692            return size + mode;
16693        }
16694
16695        /**
16696         * Extracts the mode from the supplied measure specification.
16697         *
16698         * @param measureSpec the measure specification to extract the mode from
16699         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16700         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16701         *         {@link android.view.View.MeasureSpec#EXACTLY}
16702         */
16703        public static int getMode(int measureSpec) {
16704            return (measureSpec & MODE_MASK);
16705        }
16706
16707        /**
16708         * Extracts the size from the supplied measure specification.
16709         *
16710         * @param measureSpec the measure specification to extract the size from
16711         * @return the size in pixels defined in the supplied measure specification
16712         */
16713        public static int getSize(int measureSpec) {
16714            return (measureSpec & ~MODE_MASK);
16715        }
16716
16717        /**
16718         * Returns a String representation of the specified measure
16719         * specification.
16720         *
16721         * @param measureSpec the measure specification to convert to a String
16722         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16723         */
16724        public static String toString(int measureSpec) {
16725            int mode = getMode(measureSpec);
16726            int size = getSize(measureSpec);
16727
16728            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16729
16730            if (mode == UNSPECIFIED)
16731                sb.append("UNSPECIFIED ");
16732            else if (mode == EXACTLY)
16733                sb.append("EXACTLY ");
16734            else if (mode == AT_MOST)
16735                sb.append("AT_MOST ");
16736            else
16737                sb.append(mode).append(" ");
16738
16739            sb.append(size);
16740            return sb.toString();
16741        }
16742    }
16743
16744    class CheckForLongPress implements Runnable {
16745
16746        private int mOriginalWindowAttachCount;
16747
16748        public void run() {
16749            if (isPressed() && (mParent != null)
16750                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16751                if (performLongClick()) {
16752                    mHasPerformedLongPress = true;
16753                }
16754            }
16755        }
16756
16757        public void rememberWindowAttachCount() {
16758            mOriginalWindowAttachCount = mWindowAttachCount;
16759        }
16760    }
16761
16762    private final class CheckForTap implements Runnable {
16763        public void run() {
16764            mPrivateFlags &= ~PREPRESSED;
16765            setPressed(true);
16766            checkForLongClick(ViewConfiguration.getTapTimeout());
16767        }
16768    }
16769
16770    private final class PerformClick implements Runnable {
16771        public void run() {
16772            performClick();
16773        }
16774    }
16775
16776    /** @hide */
16777    public void hackTurnOffWindowResizeAnim(boolean off) {
16778        mAttachInfo.mTurnOffWindowResizeAnim = off;
16779    }
16780
16781    /**
16782     * This method returns a ViewPropertyAnimator object, which can be used to animate
16783     * specific properties on this View.
16784     *
16785     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16786     */
16787    public ViewPropertyAnimator animate() {
16788        if (mAnimator == null) {
16789            mAnimator = new ViewPropertyAnimator(this);
16790        }
16791        return mAnimator;
16792    }
16793
16794    /**
16795     * Interface definition for a callback to be invoked when a key event is
16796     * dispatched to this view. The callback will be invoked before the key
16797     * event is given to the view.
16798     */
16799    public interface OnKeyListener {
16800        /**
16801         * Called when a key is dispatched to a view. This allows listeners to
16802         * get a chance to respond before the target view.
16803         *
16804         * @param v The view the key has been dispatched to.
16805         * @param keyCode The code for the physical key that was pressed
16806         * @param event The KeyEvent object containing full information about
16807         *        the event.
16808         * @return True if the listener has consumed the event, false otherwise.
16809         */
16810        boolean onKey(View v, int keyCode, KeyEvent event);
16811    }
16812
16813    /**
16814     * Interface definition for a callback to be invoked when a touch event is
16815     * dispatched to this view. The callback will be invoked before the touch
16816     * event is given to the view.
16817     */
16818    public interface OnTouchListener {
16819        /**
16820         * Called when a touch event is dispatched to a view. This allows listeners to
16821         * get a chance to respond before the target view.
16822         *
16823         * @param v The view the touch event has been dispatched to.
16824         * @param event The MotionEvent object containing full information about
16825         *        the event.
16826         * @return True if the listener has consumed the event, false otherwise.
16827         */
16828        boolean onTouch(View v, MotionEvent event);
16829    }
16830
16831    /**
16832     * Interface definition for a callback to be invoked when a hover event is
16833     * dispatched to this view. The callback will be invoked before the hover
16834     * event is given to the view.
16835     */
16836    public interface OnHoverListener {
16837        /**
16838         * Called when a hover event is dispatched to a view. This allows listeners to
16839         * get a chance to respond before the target view.
16840         *
16841         * @param v The view the hover event has been dispatched to.
16842         * @param event The MotionEvent object containing full information about
16843         *        the event.
16844         * @return True if the listener has consumed the event, false otherwise.
16845         */
16846        boolean onHover(View v, MotionEvent event);
16847    }
16848
16849    /**
16850     * Interface definition for a callback to be invoked when a generic motion event is
16851     * dispatched to this view. The callback will be invoked before the generic motion
16852     * event is given to the view.
16853     */
16854    public interface OnGenericMotionListener {
16855        /**
16856         * Called when a generic motion event is dispatched to a view. This allows listeners to
16857         * get a chance to respond before the target view.
16858         *
16859         * @param v The view the generic motion event has been dispatched to.
16860         * @param event The MotionEvent object containing full information about
16861         *        the event.
16862         * @return True if the listener has consumed the event, false otherwise.
16863         */
16864        boolean onGenericMotion(View v, MotionEvent event);
16865    }
16866
16867    /**
16868     * Interface definition for a callback to be invoked when a view has been clicked and held.
16869     */
16870    public interface OnLongClickListener {
16871        /**
16872         * Called when a view has been clicked and held.
16873         *
16874         * @param v The view that was clicked and held.
16875         *
16876         * @return true if the callback consumed the long click, false otherwise.
16877         */
16878        boolean onLongClick(View v);
16879    }
16880
16881    /**
16882     * Interface definition for a callback to be invoked when a drag is being dispatched
16883     * to this view.  The callback will be invoked before the hosting view's own
16884     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16885     * onDrag(event) behavior, it should return 'false' from this callback.
16886     *
16887     * <div class="special reference">
16888     * <h3>Developer Guides</h3>
16889     * <p>For a guide to implementing drag and drop features, read the
16890     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16891     * </div>
16892     */
16893    public interface OnDragListener {
16894        /**
16895         * Called when a drag event is dispatched to a view. This allows listeners
16896         * to get a chance to override base View behavior.
16897         *
16898         * @param v The View that received the drag event.
16899         * @param event The {@link android.view.DragEvent} object for the drag event.
16900         * @return {@code true} if the drag event was handled successfully, or {@code false}
16901         * if the drag event was not handled. Note that {@code false} will trigger the View
16902         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16903         */
16904        boolean onDrag(View v, DragEvent event);
16905    }
16906
16907    /**
16908     * Interface definition for a callback to be invoked when the focus state of
16909     * a view changed.
16910     */
16911    public interface OnFocusChangeListener {
16912        /**
16913         * Called when the focus state of a view has changed.
16914         *
16915         * @param v The view whose state has changed.
16916         * @param hasFocus The new focus state of v.
16917         */
16918        void onFocusChange(View v, boolean hasFocus);
16919    }
16920
16921    /**
16922     * Interface definition for a callback to be invoked when a view is clicked.
16923     */
16924    public interface OnClickListener {
16925        /**
16926         * Called when a view has been clicked.
16927         *
16928         * @param v The view that was clicked.
16929         */
16930        void onClick(View v);
16931    }
16932
16933    /**
16934     * Interface definition for a callback to be invoked when the context menu
16935     * for this view is being built.
16936     */
16937    public interface OnCreateContextMenuListener {
16938        /**
16939         * Called when the context menu for this view is being built. It is not
16940         * safe to hold onto the menu after this method returns.
16941         *
16942         * @param menu The context menu that is being built
16943         * @param v The view for which the context menu is being built
16944         * @param menuInfo Extra information about the item for which the
16945         *            context menu should be shown. This information will vary
16946         *            depending on the class of v.
16947         */
16948        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16949    }
16950
16951    /**
16952     * Interface definition for a callback to be invoked when the status bar changes
16953     * visibility.  This reports <strong>global</strong> changes to the system UI
16954     * state, not what the application is requesting.
16955     *
16956     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16957     */
16958    public interface OnSystemUiVisibilityChangeListener {
16959        /**
16960         * Called when the status bar changes visibility because of a call to
16961         * {@link View#setSystemUiVisibility(int)}.
16962         *
16963         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16964         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
16965         * This tells you the <strong>global</strong> state of these UI visibility
16966         * flags, not what your app is currently applying.
16967         */
16968        public void onSystemUiVisibilityChange(int visibility);
16969    }
16970
16971    /**
16972     * Interface definition for a callback to be invoked when this view is attached
16973     * or detached from its window.
16974     */
16975    public interface OnAttachStateChangeListener {
16976        /**
16977         * Called when the view is attached to a window.
16978         * @param v The view that was attached
16979         */
16980        public void onViewAttachedToWindow(View v);
16981        /**
16982         * Called when the view is detached from a window.
16983         * @param v The view that was detached
16984         */
16985        public void onViewDetachedFromWindow(View v);
16986    }
16987
16988    private final class UnsetPressedState implements Runnable {
16989        public void run() {
16990            setPressed(false);
16991        }
16992    }
16993
16994    /**
16995     * Base class for derived classes that want to save and restore their own
16996     * state in {@link android.view.View#onSaveInstanceState()}.
16997     */
16998    public static class BaseSavedState extends AbsSavedState {
16999        /**
17000         * Constructor used when reading from a parcel. Reads the state of the superclass.
17001         *
17002         * @param source
17003         */
17004        public BaseSavedState(Parcel source) {
17005            super(source);
17006        }
17007
17008        /**
17009         * Constructor called by derived classes when creating their SavedState objects
17010         *
17011         * @param superState The state of the superclass of this view
17012         */
17013        public BaseSavedState(Parcelable superState) {
17014            super(superState);
17015        }
17016
17017        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17018                new Parcelable.Creator<BaseSavedState>() {
17019            public BaseSavedState createFromParcel(Parcel in) {
17020                return new BaseSavedState(in);
17021            }
17022
17023            public BaseSavedState[] newArray(int size) {
17024                return new BaseSavedState[size];
17025            }
17026        };
17027    }
17028
17029    /**
17030     * A set of information given to a view when it is attached to its parent
17031     * window.
17032     */
17033    static class AttachInfo {
17034        interface Callbacks {
17035            void playSoundEffect(int effectId);
17036            boolean performHapticFeedback(int effectId, boolean always);
17037        }
17038
17039        /**
17040         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17041         * to a Handler. This class contains the target (View) to invalidate and
17042         * the coordinates of the dirty rectangle.
17043         *
17044         * For performance purposes, this class also implements a pool of up to
17045         * POOL_LIMIT objects that get reused. This reduces memory allocations
17046         * whenever possible.
17047         */
17048        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17049            private static final int POOL_LIMIT = 10;
17050            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17051                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17052                        public InvalidateInfo newInstance() {
17053                            return new InvalidateInfo();
17054                        }
17055
17056                        public void onAcquired(InvalidateInfo element) {
17057                        }
17058
17059                        public void onReleased(InvalidateInfo element) {
17060                            element.target = null;
17061                        }
17062                    }, POOL_LIMIT)
17063            );
17064
17065            private InvalidateInfo mNext;
17066            private boolean mIsPooled;
17067
17068            View target;
17069
17070            int left;
17071            int top;
17072            int right;
17073            int bottom;
17074
17075            public void setNextPoolable(InvalidateInfo element) {
17076                mNext = element;
17077            }
17078
17079            public InvalidateInfo getNextPoolable() {
17080                return mNext;
17081            }
17082
17083            static InvalidateInfo acquire() {
17084                return sPool.acquire();
17085            }
17086
17087            void release() {
17088                sPool.release(this);
17089            }
17090
17091            public boolean isPooled() {
17092                return mIsPooled;
17093            }
17094
17095            public void setPooled(boolean isPooled) {
17096                mIsPooled = isPooled;
17097            }
17098        }
17099
17100        final IWindowSession mSession;
17101
17102        final IWindow mWindow;
17103
17104        final IBinder mWindowToken;
17105
17106        final Callbacks mRootCallbacks;
17107
17108        HardwareCanvas mHardwareCanvas;
17109
17110        /**
17111         * The top view of the hierarchy.
17112         */
17113        View mRootView;
17114
17115        IBinder mPanelParentWindowToken;
17116        Surface mSurface;
17117
17118        boolean mHardwareAccelerated;
17119        boolean mHardwareAccelerationRequested;
17120        HardwareRenderer mHardwareRenderer;
17121
17122        boolean mScreenOn;
17123
17124        /**
17125         * Scale factor used by the compatibility mode
17126         */
17127        float mApplicationScale;
17128
17129        /**
17130         * Indicates whether the application is in compatibility mode
17131         */
17132        boolean mScalingRequired;
17133
17134        /**
17135         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17136         */
17137        boolean mTurnOffWindowResizeAnim;
17138
17139        /**
17140         * Left position of this view's window
17141         */
17142        int mWindowLeft;
17143
17144        /**
17145         * Top position of this view's window
17146         */
17147        int mWindowTop;
17148
17149        /**
17150         * Indicates whether views need to use 32-bit drawing caches
17151         */
17152        boolean mUse32BitDrawingCache;
17153
17154        /**
17155         * For windows that are full-screen but using insets to layout inside
17156         * of the screen decorations, these are the current insets for the
17157         * content of the window.
17158         */
17159        final Rect mContentInsets = new Rect();
17160
17161        /**
17162         * For windows that are full-screen but using insets to layout inside
17163         * of the screen decorations, these are the current insets for the
17164         * actual visible parts of the window.
17165         */
17166        final Rect mVisibleInsets = new Rect();
17167
17168        /**
17169         * The internal insets given by this window.  This value is
17170         * supplied by the client (through
17171         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17172         * be given to the window manager when changed to be used in laying
17173         * out windows behind it.
17174         */
17175        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17176                = new ViewTreeObserver.InternalInsetsInfo();
17177
17178        /**
17179         * All views in the window's hierarchy that serve as scroll containers,
17180         * used to determine if the window can be resized or must be panned
17181         * to adjust for a soft input area.
17182         */
17183        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17184
17185        final KeyEvent.DispatcherState mKeyDispatchState
17186                = new KeyEvent.DispatcherState();
17187
17188        /**
17189         * Indicates whether the view's window currently has the focus.
17190         */
17191        boolean mHasWindowFocus;
17192
17193        /**
17194         * The current visibility of the window.
17195         */
17196        int mWindowVisibility;
17197
17198        /**
17199         * Indicates the time at which drawing started to occur.
17200         */
17201        long mDrawingTime;
17202
17203        /**
17204         * Indicates whether or not ignoring the DIRTY_MASK flags.
17205         */
17206        boolean mIgnoreDirtyState;
17207
17208        /**
17209         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17210         * to avoid clearing that flag prematurely.
17211         */
17212        boolean mSetIgnoreDirtyState = false;
17213
17214        /**
17215         * Indicates whether the view's window is currently in touch mode.
17216         */
17217        boolean mInTouchMode;
17218
17219        /**
17220         * Indicates that ViewAncestor should trigger a global layout change
17221         * the next time it performs a traversal
17222         */
17223        boolean mRecomputeGlobalAttributes;
17224
17225        /**
17226         * Always report new attributes at next traversal.
17227         */
17228        boolean mForceReportNewAttributes;
17229
17230        /**
17231         * Set during a traveral if any views want to keep the screen on.
17232         */
17233        boolean mKeepScreenOn;
17234
17235        /**
17236         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17237         */
17238        int mSystemUiVisibility;
17239
17240        /**
17241         * Hack to force certain system UI visibility flags to be cleared.
17242         */
17243        int mDisabledSystemUiVisibility;
17244
17245        /**
17246         * Last global system UI visibility reported by the window manager.
17247         */
17248        int mGlobalSystemUiVisibility;
17249
17250        /**
17251         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17252         * attached.
17253         */
17254        boolean mHasSystemUiListeners;
17255
17256        /**
17257         * Set if the visibility of any views has changed.
17258         */
17259        boolean mViewVisibilityChanged;
17260
17261        /**
17262         * Set to true if a view has been scrolled.
17263         */
17264        boolean mViewScrollChanged;
17265
17266        /**
17267         * Global to the view hierarchy used as a temporary for dealing with
17268         * x/y points in the transparent region computations.
17269         */
17270        final int[] mTransparentLocation = new int[2];
17271
17272        /**
17273         * Global to the view hierarchy used as a temporary for dealing with
17274         * x/y points in the ViewGroup.invalidateChild implementation.
17275         */
17276        final int[] mInvalidateChildLocation = new int[2];
17277
17278
17279        /**
17280         * Global to the view hierarchy used as a temporary for dealing with
17281         * x/y location when view is transformed.
17282         */
17283        final float[] mTmpTransformLocation = new float[2];
17284
17285        /**
17286         * The view tree observer used to dispatch global events like
17287         * layout, pre-draw, touch mode change, etc.
17288         */
17289        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17290
17291        /**
17292         * A Canvas used by the view hierarchy to perform bitmap caching.
17293         */
17294        Canvas mCanvas;
17295
17296        /**
17297         * The view root impl.
17298         */
17299        final ViewRootImpl mViewRootImpl;
17300
17301        /**
17302         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17303         * handler can be used to pump events in the UI events queue.
17304         */
17305        final Handler mHandler;
17306
17307        /**
17308         * Temporary for use in computing invalidate rectangles while
17309         * calling up the hierarchy.
17310         */
17311        final Rect mTmpInvalRect = new Rect();
17312
17313        /**
17314         * Temporary for use in computing hit areas with transformed views
17315         */
17316        final RectF mTmpTransformRect = new RectF();
17317
17318        /**
17319         * Temporary list for use in collecting focusable descendents of a view.
17320         */
17321        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17322
17323        /**
17324         * The id of the window for accessibility purposes.
17325         */
17326        int mAccessibilityWindowId = View.NO_ID;
17327
17328        /**
17329         * Whether to ingore not exposed for accessibility Views when
17330         * reporting the view tree to accessibility services.
17331         */
17332        boolean mIncludeNotImportantViews;
17333
17334        /**
17335         * The drawable for highlighting accessibility focus.
17336         */
17337        Drawable mAccessibilityFocusDrawable;
17338
17339        /**
17340         * Show where the margins, bounds and layout bounds are for each view.
17341         */
17342        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17343
17344        /**
17345         * Point used to compute visible regions.
17346         */
17347        final Point mPoint = new Point();
17348
17349        /**
17350         * Creates a new set of attachment information with the specified
17351         * events handler and thread.
17352         *
17353         * @param handler the events handler the view must use
17354         */
17355        AttachInfo(IWindowSession session, IWindow window,
17356                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17357            mSession = session;
17358            mWindow = window;
17359            mWindowToken = window.asBinder();
17360            mViewRootImpl = viewRootImpl;
17361            mHandler = handler;
17362            mRootCallbacks = effectPlayer;
17363        }
17364    }
17365
17366    /**
17367     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17368     * is supported. This avoids keeping too many unused fields in most
17369     * instances of View.</p>
17370     */
17371    private static class ScrollabilityCache implements Runnable {
17372
17373        /**
17374         * Scrollbars are not visible
17375         */
17376        public static final int OFF = 0;
17377
17378        /**
17379         * Scrollbars are visible
17380         */
17381        public static final int ON = 1;
17382
17383        /**
17384         * Scrollbars are fading away
17385         */
17386        public static final int FADING = 2;
17387
17388        public boolean fadeScrollBars;
17389
17390        public int fadingEdgeLength;
17391        public int scrollBarDefaultDelayBeforeFade;
17392        public int scrollBarFadeDuration;
17393
17394        public int scrollBarSize;
17395        public ScrollBarDrawable scrollBar;
17396        public float[] interpolatorValues;
17397        public View host;
17398
17399        public final Paint paint;
17400        public final Matrix matrix;
17401        public Shader shader;
17402
17403        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17404
17405        private static final float[] OPAQUE = { 255 };
17406        private static final float[] TRANSPARENT = { 0.0f };
17407
17408        /**
17409         * When fading should start. This time moves into the future every time
17410         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17411         */
17412        public long fadeStartTime;
17413
17414
17415        /**
17416         * The current state of the scrollbars: ON, OFF, or FADING
17417         */
17418        public int state = OFF;
17419
17420        private int mLastColor;
17421
17422        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17423            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17424            scrollBarSize = configuration.getScaledScrollBarSize();
17425            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17426            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17427
17428            paint = new Paint();
17429            matrix = new Matrix();
17430            // use use a height of 1, and then wack the matrix each time we
17431            // actually use it.
17432            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17433
17434            paint.setShader(shader);
17435            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17436            this.host = host;
17437        }
17438
17439        public void setFadeColor(int color) {
17440            if (color != 0 && color != mLastColor) {
17441                mLastColor = color;
17442                color |= 0xFF000000;
17443
17444                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17445                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17446
17447                paint.setShader(shader);
17448                // Restore the default transfer mode (src_over)
17449                paint.setXfermode(null);
17450            }
17451        }
17452
17453        public void run() {
17454            long now = AnimationUtils.currentAnimationTimeMillis();
17455            if (now >= fadeStartTime) {
17456
17457                // the animation fades the scrollbars out by changing
17458                // the opacity (alpha) from fully opaque to fully
17459                // transparent
17460                int nextFrame = (int) now;
17461                int framesCount = 0;
17462
17463                Interpolator interpolator = scrollBarInterpolator;
17464
17465                // Start opaque
17466                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17467
17468                // End transparent
17469                nextFrame += scrollBarFadeDuration;
17470                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17471
17472                state = FADING;
17473
17474                // Kick off the fade animation
17475                host.invalidate(true);
17476            }
17477        }
17478    }
17479
17480    /**
17481     * Resuable callback for sending
17482     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17483     */
17484    private class SendViewScrolledAccessibilityEvent implements Runnable {
17485        public volatile boolean mIsPending;
17486
17487        public void run() {
17488            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17489            mIsPending = false;
17490        }
17491    }
17492
17493    /**
17494     * <p>
17495     * This class represents a delegate that can be registered in a {@link View}
17496     * to enhance accessibility support via composition rather via inheritance.
17497     * It is specifically targeted to widget developers that extend basic View
17498     * classes i.e. classes in package android.view, that would like their
17499     * applications to be backwards compatible.
17500     * </p>
17501     * <div class="special reference">
17502     * <h3>Developer Guides</h3>
17503     * <p>For more information about making applications accessible, read the
17504     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17505     * developer guide.</p>
17506     * </div>
17507     * <p>
17508     * A scenario in which a developer would like to use an accessibility delegate
17509     * is overriding a method introduced in a later API version then the minimal API
17510     * version supported by the application. For example, the method
17511     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17512     * in API version 4 when the accessibility APIs were first introduced. If a
17513     * developer would like his application to run on API version 4 devices (assuming
17514     * all other APIs used by the application are version 4 or lower) and take advantage
17515     * of this method, instead of overriding the method which would break the application's
17516     * backwards compatibility, he can override the corresponding method in this
17517     * delegate and register the delegate in the target View if the API version of
17518     * the system is high enough i.e. the API version is same or higher to the API
17519     * version that introduced
17520     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17521     * </p>
17522     * <p>
17523     * Here is an example implementation:
17524     * </p>
17525     * <code><pre><p>
17526     * if (Build.VERSION.SDK_INT >= 14) {
17527     *     // If the API version is equal of higher than the version in
17528     *     // which onInitializeAccessibilityNodeInfo was introduced we
17529     *     // register a delegate with a customized implementation.
17530     *     View view = findViewById(R.id.view_id);
17531     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17532     *         public void onInitializeAccessibilityNodeInfo(View host,
17533     *                 AccessibilityNodeInfo info) {
17534     *             // Let the default implementation populate the info.
17535     *             super.onInitializeAccessibilityNodeInfo(host, info);
17536     *             // Set some other information.
17537     *             info.setEnabled(host.isEnabled());
17538     *         }
17539     *     });
17540     * }
17541     * </code></pre></p>
17542     * <p>
17543     * This delegate contains methods that correspond to the accessibility methods
17544     * in View. If a delegate has been specified the implementation in View hands
17545     * off handling to the corresponding method in this delegate. The default
17546     * implementation the delegate methods behaves exactly as the corresponding
17547     * method in View for the case of no accessibility delegate been set. Hence,
17548     * to customize the behavior of a View method, clients can override only the
17549     * corresponding delegate method without altering the behavior of the rest
17550     * accessibility related methods of the host view.
17551     * </p>
17552     */
17553    public static class AccessibilityDelegate {
17554
17555        /**
17556         * Sends an accessibility event of the given type. If accessibility is not
17557         * enabled this method has no effect.
17558         * <p>
17559         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17560         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17561         * been set.
17562         * </p>
17563         *
17564         * @param host The View hosting the delegate.
17565         * @param eventType The type of the event to send.
17566         *
17567         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17568         */
17569        public void sendAccessibilityEvent(View host, int eventType) {
17570            host.sendAccessibilityEventInternal(eventType);
17571        }
17572
17573        /**
17574         * Performs the specified accessibility action on the view. For
17575         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17576         * <p>
17577         * The default implementation behaves as
17578         * {@link View#performAccessibilityAction(int, Bundle)
17579         *  View#performAccessibilityAction(int, Bundle)} for the case of
17580         *  no accessibility delegate been set.
17581         * </p>
17582         *
17583         * @param action The action to perform.
17584         * @return Whether the action was performed.
17585         *
17586         * @see View#performAccessibilityAction(int, Bundle)
17587         *      View#performAccessibilityAction(int, Bundle)
17588         */
17589        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17590            return host.performAccessibilityActionInternal(action, args);
17591        }
17592
17593        /**
17594         * Sends an accessibility event. This method behaves exactly as
17595         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17596         * empty {@link AccessibilityEvent} and does not perform a check whether
17597         * accessibility is enabled.
17598         * <p>
17599         * The default implementation behaves as
17600         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17601         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17602         * the case of no accessibility delegate been set.
17603         * </p>
17604         *
17605         * @param host The View hosting the delegate.
17606         * @param event The event to send.
17607         *
17608         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17609         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17610         */
17611        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17612            host.sendAccessibilityEventUncheckedInternal(event);
17613        }
17614
17615        /**
17616         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17617         * to its children for adding their text content to the event.
17618         * <p>
17619         * The default implementation behaves as
17620         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17621         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17622         * the case of no accessibility delegate been set.
17623         * </p>
17624         *
17625         * @param host The View hosting the delegate.
17626         * @param event The event.
17627         * @return True if the event population was completed.
17628         *
17629         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17630         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17631         */
17632        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17633            return host.dispatchPopulateAccessibilityEventInternal(event);
17634        }
17635
17636        /**
17637         * Gives a chance to the host View to populate the accessibility event with its
17638         * text content.
17639         * <p>
17640         * The default implementation behaves as
17641         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17642         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17643         * the case of no accessibility delegate been set.
17644         * </p>
17645         *
17646         * @param host The View hosting the delegate.
17647         * @param event The accessibility event which to populate.
17648         *
17649         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17650         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17651         */
17652        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17653            host.onPopulateAccessibilityEventInternal(event);
17654        }
17655
17656        /**
17657         * Initializes an {@link AccessibilityEvent} with information about the
17658         * the host View which is the event source.
17659         * <p>
17660         * The default implementation behaves as
17661         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17662         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17663         * the case of no accessibility delegate been set.
17664         * </p>
17665         *
17666         * @param host The View hosting the delegate.
17667         * @param event The event to initialize.
17668         *
17669         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17670         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17671         */
17672        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17673            host.onInitializeAccessibilityEventInternal(event);
17674        }
17675
17676        /**
17677         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17678         * <p>
17679         * The default implementation behaves as
17680         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17681         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17682         * the case of no accessibility delegate been set.
17683         * </p>
17684         *
17685         * @param host The View hosting the delegate.
17686         * @param info The instance to initialize.
17687         *
17688         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17689         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17690         */
17691        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17692            host.onInitializeAccessibilityNodeInfoInternal(info);
17693        }
17694
17695        /**
17696         * Called when a child of the host View has requested sending an
17697         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17698         * to augment the event.
17699         * <p>
17700         * The default implementation behaves as
17701         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17702         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17703         * the case of no accessibility delegate been set.
17704         * </p>
17705         *
17706         * @param host The View hosting the delegate.
17707         * @param child The child which requests sending the event.
17708         * @param event The event to be sent.
17709         * @return True if the event should be sent
17710         *
17711         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17712         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17713         */
17714        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17715                AccessibilityEvent event) {
17716            return host.onRequestSendAccessibilityEventInternal(child, event);
17717        }
17718
17719        /**
17720         * Gets the provider for managing a virtual view hierarchy rooted at this View
17721         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17722         * that explore the window content.
17723         * <p>
17724         * The default implementation behaves as
17725         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17726         * the case of no accessibility delegate been set.
17727         * </p>
17728         *
17729         * @return The provider.
17730         *
17731         * @see AccessibilityNodeProvider
17732         */
17733        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17734            return null;
17735        }
17736    }
17737}
17738