View.java revision 7d3082a3f09e32e7c42b2896e90902157039b10e
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 hardware key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a hardware 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, 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     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1011     * item.
1012     */
1013    public static final int FOCUS_BACKWARD = 0x00000001;
1014
1015    /**
1016     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1017     * item.
1018     */
1019    public static final int FOCUS_FORWARD = 0x00000002;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the left.
1023     */
1024    public static final int FOCUS_LEFT = 0x00000011;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus up.
1028     */
1029    public static final int FOCUS_UP = 0x00000021;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move focus to the right.
1033     */
1034    public static final int FOCUS_RIGHT = 0x00000042;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus down.
1038     */
1039    public static final int FOCUS_DOWN = 0x00000082;
1040
1041    /**
1042     * Bits of {@link #getMeasuredWidthAndState()} and
1043     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1044     */
1045    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1046
1047    /**
1048     * Bits of {@link #getMeasuredWidthAndState()} and
1049     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1050     */
1051    public static final int MEASURED_STATE_MASK = 0xff000000;
1052
1053    /**
1054     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1055     * for functions that combine both width and height into a single int,
1056     * such as {@link #getMeasuredState()} and the childState argument of
1057     * {@link #resolveSizeAndState(int, int, int)}.
1058     */
1059    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1060
1061    /**
1062     * Bit of {@link #getMeasuredWidthAndState()} and
1063     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1064     * is smaller that the space the view would like to have.
1065     */
1066    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1067
1068    /**
1069     * Base View state sets
1070     */
1071    // Singles
1072    /**
1073     * Indicates the view has no states set. States are used with
1074     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1075     * view depending on its state.
1076     *
1077     * @see android.graphics.drawable.Drawable
1078     * @see #getDrawableState()
1079     */
1080    protected static final int[] EMPTY_STATE_SET;
1081    /**
1082     * Indicates the view is enabled. States are used with
1083     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1084     * view depending on its state.
1085     *
1086     * @see android.graphics.drawable.Drawable
1087     * @see #getDrawableState()
1088     */
1089    protected static final int[] ENABLED_STATE_SET;
1090    /**
1091     * Indicates the view is focused. States are used with
1092     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1093     * view depending on its state.
1094     *
1095     * @see android.graphics.drawable.Drawable
1096     * @see #getDrawableState()
1097     */
1098    protected static final int[] FOCUSED_STATE_SET;
1099    /**
1100     * Indicates the view is selected. States are used with
1101     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1102     * view depending on its state.
1103     *
1104     * @see android.graphics.drawable.Drawable
1105     * @see #getDrawableState()
1106     */
1107    protected static final int[] SELECTED_STATE_SET;
1108    /**
1109     * Indicates the view is pressed. States are used with
1110     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1111     * view depending on its state.
1112     *
1113     * @see android.graphics.drawable.Drawable
1114     * @see #getDrawableState()
1115     * @hide
1116     */
1117    protected static final int[] PRESSED_STATE_SET;
1118    /**
1119     * Indicates the view's window has focus. 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[] WINDOW_FOCUSED_STATE_SET;
1127    // Doubles
1128    /**
1129     * Indicates the view is enabled and has the focus.
1130     *
1131     * @see #ENABLED_STATE_SET
1132     * @see #FOCUSED_STATE_SET
1133     */
1134    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1135    /**
1136     * Indicates the view is enabled and selected.
1137     *
1138     * @see #ENABLED_STATE_SET
1139     * @see #SELECTED_STATE_SET
1140     */
1141    protected static final int[] ENABLED_SELECTED_STATE_SET;
1142    /**
1143     * Indicates the view is enabled and that its window has focus.
1144     *
1145     * @see #ENABLED_STATE_SET
1146     * @see #WINDOW_FOCUSED_STATE_SET
1147     */
1148    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1149    /**
1150     * Indicates the view is focused and selected.
1151     *
1152     * @see #FOCUSED_STATE_SET
1153     * @see #SELECTED_STATE_SET
1154     */
1155    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1156    /**
1157     * Indicates the view has the focus and that its window has the focus.
1158     *
1159     * @see #FOCUSED_STATE_SET
1160     * @see #WINDOW_FOCUSED_STATE_SET
1161     */
1162    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1163    /**
1164     * Indicates the view is selected and that its window has the focus.
1165     *
1166     * @see #SELECTED_STATE_SET
1167     * @see #WINDOW_FOCUSED_STATE_SET
1168     */
1169    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1170    // Triples
1171    /**
1172     * Indicates the view is enabled, focused and selected.
1173     *
1174     * @see #ENABLED_STATE_SET
1175     * @see #FOCUSED_STATE_SET
1176     * @see #SELECTED_STATE_SET
1177     */
1178    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1179    /**
1180     * Indicates the view is enabled, focused and its window has the focus.
1181     *
1182     * @see #ENABLED_STATE_SET
1183     * @see #FOCUSED_STATE_SET
1184     * @see #WINDOW_FOCUSED_STATE_SET
1185     */
1186    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1187    /**
1188     * Indicates the view is enabled, selected and its window has the focus.
1189     *
1190     * @see #ENABLED_STATE_SET
1191     * @see #SELECTED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1195    /**
1196     * Indicates the view is focused, selected and its window has the focus.
1197     *
1198     * @see #FOCUSED_STATE_SET
1199     * @see #SELECTED_STATE_SET
1200     * @see #WINDOW_FOCUSED_STATE_SET
1201     */
1202    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1203    /**
1204     * Indicates the view is enabled, focused, selected and its window
1205     * has the focus.
1206     *
1207     * @see #ENABLED_STATE_SET
1208     * @see #FOCUSED_STATE_SET
1209     * @see #SELECTED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1213    /**
1214     * Indicates the view is pressed and its window has the focus.
1215     *
1216     * @see #PRESSED_STATE_SET
1217     * @see #WINDOW_FOCUSED_STATE_SET
1218     */
1219    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1220    /**
1221     * Indicates the view is pressed and selected.
1222     *
1223     * @see #PRESSED_STATE_SET
1224     * @see #SELECTED_STATE_SET
1225     */
1226    protected static final int[] PRESSED_SELECTED_STATE_SET;
1227    /**
1228     * Indicates the view is pressed, selected and its window has the focus.
1229     *
1230     * @see #PRESSED_STATE_SET
1231     * @see #SELECTED_STATE_SET
1232     * @see #WINDOW_FOCUSED_STATE_SET
1233     */
1234    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1235    /**
1236     * Indicates the view is pressed and focused.
1237     *
1238     * @see #PRESSED_STATE_SET
1239     * @see #FOCUSED_STATE_SET
1240     */
1241    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1242    /**
1243     * Indicates the view is pressed, focused and its window has the focus.
1244     *
1245     * @see #PRESSED_STATE_SET
1246     * @see #FOCUSED_STATE_SET
1247     * @see #WINDOW_FOCUSED_STATE_SET
1248     */
1249    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1250    /**
1251     * Indicates the view is pressed, focused and selected.
1252     *
1253     * @see #PRESSED_STATE_SET
1254     * @see #SELECTED_STATE_SET
1255     * @see #FOCUSED_STATE_SET
1256     */
1257    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1258    /**
1259     * Indicates the view is pressed, focused, selected and its window has the focus.
1260     *
1261     * @see #PRESSED_STATE_SET
1262     * @see #FOCUSED_STATE_SET
1263     * @see #SELECTED_STATE_SET
1264     * @see #WINDOW_FOCUSED_STATE_SET
1265     */
1266    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1267    /**
1268     * Indicates the view is pressed and enabled.
1269     *
1270     * @see #PRESSED_STATE_SET
1271     * @see #ENABLED_STATE_SET
1272     */
1273    protected static final int[] PRESSED_ENABLED_STATE_SET;
1274    /**
1275     * Indicates the view is pressed, enabled and its window has the focus.
1276     *
1277     * @see #PRESSED_STATE_SET
1278     * @see #ENABLED_STATE_SET
1279     * @see #WINDOW_FOCUSED_STATE_SET
1280     */
1281    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1282    /**
1283     * Indicates the view is pressed, enabled and selected.
1284     *
1285     * @see #PRESSED_STATE_SET
1286     * @see #ENABLED_STATE_SET
1287     * @see #SELECTED_STATE_SET
1288     */
1289    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1290    /**
1291     * Indicates the view is pressed, enabled, selected and its window has the
1292     * focus.
1293     *
1294     * @see #PRESSED_STATE_SET
1295     * @see #ENABLED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #WINDOW_FOCUSED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, enabled and focused.
1302     *
1303     * @see #PRESSED_STATE_SET
1304     * @see #ENABLED_STATE_SET
1305     * @see #FOCUSED_STATE_SET
1306     */
1307    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed, enabled, focused and its window has the
1310     * focus.
1311     *
1312     * @see #PRESSED_STATE_SET
1313     * @see #ENABLED_STATE_SET
1314     * @see #FOCUSED_STATE_SET
1315     * @see #WINDOW_FOCUSED_STATE_SET
1316     */
1317    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1318    /**
1319     * Indicates the view is pressed, enabled, focused and selected.
1320     *
1321     * @see #PRESSED_STATE_SET
1322     * @see #ENABLED_STATE_SET
1323     * @see #SELECTED_STATE_SET
1324     * @see #FOCUSED_STATE_SET
1325     */
1326    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1327    /**
1328     * Indicates the view is pressed, enabled, focused, selected and its window
1329     * has the focus.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     * @see #WINDOW_FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1338
1339    /**
1340     * The order here is very important to {@link #getDrawableState()}
1341     */
1342    private static final int[][] VIEW_STATE_SETS;
1343
1344    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1345    static final int VIEW_STATE_SELECTED = 1 << 1;
1346    static final int VIEW_STATE_FOCUSED = 1 << 2;
1347    static final int VIEW_STATE_ENABLED = 1 << 3;
1348    static final int VIEW_STATE_PRESSED = 1 << 4;
1349    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1350    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1351    static final int VIEW_STATE_HOVERED = 1 << 7;
1352    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1353    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1354
1355    static final int[] VIEW_STATE_IDS = new int[] {
1356        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1357        R.attr.state_selected,          VIEW_STATE_SELECTED,
1358        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1359        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1360        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1361        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1362        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1363        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1364        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1365        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1366    };
1367
1368    static {
1369        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1370            throw new IllegalStateException(
1371                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1372        }
1373        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1374        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1375            int viewState = R.styleable.ViewDrawableStates[i];
1376            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1377                if (VIEW_STATE_IDS[j] == viewState) {
1378                    orderedIds[i * 2] = viewState;
1379                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1380                }
1381            }
1382        }
1383        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1384        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1385        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1386            int numBits = Integer.bitCount(i);
1387            int[] set = new int[numBits];
1388            int pos = 0;
1389            for (int j = 0; j < orderedIds.length; j += 2) {
1390                if ((i & orderedIds[j+1]) != 0) {
1391                    set[pos++] = orderedIds[j];
1392                }
1393            }
1394            VIEW_STATE_SETS[i] = set;
1395        }
1396
1397        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1398        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1399        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1400        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1401                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1402        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1403        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1404                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1405        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1406                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1407        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1409                | VIEW_STATE_FOCUSED];
1410        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1411        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1413        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1415        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1417                | VIEW_STATE_ENABLED];
1418        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1420        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1421                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1422                | VIEW_STATE_ENABLED];
1423        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1425                | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1429
1430        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1431        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1433        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1434                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1435        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1436                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1437                | VIEW_STATE_PRESSED];
1438        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1439                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1440        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1441                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1442                | VIEW_STATE_PRESSED];
1443        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1445                | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1449        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1451        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1462                | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1465                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1471                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1472                | VIEW_STATE_PRESSED];
1473    }
1474
1475    /**
1476     * Accessibility event types that are dispatched for text population.
1477     */
1478    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1479            AccessibilityEvent.TYPE_VIEW_CLICKED
1480            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1481            | AccessibilityEvent.TYPE_VIEW_SELECTED
1482            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1483            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1484            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1485            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1486            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1487            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1488            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1489            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1490
1491    /**
1492     * Temporary Rect currently for use in setBackground().  This will probably
1493     * be extended in the future to hold our own class with more than just
1494     * a Rect. :)
1495     */
1496    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1497
1498    /**
1499     * Map used to store views' tags.
1500     */
1501    private SparseArray<Object> mKeyedTags;
1502
1503    /**
1504     * The next available accessiiblity id.
1505     */
1506    private static int sNextAccessibilityViewId;
1507
1508    /**
1509     * The animation currently associated with this view.
1510     * @hide
1511     */
1512    protected Animation mCurrentAnimation = null;
1513
1514    /**
1515     * Width as measured during measure pass.
1516     * {@hide}
1517     */
1518    @ViewDebug.ExportedProperty(category = "measurement")
1519    int mMeasuredWidth;
1520
1521    /**
1522     * Height as measured during measure pass.
1523     * {@hide}
1524     */
1525    @ViewDebug.ExportedProperty(category = "measurement")
1526    int mMeasuredHeight;
1527
1528    /**
1529     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1530     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1531     * its display list. This flag, used only when hw accelerated, allows us to clear the
1532     * flag while retaining this information until it's needed (at getDisplayList() time and
1533     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1534     *
1535     * {@hide}
1536     */
1537    boolean mRecreateDisplayList = false;
1538
1539    /**
1540     * The view's identifier.
1541     * {@hide}
1542     *
1543     * @see #setId(int)
1544     * @see #getId()
1545     */
1546    @ViewDebug.ExportedProperty(resolveId = true)
1547    int mID = NO_ID;
1548
1549    /**
1550     * The stable ID of this view for accessibility purposes.
1551     */
1552    int mAccessibilityViewId = NO_ID;
1553
1554    /**
1555     * @hide
1556     */
1557    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1558
1559    /**
1560     * The view's tag.
1561     * {@hide}
1562     *
1563     * @see #setTag(Object)
1564     * @see #getTag()
1565     */
1566    protected Object mTag;
1567
1568    // for mPrivateFlags:
1569    /** {@hide} */
1570    static final int WANTS_FOCUS                    = 0x00000001;
1571    /** {@hide} */
1572    static final int FOCUSED                        = 0x00000002;
1573    /** {@hide} */
1574    static final int SELECTED                       = 0x00000004;
1575    /** {@hide} */
1576    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1577    /** {@hide} */
1578    static final int HAS_BOUNDS                     = 0x00000010;
1579    /** {@hide} */
1580    static final int DRAWN                          = 0x00000020;
1581    /**
1582     * When this flag is set, this view is running an animation on behalf of its
1583     * children and should therefore not cancel invalidate requests, even if they
1584     * lie outside of this view's bounds.
1585     *
1586     * {@hide}
1587     */
1588    static final int DRAW_ANIMATION                 = 0x00000040;
1589    /** {@hide} */
1590    static final int SKIP_DRAW                      = 0x00000080;
1591    /** {@hide} */
1592    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1593    /** {@hide} */
1594    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1595    /** {@hide} */
1596    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1597    /** {@hide} */
1598    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1599    /** {@hide} */
1600    static final int FORCE_LAYOUT                   = 0x00001000;
1601    /** {@hide} */
1602    static final int LAYOUT_REQUIRED                = 0x00002000;
1603
1604    private static final int PRESSED                = 0x00004000;
1605
1606    /** {@hide} */
1607    static final int DRAWING_CACHE_VALID            = 0x00008000;
1608    /**
1609     * Flag used to indicate that this view should be drawn once more (and only once
1610     * more) after its animation has completed.
1611     * {@hide}
1612     */
1613    static final int ANIMATION_STARTED              = 0x00010000;
1614
1615    private static final int SAVE_STATE_CALLED      = 0x00020000;
1616
1617    /**
1618     * Indicates that the View returned true when onSetAlpha() was called and that
1619     * the alpha must be restored.
1620     * {@hide}
1621     */
1622    static final int ALPHA_SET                      = 0x00040000;
1623
1624    /**
1625     * Set by {@link #setScrollContainer(boolean)}.
1626     */
1627    static final int SCROLL_CONTAINER               = 0x00080000;
1628
1629    /**
1630     * Set by {@link #setScrollContainer(boolean)}.
1631     */
1632    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1633
1634    /**
1635     * View flag indicating whether this view was invalidated (fully or partially.)
1636     *
1637     * @hide
1638     */
1639    static final int DIRTY                          = 0x00200000;
1640
1641    /**
1642     * View flag indicating whether this view was invalidated by an opaque
1643     * invalidate request.
1644     *
1645     * @hide
1646     */
1647    static final int DIRTY_OPAQUE                   = 0x00400000;
1648
1649    /**
1650     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1651     *
1652     * @hide
1653     */
1654    static final int DIRTY_MASK                     = 0x00600000;
1655
1656    /**
1657     * Indicates whether the background is opaque.
1658     *
1659     * @hide
1660     */
1661    static final int OPAQUE_BACKGROUND              = 0x00800000;
1662
1663    /**
1664     * Indicates whether the scrollbars are opaque.
1665     *
1666     * @hide
1667     */
1668    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1669
1670    /**
1671     * Indicates whether the view is opaque.
1672     *
1673     * @hide
1674     */
1675    static final int OPAQUE_MASK                    = 0x01800000;
1676
1677    /**
1678     * Indicates a prepressed state;
1679     * the short time between ACTION_DOWN and recognizing
1680     * a 'real' press. Prepressed is used to recognize quick taps
1681     * even when they are shorter than ViewConfiguration.getTapTimeout().
1682     *
1683     * @hide
1684     */
1685    private static final int PREPRESSED             = 0x02000000;
1686
1687    /**
1688     * Indicates whether the view is temporarily detached.
1689     *
1690     * @hide
1691     */
1692    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1693
1694    /**
1695     * Indicates that we should awaken scroll bars once attached
1696     *
1697     * @hide
1698     */
1699    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1700
1701    /**
1702     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1703     * @hide
1704     */
1705    private static final int HOVERED              = 0x10000000;
1706
1707    /**
1708     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1709     * for transform operations
1710     *
1711     * @hide
1712     */
1713    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1714
1715    /** {@hide} */
1716    static final int ACTIVATED                    = 0x40000000;
1717
1718    /**
1719     * Indicates that this view was specifically invalidated, not just dirtied because some
1720     * child view was invalidated. The flag is used to determine when we need to recreate
1721     * a view's display list (as opposed to just returning a reference to its existing
1722     * display list).
1723     *
1724     * @hide
1725     */
1726    static final int INVALIDATED                  = 0x80000000;
1727
1728    /* Masks for mPrivateFlags2 */
1729
1730    /**
1731     * Indicates that this view has reported that it can accept the current drag's content.
1732     * Cleared when the drag operation concludes.
1733     * @hide
1734     */
1735    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1736
1737    /**
1738     * Indicates that this view is currently directly under the drag location in a
1739     * drag-and-drop operation involving content that it can accept.  Cleared when
1740     * the drag exits the view, or when the drag operation concludes.
1741     * @hide
1742     */
1743    static final int DRAG_HOVERED                 = 0x00000002;
1744
1745    /**
1746     * Horizontal layout direction of this view is from Left to Right.
1747     * Use with {@link #setLayoutDirection}.
1748     */
1749    public static final int LAYOUT_DIRECTION_LTR = 0;
1750
1751    /**
1752     * Horizontal layout direction of this view is from Right to Left.
1753     * Use with {@link #setLayoutDirection}.
1754     */
1755    public static final int LAYOUT_DIRECTION_RTL = 1;
1756
1757    /**
1758     * Horizontal layout direction of this view is inherited from its parent.
1759     * Use with {@link #setLayoutDirection}.
1760     */
1761    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1762
1763    /**
1764     * Horizontal layout direction of this view is from deduced from the default language
1765     * script for the locale. Use with {@link #setLayoutDirection}.
1766     */
1767    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1768
1769    /**
1770     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1771     * @hide
1772     */
1773    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1774
1775    /**
1776     * Mask for use with private flags indicating bits used for horizontal layout direction.
1777     * @hide
1778     */
1779    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1780
1781    /**
1782     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1783     * right-to-left direction.
1784     * @hide
1785     */
1786    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1787
1788    /**
1789     * Indicates whether the view horizontal layout direction has been resolved.
1790     * @hide
1791     */
1792    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1793
1794    /**
1795     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1796     * @hide
1797     */
1798    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1799
1800    /*
1801     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1802     * flag value.
1803     * @hide
1804     */
1805    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1806            LAYOUT_DIRECTION_LTR,
1807            LAYOUT_DIRECTION_RTL,
1808            LAYOUT_DIRECTION_INHERIT,
1809            LAYOUT_DIRECTION_LOCALE
1810    };
1811
1812    /**
1813     * Default horizontal layout direction.
1814     * @hide
1815     */
1816    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1817
1818    /**
1819     * Indicates that the view is tracking some sort of transient state
1820     * that the app should not need to be aware of, but that the framework
1821     * should take special care to preserve.
1822     *
1823     * @hide
1824     */
1825    static final int HAS_TRANSIENT_STATE = 0x00000100;
1826
1827
1828    /**
1829     * Text direction is inherited thru {@link ViewGroup}
1830     */
1831    public static final int TEXT_DIRECTION_INHERIT = 0;
1832
1833    /**
1834     * Text direction is using "first strong algorithm". The first strong directional character
1835     * determines the paragraph direction. If there is no strong directional character, the
1836     * paragraph direction is the view's resolved layout direction.
1837     */
1838    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1839
1840    /**
1841     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1842     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1843     * If there are neither, the paragraph direction is the view's resolved layout direction.
1844     */
1845    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1846
1847    /**
1848     * Text direction is forced to LTR.
1849     */
1850    public static final int TEXT_DIRECTION_LTR = 3;
1851
1852    /**
1853     * Text direction is forced to RTL.
1854     */
1855    public static final int TEXT_DIRECTION_RTL = 4;
1856
1857    /**
1858     * Text direction is coming from the system Locale.
1859     */
1860    public static final int TEXT_DIRECTION_LOCALE = 5;
1861
1862    /**
1863     * Default text direction is inherited
1864     */
1865    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1866
1867    /**
1868     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1869     * @hide
1870     */
1871    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1872
1873    /**
1874     * Mask for use with private flags indicating bits used for text direction.
1875     * @hide
1876     */
1877    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1878
1879    /**
1880     * Array of text direction flags for mapping attribute "textDirection" to correct
1881     * flag value.
1882     * @hide
1883     */
1884    private static final int[] TEXT_DIRECTION_FLAGS = {
1885            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1886            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1887            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1888            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1889            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1890            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1891    };
1892
1893    /**
1894     * Indicates whether the view text direction has been resolved.
1895     * @hide
1896     */
1897    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1898
1899    /**
1900     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1901     * @hide
1902     */
1903    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1904
1905    /**
1906     * Mask for use with private flags indicating bits used for resolved text direction.
1907     * @hide
1908     */
1909    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1910
1911    /**
1912     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1913     * @hide
1914     */
1915    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1916            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1917
1918    /*
1919     * Default text alignment. The text alignment of this View is inherited from its parent.
1920     * Use with {@link #setTextAlignment(int)}
1921     */
1922    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1923
1924    /**
1925     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1926     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1927     *
1928     * Use with {@link #setTextAlignment(int)}
1929     */
1930    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1931
1932    /**
1933     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1934     *
1935     * Use with {@link #setTextAlignment(int)}
1936     */
1937    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1938
1939    /**
1940     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1941     *
1942     * Use with {@link #setTextAlignment(int)}
1943     */
1944    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1945
1946    /**
1947     * Center the paragraph, e.g. ALIGN_CENTER.
1948     *
1949     * Use with {@link #setTextAlignment(int)}
1950     */
1951    public static final int TEXT_ALIGNMENT_CENTER = 4;
1952
1953    /**
1954     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1955     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1956     *
1957     * Use with {@link #setTextAlignment(int)}
1958     */
1959    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1960
1961    /**
1962     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1963     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1964     *
1965     * Use with {@link #setTextAlignment(int)}
1966     */
1967    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1968
1969    /**
1970     * Default text alignment is inherited
1971     */
1972    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
1973
1974    /**
1975      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1976      * @hide
1977      */
1978    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
1979
1980    /**
1981      * Mask for use with private flags indicating bits used for text alignment.
1982      * @hide
1983      */
1984    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
1985
1986    /**
1987     * Array of text direction flags for mapping attribute "textAlignment" to correct
1988     * flag value.
1989     * @hide
1990     */
1991    private static final int[] TEXT_ALIGNMENT_FLAGS = {
1992            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
1993            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
1994            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
1995            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
1996            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
1997            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
1998            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
1999    };
2000
2001    /**
2002     * Indicates whether the view text alignment has been resolved.
2003     * @hide
2004     */
2005    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2006
2007    /**
2008     * Bit shift to get the resolved text alignment.
2009     * @hide
2010     */
2011    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2012
2013    /**
2014     * Mask for use with private flags indicating bits used for text alignment.
2015     * @hide
2016     */
2017    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2018
2019    /**
2020     * Indicates whether if the view text alignment has been resolved to gravity
2021     */
2022    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2023            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2024
2025    // Accessiblity constants for mPrivateFlags2
2026
2027    /**
2028     * Shift for the bits in {@link #mPrivateFlags2} related to the
2029     * "importantForAccessibility" attribute.
2030     */
2031    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2032
2033    /**
2034     * Automatically determine whether a view is important for accessibility.
2035     */
2036    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2037
2038    /**
2039     * The view is important for accessibility.
2040     */
2041    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2042
2043    /**
2044     * The view is not important for accessibility.
2045     */
2046    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2047
2048    /**
2049     * The default whether the view is important for accessiblity.
2050     */
2051    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2052
2053    /**
2054     * Mask for obtainig the bits which specify how to determine
2055     * whether a view is important for accessibility.
2056     */
2057    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2058        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2059        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2060
2061    /**
2062     * Flag indicating whether a view has accessibility focus.
2063     */
2064    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2065
2066    /**
2067     * Flag indicating whether a view state for accessibility has changed.
2068     */
2069    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2070
2071    /**
2072     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2073     * is used to check whether later changes to the view's transform should invalidate the
2074     * view to force the quickReject test to run again.
2075     */
2076    static final int VIEW_QUICK_REJECTED = 0x10000000;
2077
2078    // There are a couple of flags left in mPrivateFlags2
2079
2080    /* End of masks for mPrivateFlags2 */
2081
2082    /* Masks for mPrivateFlags3 */
2083
2084    /**
2085     * Flag indicating that view has a transform animation set on it. This is used to track whether
2086     * an animation is cleared between successive frames, in order to tell the associated
2087     * DisplayList to clear its animation matrix.
2088     */
2089    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2090
2091    /**
2092     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2093     * animation is cleared between successive frames, in order to tell the associated
2094     * DisplayList to restore its alpha value.
2095     */
2096    static final int VIEW_IS_ANIMATING_ALPHA = 0x2;
2097
2098
2099    /* End of masks for mPrivateFlags3 */
2100
2101    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2102
2103    /**
2104     * Always allow a user to over-scroll this view, provided it is a
2105     * view that can scroll.
2106     *
2107     * @see #getOverScrollMode()
2108     * @see #setOverScrollMode(int)
2109     */
2110    public static final int OVER_SCROLL_ALWAYS = 0;
2111
2112    /**
2113     * Allow a user to over-scroll this view only if the content is large
2114     * enough to meaningfully scroll, provided it is a view that can scroll.
2115     *
2116     * @see #getOverScrollMode()
2117     * @see #setOverScrollMode(int)
2118     */
2119    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2120
2121    /**
2122     * Never allow a user to over-scroll this view.
2123     *
2124     * @see #getOverScrollMode()
2125     * @see #setOverScrollMode(int)
2126     */
2127    public static final int OVER_SCROLL_NEVER = 2;
2128
2129    /**
2130     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2131     * requested the system UI (status bar) to be visible (the default).
2132     *
2133     * @see #setSystemUiVisibility(int)
2134     */
2135    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2136
2137    /**
2138     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2139     * system UI to enter an unobtrusive "low profile" mode.
2140     *
2141     * <p>This is for use in games, book readers, video players, or any other
2142     * "immersive" application where the usual system chrome is deemed too distracting.
2143     *
2144     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2145     *
2146     * @see #setSystemUiVisibility(int)
2147     */
2148    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2149
2150    /**
2151     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2152     * system navigation be temporarily hidden.
2153     *
2154     * <p>This is an even less obtrusive state than that called for by
2155     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2156     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2157     * those to disappear. This is useful (in conjunction with the
2158     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2159     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2160     * window flags) for displaying content using every last pixel on the display.
2161     *
2162     * <p>There is a limitation: because navigation controls are so important, the least user
2163     * interaction will cause them to reappear immediately.  When this happens, both
2164     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2165     * so that both elements reappear at the same time.
2166     *
2167     * @see #setSystemUiVisibility(int)
2168     */
2169    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2170
2171    /**
2172     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2173     * into the normal fullscreen mode so that its content can take over the screen
2174     * while still allowing the user to interact with the application.
2175     *
2176     * <p>This has the same visual effect as
2177     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2178     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2179     * meaning that non-critical screen decorations (such as the status bar) will be
2180     * hidden while the user is in the View's window, focusing the experience on
2181     * that content.  Unlike the window flag, if you are using ActionBar in
2182     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2183     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2184     * hide the action bar.
2185     *
2186     * <p>This approach to going fullscreen is best used over the window flag when
2187     * it is a transient state -- that is, the application does this at certain
2188     * points in its user interaction where it wants to allow the user to focus
2189     * on content, but not as a continuous state.  For situations where the application
2190     * would like to simply stay full screen the entire time (such as a game that
2191     * wants to take over the screen), the
2192     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2193     * is usually a better approach.  The state set here will be removed by the system
2194     * in various situations (such as the user moving to another application) like
2195     * the other system UI states.
2196     *
2197     * <p>When using this flag, the application should provide some easy facility
2198     * for the user to go out of it.  A common example would be in an e-book
2199     * reader, where tapping on the screen brings back whatever screen and UI
2200     * decorations that had been hidden while the user was immersed in reading
2201     * the book.
2202     *
2203     * @see #setSystemUiVisibility(int)
2204     */
2205    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2206
2207    /**
2208     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2209     * flags, we would like a stable view of the content insets given to
2210     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2211     * will always represent the worst case that the application can expect
2212     * as a continuous state.  In the stock Android UI this is the space for
2213     * the system bar, nav bar, and status bar, but not more transient elements
2214     * such as an input method.
2215     *
2216     * The stable layout your UI sees is based on the system UI modes you can
2217     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2218     * then you will get a stable layout for changes of the
2219     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2220     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2221     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2222     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2223     * with a stable layout.  (Note that you should avoid using
2224     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2225     *
2226     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2227     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2228     * then a hidden status bar will be considered a "stable" state for purposes
2229     * here.  This allows your UI to continually hide the status bar, while still
2230     * using the system UI flags to hide the action bar while still retaining
2231     * a stable layout.  Note that changing the window fullscreen flag will never
2232     * provide a stable layout for a clean transition.
2233     *
2234     * <p>If you are using ActionBar in
2235     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2236     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2237     * insets it adds to those given to the application.
2238     */
2239    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2240
2241    /**
2242     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2243     * to be layed out as if it has requested
2244     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2245     * allows it to avoid artifacts when switching in and out of that mode, at
2246     * the expense that some of its user interface may be covered by screen
2247     * decorations when they are shown.  You can perform layout of your inner
2248     * UI elements to account for the navagation system UI through the
2249     * {@link #fitSystemWindows(Rect)} method.
2250     */
2251    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2252
2253    /**
2254     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2255     * to be layed out as if it has requested
2256     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2257     * allows it to avoid artifacts when switching in and out of that mode, at
2258     * the expense that some of its user interface may be covered by screen
2259     * decorations when they are shown.  You can perform layout of your inner
2260     * UI elements to account for non-fullscreen system UI through the
2261     * {@link #fitSystemWindows(Rect)} method.
2262     */
2263    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2264
2265    /**
2266     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2267     */
2268    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2269
2270    /**
2271     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2272     */
2273    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2274
2275    /**
2276     * @hide
2277     *
2278     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2279     * out of the public fields to keep the undefined bits out of the developer's way.
2280     *
2281     * Flag to make the status bar not expandable.  Unless you also
2282     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2283     */
2284    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2285
2286    /**
2287     * @hide
2288     *
2289     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2290     * out of the public fields to keep the undefined bits out of the developer's way.
2291     *
2292     * Flag to hide notification icons and scrolling ticker text.
2293     */
2294    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2295
2296    /**
2297     * @hide
2298     *
2299     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2300     * out of the public fields to keep the undefined bits out of the developer's way.
2301     *
2302     * Flag to disable incoming notification alerts.  This will not block
2303     * icons, but it will block sound, vibrating and other visual or aural notifications.
2304     */
2305    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2306
2307    /**
2308     * @hide
2309     *
2310     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2311     * out of the public fields to keep the undefined bits out of the developer's way.
2312     *
2313     * Flag to hide only the scrolling ticker.  Note that
2314     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2315     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2316     */
2317    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2318
2319    /**
2320     * @hide
2321     *
2322     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2323     * out of the public fields to keep the undefined bits out of the developer's way.
2324     *
2325     * Flag to hide the center system info area.
2326     */
2327    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2328
2329    /**
2330     * @hide
2331     *
2332     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2333     * out of the public fields to keep the undefined bits out of the developer's way.
2334     *
2335     * Flag to hide only the home button.  Don't use this
2336     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2337     */
2338    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2339
2340    /**
2341     * @hide
2342     *
2343     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2344     * out of the public fields to keep the undefined bits out of the developer's way.
2345     *
2346     * Flag to hide only the back button. Don't use this
2347     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2348     */
2349    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2350
2351    /**
2352     * @hide
2353     *
2354     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2355     * out of the public fields to keep the undefined bits out of the developer's way.
2356     *
2357     * Flag to hide only the clock.  You might use this if your activity has
2358     * its own clock making the status bar's clock redundant.
2359     */
2360    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2361
2362    /**
2363     * @hide
2364     *
2365     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2366     * out of the public fields to keep the undefined bits out of the developer's way.
2367     *
2368     * Flag to hide only the recent apps button. Don't use this
2369     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2370     */
2371    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2372
2373    /**
2374     * @hide
2375     */
2376    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2377
2378    /**
2379     * These are the system UI flags that can be cleared by events outside
2380     * of an application.  Currently this is just the ability to tap on the
2381     * screen while hiding the navigation bar to have it return.
2382     * @hide
2383     */
2384    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2385            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2386            | SYSTEM_UI_FLAG_FULLSCREEN;
2387
2388    /**
2389     * Flags that can impact the layout in relation to system UI.
2390     */
2391    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2392            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2393            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2394
2395    /**
2396     * Find views that render the specified text.
2397     *
2398     * @see #findViewsWithText(ArrayList, CharSequence, int)
2399     */
2400    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2401
2402    /**
2403     * Find find views that contain the specified content description.
2404     *
2405     * @see #findViewsWithText(ArrayList, CharSequence, int)
2406     */
2407    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2408
2409    /**
2410     * Find views that contain {@link AccessibilityNodeProvider}. Such
2411     * a View is a root of virtual view hierarchy and may contain the searched
2412     * text. If this flag is set Views with providers are automatically
2413     * added and it is a responsibility of the client to call the APIs of
2414     * the provider to determine whether the virtual tree rooted at this View
2415     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2416     * represeting the virtual views with this text.
2417     *
2418     * @see #findViewsWithText(ArrayList, CharSequence, int)
2419     *
2420     * @hide
2421     */
2422    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2423
2424    /**
2425     * The undefined cursor position.
2426     */
2427    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2428
2429    /**
2430     * Indicates that the screen has changed state and is now off.
2431     *
2432     * @see #onScreenStateChanged(int)
2433     */
2434    public static final int SCREEN_STATE_OFF = 0x0;
2435
2436    /**
2437     * Indicates that the screen has changed state and is now on.
2438     *
2439     * @see #onScreenStateChanged(int)
2440     */
2441    public static final int SCREEN_STATE_ON = 0x1;
2442
2443    /**
2444     * Controls the over-scroll mode for this view.
2445     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2446     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2447     * and {@link #OVER_SCROLL_NEVER}.
2448     */
2449    private int mOverScrollMode;
2450
2451    /**
2452     * The parent this view is attached to.
2453     * {@hide}
2454     *
2455     * @see #getParent()
2456     */
2457    protected ViewParent mParent;
2458
2459    /**
2460     * {@hide}
2461     */
2462    AttachInfo mAttachInfo;
2463
2464    /**
2465     * {@hide}
2466     */
2467    @ViewDebug.ExportedProperty(flagMapping = {
2468        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2469                name = "FORCE_LAYOUT"),
2470        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2471                name = "LAYOUT_REQUIRED"),
2472        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2473            name = "DRAWING_CACHE_INVALID", outputIf = false),
2474        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2475        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2476        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2477        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2478    })
2479    int mPrivateFlags;
2480    int mPrivateFlags2;
2481    int mPrivateFlags3;
2482
2483    /**
2484     * This view's request for the visibility of the status bar.
2485     * @hide
2486     */
2487    @ViewDebug.ExportedProperty(flagMapping = {
2488        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2489                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2490                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2491        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2492                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2493                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2494        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2495                                equals = SYSTEM_UI_FLAG_VISIBLE,
2496                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2497    })
2498    int mSystemUiVisibility;
2499
2500    /**
2501     * Reference count for transient state.
2502     * @see #setHasTransientState(boolean)
2503     */
2504    int mTransientStateCount = 0;
2505
2506    /**
2507     * Count of how many windows this view has been attached to.
2508     */
2509    int mWindowAttachCount;
2510
2511    /**
2512     * The layout parameters associated with this view and used by the parent
2513     * {@link android.view.ViewGroup} to determine how this view should be
2514     * laid out.
2515     * {@hide}
2516     */
2517    protected ViewGroup.LayoutParams mLayoutParams;
2518
2519    /**
2520     * The view flags hold various views states.
2521     * {@hide}
2522     */
2523    @ViewDebug.ExportedProperty
2524    int mViewFlags;
2525
2526    static class TransformationInfo {
2527        /**
2528         * The transform matrix for the View. This transform is calculated internally
2529         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2530         * is used by default. Do *not* use this variable directly; instead call
2531         * getMatrix(), which will automatically recalculate the matrix if necessary
2532         * to get the correct matrix based on the latest rotation and scale properties.
2533         */
2534        private final Matrix mMatrix = new Matrix();
2535
2536        /**
2537         * The transform matrix for the View. This transform is calculated internally
2538         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2539         * is used by default. Do *not* use this variable directly; instead call
2540         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2541         * to get the correct matrix based on the latest rotation and scale properties.
2542         */
2543        private Matrix mInverseMatrix;
2544
2545        /**
2546         * An internal variable that tracks whether we need to recalculate the
2547         * transform matrix, based on whether the rotation or scaleX/Y properties
2548         * have changed since the matrix was last calculated.
2549         */
2550        boolean mMatrixDirty = false;
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        private boolean mInverseMatrixDirty = true;
2558
2559        /**
2560         * A 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. This variable
2563         * is only valid after a call to updateMatrix() or to a function that
2564         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2565         */
2566        private boolean mMatrixIsIdentity = true;
2567
2568        /**
2569         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2570         */
2571        private Camera mCamera = null;
2572
2573        /**
2574         * This matrix is used when computing the matrix for 3D rotations.
2575         */
2576        private Matrix matrix3D = null;
2577
2578        /**
2579         * These prev values are used to recalculate a centered pivot point when necessary. The
2580         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2581         * set), so thes values are only used then as well.
2582         */
2583        private int mPrevWidth = -1;
2584        private int mPrevHeight = -1;
2585
2586        /**
2587         * The degrees rotation around the vertical axis through the pivot point.
2588         */
2589        @ViewDebug.ExportedProperty
2590        float mRotationY = 0f;
2591
2592        /**
2593         * The degrees rotation around the horizontal axis through the pivot point.
2594         */
2595        @ViewDebug.ExportedProperty
2596        float mRotationX = 0f;
2597
2598        /**
2599         * The degrees rotation around the pivot point.
2600         */
2601        @ViewDebug.ExportedProperty
2602        float mRotation = 0f;
2603
2604        /**
2605         * The amount of translation of the object away from its left property (post-layout).
2606         */
2607        @ViewDebug.ExportedProperty
2608        float mTranslationX = 0f;
2609
2610        /**
2611         * The amount of translation of the object away from its top property (post-layout).
2612         */
2613        @ViewDebug.ExportedProperty
2614        float mTranslationY = 0f;
2615
2616        /**
2617         * The amount of scale in the x direction around the pivot point. A
2618         * value of 1 means no scaling is applied.
2619         */
2620        @ViewDebug.ExportedProperty
2621        float mScaleX = 1f;
2622
2623        /**
2624         * The amount of scale in the y direction around the pivot point. A
2625         * value of 1 means no scaling is applied.
2626         */
2627        @ViewDebug.ExportedProperty
2628        float mScaleY = 1f;
2629
2630        /**
2631         * The x location of the point around which the view is rotated and scaled.
2632         */
2633        @ViewDebug.ExportedProperty
2634        float mPivotX = 0f;
2635
2636        /**
2637         * The y location of the point around which the view is rotated and scaled.
2638         */
2639        @ViewDebug.ExportedProperty
2640        float mPivotY = 0f;
2641
2642        /**
2643         * The opacity of the View. This is a value from 0 to 1, where 0 means
2644         * completely transparent and 1 means completely opaque.
2645         */
2646        @ViewDebug.ExportedProperty
2647        float mAlpha = 1f;
2648    }
2649
2650    TransformationInfo mTransformationInfo;
2651
2652    private boolean mLastIsOpaque;
2653
2654    /**
2655     * Convenience value to check for float values that are close enough to zero to be considered
2656     * zero.
2657     */
2658    private static final float NONZERO_EPSILON = .001f;
2659
2660    /**
2661     * The distance in pixels from the left edge of this view's parent
2662     * to the left edge of this view.
2663     * {@hide}
2664     */
2665    @ViewDebug.ExportedProperty(category = "layout")
2666    protected int mLeft;
2667    /**
2668     * The distance in pixels from the left edge of this view's parent
2669     * to the right edge of this view.
2670     * {@hide}
2671     */
2672    @ViewDebug.ExportedProperty(category = "layout")
2673    protected int mRight;
2674    /**
2675     * The distance in pixels from the top edge of this view's parent
2676     * to the top edge of this view.
2677     * {@hide}
2678     */
2679    @ViewDebug.ExportedProperty(category = "layout")
2680    protected int mTop;
2681    /**
2682     * The distance in pixels from the top edge of this view's parent
2683     * to the bottom edge of this view.
2684     * {@hide}
2685     */
2686    @ViewDebug.ExportedProperty(category = "layout")
2687    protected int mBottom;
2688
2689    /**
2690     * The offset, in pixels, by which the content of this view is scrolled
2691     * horizontally.
2692     * {@hide}
2693     */
2694    @ViewDebug.ExportedProperty(category = "scrolling")
2695    protected int mScrollX;
2696    /**
2697     * The offset, in pixels, by which the content of this view is scrolled
2698     * vertically.
2699     * {@hide}
2700     */
2701    @ViewDebug.ExportedProperty(category = "scrolling")
2702    protected int mScrollY;
2703
2704    /**
2705     * The left padding in pixels, that is the distance in pixels between the
2706     * left edge of this view and the left edge of its content.
2707     * {@hide}
2708     */
2709    @ViewDebug.ExportedProperty(category = "padding")
2710    protected int mPaddingLeft;
2711    /**
2712     * The right padding in pixels, that is the distance in pixels between the
2713     * right edge of this view and the right edge of its content.
2714     * {@hide}
2715     */
2716    @ViewDebug.ExportedProperty(category = "padding")
2717    protected int mPaddingRight;
2718    /**
2719     * The top padding in pixels, that is the distance in pixels between the
2720     * top edge of this view and the top edge of its content.
2721     * {@hide}
2722     */
2723    @ViewDebug.ExportedProperty(category = "padding")
2724    protected int mPaddingTop;
2725    /**
2726     * The bottom padding in pixels, that is the distance in pixels between the
2727     * bottom edge of this view and the bottom edge of its content.
2728     * {@hide}
2729     */
2730    @ViewDebug.ExportedProperty(category = "padding")
2731    protected int mPaddingBottom;
2732
2733    /**
2734     * The layout insets in pixels, that is the distance in pixels between the
2735     * visible edges of this view its bounds.
2736     */
2737    private Insets mLayoutInsets;
2738
2739    /**
2740     * Briefly describes the view and is primarily used for accessibility support.
2741     */
2742    private CharSequence mContentDescription;
2743
2744    /**
2745     * Cache the paddingRight set by the user to append to the scrollbar's size.
2746     *
2747     * @hide
2748     */
2749    @ViewDebug.ExportedProperty(category = "padding")
2750    protected int mUserPaddingRight;
2751
2752    /**
2753     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2754     *
2755     * @hide
2756     */
2757    @ViewDebug.ExportedProperty(category = "padding")
2758    protected int mUserPaddingBottom;
2759
2760    /**
2761     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2762     *
2763     * @hide
2764     */
2765    @ViewDebug.ExportedProperty(category = "padding")
2766    protected int mUserPaddingLeft;
2767
2768    /**
2769     * Cache if the user padding is relative.
2770     *
2771     */
2772    @ViewDebug.ExportedProperty(category = "padding")
2773    boolean mUserPaddingRelative;
2774
2775    /**
2776     * Cache the paddingStart set by the user to append to the scrollbar's size.
2777     *
2778     */
2779    @ViewDebug.ExportedProperty(category = "padding")
2780    int mUserPaddingStart;
2781
2782    /**
2783     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2784     *
2785     */
2786    @ViewDebug.ExportedProperty(category = "padding")
2787    int mUserPaddingEnd;
2788
2789    /**
2790     * @hide
2791     */
2792    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2793    /**
2794     * @hide
2795     */
2796    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2797
2798    private Drawable mBackground;
2799
2800    private int mBackgroundResource;
2801    private boolean mBackgroundSizeChanged;
2802
2803    static class ListenerInfo {
2804        /**
2805         * Listener used to dispatch focus change events.
2806         * This field should be made private, so it is hidden from the SDK.
2807         * {@hide}
2808         */
2809        protected OnFocusChangeListener mOnFocusChangeListener;
2810
2811        /**
2812         * Listeners for layout change events.
2813         */
2814        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2815
2816        /**
2817         * Listeners for attach events.
2818         */
2819        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2820
2821        /**
2822         * Listener used to dispatch click events.
2823         * This field should be made private, so it is hidden from the SDK.
2824         * {@hide}
2825         */
2826        public OnClickListener mOnClickListener;
2827
2828        /**
2829         * Listener used to dispatch long click events.
2830         * This field should be made private, so it is hidden from the SDK.
2831         * {@hide}
2832         */
2833        protected OnLongClickListener mOnLongClickListener;
2834
2835        /**
2836         * Listener used to build the context menu.
2837         * This field should be made private, so it is hidden from the SDK.
2838         * {@hide}
2839         */
2840        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2841
2842        private OnKeyListener mOnKeyListener;
2843
2844        private OnTouchListener mOnTouchListener;
2845
2846        private OnHoverListener mOnHoverListener;
2847
2848        private OnGenericMotionListener mOnGenericMotionListener;
2849
2850        private OnDragListener mOnDragListener;
2851
2852        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2853    }
2854
2855    ListenerInfo mListenerInfo;
2856
2857    /**
2858     * The application environment this view lives in.
2859     * This field should be made private, so it is hidden from the SDK.
2860     * {@hide}
2861     */
2862    protected Context mContext;
2863
2864    private final Resources mResources;
2865
2866    private ScrollabilityCache mScrollCache;
2867
2868    private int[] mDrawableState = null;
2869
2870    /**
2871     * Set to true when drawing cache is enabled and cannot be created.
2872     *
2873     * @hide
2874     */
2875    public boolean mCachingFailed;
2876
2877    private Bitmap mDrawingCache;
2878    private Bitmap mUnscaledDrawingCache;
2879    private HardwareLayer mHardwareLayer;
2880    DisplayList mDisplayList;
2881
2882    /**
2883     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2884     * the user may specify which view to go to next.
2885     */
2886    private int mNextFocusLeftId = View.NO_ID;
2887
2888    /**
2889     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2890     * the user may specify which view to go to next.
2891     */
2892    private int mNextFocusRightId = View.NO_ID;
2893
2894    /**
2895     * When this view has focus and the next focus is {@link #FOCUS_UP},
2896     * the user may specify which view to go to next.
2897     */
2898    private int mNextFocusUpId = View.NO_ID;
2899
2900    /**
2901     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2902     * the user may specify which view to go to next.
2903     */
2904    private int mNextFocusDownId = View.NO_ID;
2905
2906    /**
2907     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2908     * the user may specify which view to go to next.
2909     */
2910    int mNextFocusForwardId = View.NO_ID;
2911
2912    private CheckForLongPress mPendingCheckForLongPress;
2913    private CheckForTap mPendingCheckForTap = null;
2914    private PerformClick mPerformClick;
2915    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2916
2917    private UnsetPressedState mUnsetPressedState;
2918
2919    /**
2920     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2921     * up event while a long press is invoked as soon as the long press duration is reached, so
2922     * a long press could be performed before the tap is checked, in which case the tap's action
2923     * should not be invoked.
2924     */
2925    private boolean mHasPerformedLongPress;
2926
2927    /**
2928     * The minimum height of the view. We'll try our best to have the height
2929     * of this view to at least this amount.
2930     */
2931    @ViewDebug.ExportedProperty(category = "measurement")
2932    private int mMinHeight;
2933
2934    /**
2935     * The minimum width of the view. We'll try our best to have the width
2936     * of this view to at least this amount.
2937     */
2938    @ViewDebug.ExportedProperty(category = "measurement")
2939    private int mMinWidth;
2940
2941    /**
2942     * The delegate to handle touch events that are physically in this view
2943     * but should be handled by another view.
2944     */
2945    private TouchDelegate mTouchDelegate = null;
2946
2947    /**
2948     * Solid color to use as a background when creating the drawing cache. Enables
2949     * the cache to use 16 bit bitmaps instead of 32 bit.
2950     */
2951    private int mDrawingCacheBackgroundColor = 0;
2952
2953    /**
2954     * Special tree observer used when mAttachInfo is null.
2955     */
2956    private ViewTreeObserver mFloatingTreeObserver;
2957
2958    /**
2959     * Cache the touch slop from the context that created the view.
2960     */
2961    private int mTouchSlop;
2962
2963    /**
2964     * Object that handles automatic animation of view properties.
2965     */
2966    private ViewPropertyAnimator mAnimator = null;
2967
2968    /**
2969     * Flag indicating that a drag can cross window boundaries.  When
2970     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2971     * with this flag set, all visible applications will be able to participate
2972     * in the drag operation and receive the dragged content.
2973     *
2974     * @hide
2975     */
2976    public static final int DRAG_FLAG_GLOBAL = 1;
2977
2978    /**
2979     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2980     */
2981    private float mVerticalScrollFactor;
2982
2983    /**
2984     * Position of the vertical scroll bar.
2985     */
2986    private int mVerticalScrollbarPosition;
2987
2988    /**
2989     * Position the scroll bar at the default position as determined by the system.
2990     */
2991    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2992
2993    /**
2994     * Position the scroll bar along the left edge.
2995     */
2996    public static final int SCROLLBAR_POSITION_LEFT = 1;
2997
2998    /**
2999     * Position the scroll bar along the right edge.
3000     */
3001    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3002
3003    /**
3004     * Indicates that the view does not have a layer.
3005     *
3006     * @see #getLayerType()
3007     * @see #setLayerType(int, android.graphics.Paint)
3008     * @see #LAYER_TYPE_SOFTWARE
3009     * @see #LAYER_TYPE_HARDWARE
3010     */
3011    public static final int LAYER_TYPE_NONE = 0;
3012
3013    /**
3014     * <p>Indicates that the view has a software layer. A software layer is backed
3015     * by a bitmap and causes the view to be rendered using Android's software
3016     * rendering pipeline, even if hardware acceleration is enabled.</p>
3017     *
3018     * <p>Software layers have various usages:</p>
3019     * <p>When the application is not using hardware acceleration, a software layer
3020     * is useful to apply a specific color filter and/or blending mode and/or
3021     * translucency to a view and all its children.</p>
3022     * <p>When the application is using hardware acceleration, a software layer
3023     * is useful to render drawing primitives not supported by the hardware
3024     * accelerated pipeline. It can also be used to cache a complex view tree
3025     * into a texture and reduce the complexity of drawing operations. For instance,
3026     * when animating a complex view tree with a translation, a software layer can
3027     * be used to render the view tree only once.</p>
3028     * <p>Software layers should be avoided when the affected view tree updates
3029     * often. Every update will require to re-render the software layer, which can
3030     * potentially be slow (particularly when hardware acceleration is turned on
3031     * since the layer will have to be uploaded into a hardware texture after every
3032     * update.)</p>
3033     *
3034     * @see #getLayerType()
3035     * @see #setLayerType(int, android.graphics.Paint)
3036     * @see #LAYER_TYPE_NONE
3037     * @see #LAYER_TYPE_HARDWARE
3038     */
3039    public static final int LAYER_TYPE_SOFTWARE = 1;
3040
3041    /**
3042     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3043     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3044     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3045     * rendering pipeline, but only if hardware acceleration is turned on for the
3046     * view hierarchy. When hardware acceleration is turned off, hardware layers
3047     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3048     *
3049     * <p>A hardware layer is useful to apply a specific color filter and/or
3050     * blending mode and/or translucency to a view and all its children.</p>
3051     * <p>A hardware layer can be used to cache a complex view tree into a
3052     * texture and reduce the complexity of drawing operations. For instance,
3053     * when animating a complex view tree with a translation, a hardware layer can
3054     * be used to render the view tree only once.</p>
3055     * <p>A hardware layer can also be used to increase the rendering quality when
3056     * rotation transformations are applied on a view. It can also be used to
3057     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3058     *
3059     * @see #getLayerType()
3060     * @see #setLayerType(int, android.graphics.Paint)
3061     * @see #LAYER_TYPE_NONE
3062     * @see #LAYER_TYPE_SOFTWARE
3063     */
3064    public static final int LAYER_TYPE_HARDWARE = 2;
3065
3066    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3067            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3068            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3069            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3070    })
3071    int mLayerType = LAYER_TYPE_NONE;
3072    Paint mLayerPaint;
3073    Rect mLocalDirtyRect;
3074
3075    /**
3076     * Set to true when the view is sending hover accessibility events because it
3077     * is the innermost hovered view.
3078     */
3079    private boolean mSendingHoverAccessibilityEvents;
3080
3081    /**
3082     * Simple constructor to use when creating a view from code.
3083     *
3084     * @param context The Context the view is running in, through which it can
3085     *        access the current theme, resources, etc.
3086     */
3087    public View(Context context) {
3088        mContext = context;
3089        mResources = context != null ? context.getResources() : null;
3090        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3091        // Set layout and text direction defaults
3092        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3093                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3094                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3095                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3096        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3097        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3098        mUserPaddingStart = -1;
3099        mUserPaddingEnd = -1;
3100        mUserPaddingRelative = false;
3101    }
3102
3103    /**
3104     * Delegate for injecting accessiblity functionality.
3105     */
3106    AccessibilityDelegate mAccessibilityDelegate;
3107
3108    /**
3109     * Consistency verifier for debugging purposes.
3110     * @hide
3111     */
3112    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3113            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3114                    new InputEventConsistencyVerifier(this, 0) : null;
3115
3116    /**
3117     * Constructor that is called when inflating a view from XML. This is called
3118     * when a view is being constructed from an XML file, supplying attributes
3119     * that were specified in the XML file. This version uses a default style of
3120     * 0, so the only attribute values applied are those in the Context's Theme
3121     * and the given AttributeSet.
3122     *
3123     * <p>
3124     * The method onFinishInflate() will be called after all children have been
3125     * added.
3126     *
3127     * @param context The Context the view is running in, through which it can
3128     *        access the current theme, resources, etc.
3129     * @param attrs The attributes of the XML tag that is inflating the view.
3130     * @see #View(Context, AttributeSet, int)
3131     */
3132    public View(Context context, AttributeSet attrs) {
3133        this(context, attrs, 0);
3134    }
3135
3136    /**
3137     * Perform inflation from XML and apply a class-specific base style. This
3138     * constructor of View allows subclasses to use their own base style when
3139     * they are inflating. For example, a Button class's constructor would call
3140     * this version of the super class constructor and supply
3141     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3142     * the theme's button style to modify all of the base view attributes (in
3143     * particular its background) as well as the Button class's attributes.
3144     *
3145     * @param context The Context the view is running in, through which it can
3146     *        access the current theme, resources, etc.
3147     * @param attrs The attributes of the XML tag that is inflating the view.
3148     * @param defStyle The default style to apply to this view. If 0, no style
3149     *        will be applied (beyond what is included in the theme). This may
3150     *        either be an attribute resource, whose value will be retrieved
3151     *        from the current theme, or an explicit style resource.
3152     * @see #View(Context, AttributeSet)
3153     */
3154    public View(Context context, AttributeSet attrs, int defStyle) {
3155        this(context);
3156
3157        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3158                defStyle, 0);
3159
3160        Drawable background = null;
3161
3162        int leftPadding = -1;
3163        int topPadding = -1;
3164        int rightPadding = -1;
3165        int bottomPadding = -1;
3166        int startPadding = -1;
3167        int endPadding = -1;
3168
3169        int padding = -1;
3170
3171        int viewFlagValues = 0;
3172        int viewFlagMasks = 0;
3173
3174        boolean setScrollContainer = false;
3175
3176        int x = 0;
3177        int y = 0;
3178
3179        float tx = 0;
3180        float ty = 0;
3181        float rotation = 0;
3182        float rotationX = 0;
3183        float rotationY = 0;
3184        float sx = 1f;
3185        float sy = 1f;
3186        boolean transformSet = false;
3187
3188        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3189
3190        int overScrollMode = mOverScrollMode;
3191        final int N = a.getIndexCount();
3192        for (int i = 0; i < N; i++) {
3193            int attr = a.getIndex(i);
3194            switch (attr) {
3195                case com.android.internal.R.styleable.View_background:
3196                    background = a.getDrawable(attr);
3197                    break;
3198                case com.android.internal.R.styleable.View_padding:
3199                    padding = a.getDimensionPixelSize(attr, -1);
3200                    break;
3201                 case com.android.internal.R.styleable.View_paddingLeft:
3202                    leftPadding = a.getDimensionPixelSize(attr, -1);
3203                    break;
3204                case com.android.internal.R.styleable.View_paddingTop:
3205                    topPadding = a.getDimensionPixelSize(attr, -1);
3206                    break;
3207                case com.android.internal.R.styleable.View_paddingRight:
3208                    rightPadding = a.getDimensionPixelSize(attr, -1);
3209                    break;
3210                case com.android.internal.R.styleable.View_paddingBottom:
3211                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3212                    break;
3213                case com.android.internal.R.styleable.View_paddingStart:
3214                    startPadding = a.getDimensionPixelSize(attr, -1);
3215                    break;
3216                case com.android.internal.R.styleable.View_paddingEnd:
3217                    endPadding = a.getDimensionPixelSize(attr, -1);
3218                    break;
3219                case com.android.internal.R.styleable.View_scrollX:
3220                    x = a.getDimensionPixelOffset(attr, 0);
3221                    break;
3222                case com.android.internal.R.styleable.View_scrollY:
3223                    y = a.getDimensionPixelOffset(attr, 0);
3224                    break;
3225                case com.android.internal.R.styleable.View_alpha:
3226                    setAlpha(a.getFloat(attr, 1f));
3227                    break;
3228                case com.android.internal.R.styleable.View_transformPivotX:
3229                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3230                    break;
3231                case com.android.internal.R.styleable.View_transformPivotY:
3232                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3233                    break;
3234                case com.android.internal.R.styleable.View_translationX:
3235                    tx = a.getDimensionPixelOffset(attr, 0);
3236                    transformSet = true;
3237                    break;
3238                case com.android.internal.R.styleable.View_translationY:
3239                    ty = a.getDimensionPixelOffset(attr, 0);
3240                    transformSet = true;
3241                    break;
3242                case com.android.internal.R.styleable.View_rotation:
3243                    rotation = a.getFloat(attr, 0);
3244                    transformSet = true;
3245                    break;
3246                case com.android.internal.R.styleable.View_rotationX:
3247                    rotationX = a.getFloat(attr, 0);
3248                    transformSet = true;
3249                    break;
3250                case com.android.internal.R.styleable.View_rotationY:
3251                    rotationY = a.getFloat(attr, 0);
3252                    transformSet = true;
3253                    break;
3254                case com.android.internal.R.styleable.View_scaleX:
3255                    sx = a.getFloat(attr, 1f);
3256                    transformSet = true;
3257                    break;
3258                case com.android.internal.R.styleable.View_scaleY:
3259                    sy = a.getFloat(attr, 1f);
3260                    transformSet = true;
3261                    break;
3262                case com.android.internal.R.styleable.View_id:
3263                    mID = a.getResourceId(attr, NO_ID);
3264                    break;
3265                case com.android.internal.R.styleable.View_tag:
3266                    mTag = a.getText(attr);
3267                    break;
3268                case com.android.internal.R.styleable.View_fitsSystemWindows:
3269                    if (a.getBoolean(attr, false)) {
3270                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3271                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3272                    }
3273                    break;
3274                case com.android.internal.R.styleable.View_focusable:
3275                    if (a.getBoolean(attr, false)) {
3276                        viewFlagValues |= FOCUSABLE;
3277                        viewFlagMasks |= FOCUSABLE_MASK;
3278                    }
3279                    break;
3280                case com.android.internal.R.styleable.View_focusableInTouchMode:
3281                    if (a.getBoolean(attr, false)) {
3282                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3283                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3284                    }
3285                    break;
3286                case com.android.internal.R.styleable.View_clickable:
3287                    if (a.getBoolean(attr, false)) {
3288                        viewFlagValues |= CLICKABLE;
3289                        viewFlagMasks |= CLICKABLE;
3290                    }
3291                    break;
3292                case com.android.internal.R.styleable.View_longClickable:
3293                    if (a.getBoolean(attr, false)) {
3294                        viewFlagValues |= LONG_CLICKABLE;
3295                        viewFlagMasks |= LONG_CLICKABLE;
3296                    }
3297                    break;
3298                case com.android.internal.R.styleable.View_saveEnabled:
3299                    if (!a.getBoolean(attr, true)) {
3300                        viewFlagValues |= SAVE_DISABLED;
3301                        viewFlagMasks |= SAVE_DISABLED_MASK;
3302                    }
3303                    break;
3304                case com.android.internal.R.styleable.View_duplicateParentState:
3305                    if (a.getBoolean(attr, false)) {
3306                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3307                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3308                    }
3309                    break;
3310                case com.android.internal.R.styleable.View_visibility:
3311                    final int visibility = a.getInt(attr, 0);
3312                    if (visibility != 0) {
3313                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3314                        viewFlagMasks |= VISIBILITY_MASK;
3315                    }
3316                    break;
3317                case com.android.internal.R.styleable.View_layoutDirection:
3318                    // Clear any layout direction flags (included resolved bits) already set
3319                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3320                    // Set the layout direction flags depending on the value of the attribute
3321                    final int layoutDirection = a.getInt(attr, -1);
3322                    final int value = (layoutDirection != -1) ?
3323                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3324                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3325                    break;
3326                case com.android.internal.R.styleable.View_drawingCacheQuality:
3327                    final int cacheQuality = a.getInt(attr, 0);
3328                    if (cacheQuality != 0) {
3329                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3330                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3331                    }
3332                    break;
3333                case com.android.internal.R.styleable.View_contentDescription:
3334                    setContentDescription(a.getString(attr));
3335                    break;
3336                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3337                    if (!a.getBoolean(attr, true)) {
3338                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3339                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3340                    }
3341                    break;
3342                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3343                    if (!a.getBoolean(attr, true)) {
3344                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3345                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3346                    }
3347                    break;
3348                case R.styleable.View_scrollbars:
3349                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3350                    if (scrollbars != SCROLLBARS_NONE) {
3351                        viewFlagValues |= scrollbars;
3352                        viewFlagMasks |= SCROLLBARS_MASK;
3353                        initializeScrollbars(a);
3354                    }
3355                    break;
3356                //noinspection deprecation
3357                case R.styleable.View_fadingEdge:
3358                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3359                        // Ignore the attribute starting with ICS
3360                        break;
3361                    }
3362                    // With builds < ICS, fall through and apply fading edges
3363                case R.styleable.View_requiresFadingEdge:
3364                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3365                    if (fadingEdge != FADING_EDGE_NONE) {
3366                        viewFlagValues |= fadingEdge;
3367                        viewFlagMasks |= FADING_EDGE_MASK;
3368                        initializeFadingEdge(a);
3369                    }
3370                    break;
3371                case R.styleable.View_scrollbarStyle:
3372                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3373                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3374                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3375                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3376                    }
3377                    break;
3378                case R.styleable.View_isScrollContainer:
3379                    setScrollContainer = true;
3380                    if (a.getBoolean(attr, false)) {
3381                        setScrollContainer(true);
3382                    }
3383                    break;
3384                case com.android.internal.R.styleable.View_keepScreenOn:
3385                    if (a.getBoolean(attr, false)) {
3386                        viewFlagValues |= KEEP_SCREEN_ON;
3387                        viewFlagMasks |= KEEP_SCREEN_ON;
3388                    }
3389                    break;
3390                case R.styleable.View_filterTouchesWhenObscured:
3391                    if (a.getBoolean(attr, false)) {
3392                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3393                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3394                    }
3395                    break;
3396                case R.styleable.View_nextFocusLeft:
3397                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3398                    break;
3399                case R.styleable.View_nextFocusRight:
3400                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3401                    break;
3402                case R.styleable.View_nextFocusUp:
3403                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3404                    break;
3405                case R.styleable.View_nextFocusDown:
3406                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3407                    break;
3408                case R.styleable.View_nextFocusForward:
3409                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3410                    break;
3411                case R.styleable.View_minWidth:
3412                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3413                    break;
3414                case R.styleable.View_minHeight:
3415                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3416                    break;
3417                case R.styleable.View_onClick:
3418                    if (context.isRestricted()) {
3419                        throw new IllegalStateException("The android:onClick attribute cannot "
3420                                + "be used within a restricted context");
3421                    }
3422
3423                    final String handlerName = a.getString(attr);
3424                    if (handlerName != null) {
3425                        setOnClickListener(new OnClickListener() {
3426                            private Method mHandler;
3427
3428                            public void onClick(View v) {
3429                                if (mHandler == null) {
3430                                    try {
3431                                        mHandler = getContext().getClass().getMethod(handlerName,
3432                                                View.class);
3433                                    } catch (NoSuchMethodException e) {
3434                                        int id = getId();
3435                                        String idText = id == NO_ID ? "" : " with id '"
3436                                                + getContext().getResources().getResourceEntryName(
3437                                                    id) + "'";
3438                                        throw new IllegalStateException("Could not find a method " +
3439                                                handlerName + "(View) in the activity "
3440                                                + getContext().getClass() + " for onClick handler"
3441                                                + " on view " + View.this.getClass() + idText, e);
3442                                    }
3443                                }
3444
3445                                try {
3446                                    mHandler.invoke(getContext(), View.this);
3447                                } catch (IllegalAccessException e) {
3448                                    throw new IllegalStateException("Could not execute non "
3449                                            + "public method of the activity", e);
3450                                } catch (InvocationTargetException e) {
3451                                    throw new IllegalStateException("Could not execute "
3452                                            + "method of the activity", e);
3453                                }
3454                            }
3455                        });
3456                    }
3457                    break;
3458                case R.styleable.View_overScrollMode:
3459                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3460                    break;
3461                case R.styleable.View_verticalScrollbarPosition:
3462                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3463                    break;
3464                case R.styleable.View_layerType:
3465                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3466                    break;
3467                case R.styleable.View_textDirection:
3468                    // Clear any text direction flag already set
3469                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3470                    // Set the text direction flags depending on the value of the attribute
3471                    final int textDirection = a.getInt(attr, -1);
3472                    if (textDirection != -1) {
3473                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3474                    }
3475                    break;
3476                case R.styleable.View_textAlignment:
3477                    // Clear any text alignment flag already set
3478                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3479                    // Set the text alignment flag depending on the value of the attribute
3480                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3481                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3482                    break;
3483                case R.styleable.View_importantForAccessibility:
3484                    setImportantForAccessibility(a.getInt(attr,
3485                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3486                    break;
3487            }
3488        }
3489
3490        a.recycle();
3491
3492        setOverScrollMode(overScrollMode);
3493
3494        if (background != null) {
3495            setBackground(background);
3496        }
3497
3498        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3499        // layout direction). Those cached values will be used later during padding resolution.
3500        mUserPaddingStart = startPadding;
3501        mUserPaddingEnd = endPadding;
3502
3503        updateUserPaddingRelative();
3504
3505        if (padding >= 0) {
3506            leftPadding = padding;
3507            topPadding = padding;
3508            rightPadding = padding;
3509            bottomPadding = padding;
3510        }
3511
3512        // If the user specified the padding (either with android:padding or
3513        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3514        // use the default padding or the padding from the background drawable
3515        // (stored at this point in mPadding*)
3516        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3517                topPadding >= 0 ? topPadding : mPaddingTop,
3518                rightPadding >= 0 ? rightPadding : mPaddingRight,
3519                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3520
3521        if (viewFlagMasks != 0) {
3522            setFlags(viewFlagValues, viewFlagMasks);
3523        }
3524
3525        // Needs to be called after mViewFlags is set
3526        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3527            recomputePadding();
3528        }
3529
3530        if (x != 0 || y != 0) {
3531            scrollTo(x, y);
3532        }
3533
3534        if (transformSet) {
3535            setTranslationX(tx);
3536            setTranslationY(ty);
3537            setRotation(rotation);
3538            setRotationX(rotationX);
3539            setRotationY(rotationY);
3540            setScaleX(sx);
3541            setScaleY(sy);
3542        }
3543
3544        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3545            setScrollContainer(true);
3546        }
3547
3548        computeOpaqueFlags();
3549    }
3550
3551    private void updateUserPaddingRelative() {
3552        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3553    }
3554
3555    /**
3556     * Non-public constructor for use in testing
3557     */
3558    View() {
3559        mResources = null;
3560    }
3561
3562    /**
3563     * <p>
3564     * Initializes the fading edges from a given set of styled attributes. This
3565     * method should be called by subclasses that need fading edges and when an
3566     * instance of these subclasses is created programmatically rather than
3567     * being inflated from XML. This method is automatically called when the XML
3568     * is inflated.
3569     * </p>
3570     *
3571     * @param a the styled attributes set to initialize the fading edges from
3572     */
3573    protected void initializeFadingEdge(TypedArray a) {
3574        initScrollCache();
3575
3576        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3577                R.styleable.View_fadingEdgeLength,
3578                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3579    }
3580
3581    /**
3582     * Returns the size of the vertical faded edges used to indicate that more
3583     * content in this view is visible.
3584     *
3585     * @return The size in pixels of the vertical faded edge or 0 if vertical
3586     *         faded edges are not enabled for this view.
3587     * @attr ref android.R.styleable#View_fadingEdgeLength
3588     */
3589    public int getVerticalFadingEdgeLength() {
3590        if (isVerticalFadingEdgeEnabled()) {
3591            ScrollabilityCache cache = mScrollCache;
3592            if (cache != null) {
3593                return cache.fadingEdgeLength;
3594            }
3595        }
3596        return 0;
3597    }
3598
3599    /**
3600     * Set the size of the faded edge used to indicate that more content in this
3601     * view is available.  Will not change whether the fading edge is enabled; use
3602     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3603     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3604     * for the vertical or horizontal fading edges.
3605     *
3606     * @param length The size in pixels of the faded edge used to indicate that more
3607     *        content in this view is visible.
3608     */
3609    public void setFadingEdgeLength(int length) {
3610        initScrollCache();
3611        mScrollCache.fadingEdgeLength = length;
3612    }
3613
3614    /**
3615     * Returns the size of the horizontal faded edges used to indicate that more
3616     * content in this view is visible.
3617     *
3618     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3619     *         faded edges are not enabled for this view.
3620     * @attr ref android.R.styleable#View_fadingEdgeLength
3621     */
3622    public int getHorizontalFadingEdgeLength() {
3623        if (isHorizontalFadingEdgeEnabled()) {
3624            ScrollabilityCache cache = mScrollCache;
3625            if (cache != null) {
3626                return cache.fadingEdgeLength;
3627            }
3628        }
3629        return 0;
3630    }
3631
3632    /**
3633     * Returns the width of the vertical scrollbar.
3634     *
3635     * @return The width in pixels of the vertical scrollbar or 0 if there
3636     *         is no vertical scrollbar.
3637     */
3638    public int getVerticalScrollbarWidth() {
3639        ScrollabilityCache cache = mScrollCache;
3640        if (cache != null) {
3641            ScrollBarDrawable scrollBar = cache.scrollBar;
3642            if (scrollBar != null) {
3643                int size = scrollBar.getSize(true);
3644                if (size <= 0) {
3645                    size = cache.scrollBarSize;
3646                }
3647                return size;
3648            }
3649            return 0;
3650        }
3651        return 0;
3652    }
3653
3654    /**
3655     * Returns the height of the horizontal scrollbar.
3656     *
3657     * @return The height in pixels of the horizontal scrollbar or 0 if
3658     *         there is no horizontal scrollbar.
3659     */
3660    protected int getHorizontalScrollbarHeight() {
3661        ScrollabilityCache cache = mScrollCache;
3662        if (cache != null) {
3663            ScrollBarDrawable scrollBar = cache.scrollBar;
3664            if (scrollBar != null) {
3665                int size = scrollBar.getSize(false);
3666                if (size <= 0) {
3667                    size = cache.scrollBarSize;
3668                }
3669                return size;
3670            }
3671            return 0;
3672        }
3673        return 0;
3674    }
3675
3676    /**
3677     * <p>
3678     * Initializes the scrollbars from a given set of styled attributes. This
3679     * method should be called by subclasses that need scrollbars and when an
3680     * instance of these subclasses is created programmatically rather than
3681     * being inflated from XML. This method is automatically called when the XML
3682     * is inflated.
3683     * </p>
3684     *
3685     * @param a the styled attributes set to initialize the scrollbars from
3686     */
3687    protected void initializeScrollbars(TypedArray a) {
3688        initScrollCache();
3689
3690        final ScrollabilityCache scrollabilityCache = mScrollCache;
3691
3692        if (scrollabilityCache.scrollBar == null) {
3693            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3694        }
3695
3696        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3697
3698        if (!fadeScrollbars) {
3699            scrollabilityCache.state = ScrollabilityCache.ON;
3700        }
3701        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3702
3703
3704        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3705                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3706                        .getScrollBarFadeDuration());
3707        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3708                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3709                ViewConfiguration.getScrollDefaultDelay());
3710
3711
3712        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3713                com.android.internal.R.styleable.View_scrollbarSize,
3714                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3715
3716        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3717        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3718
3719        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3720        if (thumb != null) {
3721            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3722        }
3723
3724        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3725                false);
3726        if (alwaysDraw) {
3727            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3728        }
3729
3730        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3731        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3732
3733        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3734        if (thumb != null) {
3735            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3736        }
3737
3738        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3739                false);
3740        if (alwaysDraw) {
3741            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3742        }
3743
3744        // Apply layout direction to the new Drawables if needed
3745        final int layoutDirection = getResolvedLayoutDirection();
3746        if (track != null) {
3747            track.setLayoutDirection(layoutDirection);
3748        }
3749        if (thumb != null) {
3750            thumb.setLayoutDirection(layoutDirection);
3751        }
3752
3753        // Re-apply user/background padding so that scrollbar(s) get added
3754        resolvePadding();
3755    }
3756
3757    /**
3758     * <p>
3759     * Initalizes the scrollability cache if necessary.
3760     * </p>
3761     */
3762    private void initScrollCache() {
3763        if (mScrollCache == null) {
3764            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3765        }
3766    }
3767
3768    private ScrollabilityCache getScrollCache() {
3769        initScrollCache();
3770        return mScrollCache;
3771    }
3772
3773    /**
3774     * Set the position of the vertical scroll bar. Should be one of
3775     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3776     * {@link #SCROLLBAR_POSITION_RIGHT}.
3777     *
3778     * @param position Where the vertical scroll bar should be positioned.
3779     */
3780    public void setVerticalScrollbarPosition(int position) {
3781        if (mVerticalScrollbarPosition != position) {
3782            mVerticalScrollbarPosition = position;
3783            computeOpaqueFlags();
3784            resolvePadding();
3785        }
3786    }
3787
3788    /**
3789     * @return The position where the vertical scroll bar will show, if applicable.
3790     * @see #setVerticalScrollbarPosition(int)
3791     */
3792    public int getVerticalScrollbarPosition() {
3793        return mVerticalScrollbarPosition;
3794    }
3795
3796    ListenerInfo getListenerInfo() {
3797        if (mListenerInfo != null) {
3798            return mListenerInfo;
3799        }
3800        mListenerInfo = new ListenerInfo();
3801        return mListenerInfo;
3802    }
3803
3804    /**
3805     * Register a callback to be invoked when focus of this view changed.
3806     *
3807     * @param l The callback that will run.
3808     */
3809    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3810        getListenerInfo().mOnFocusChangeListener = l;
3811    }
3812
3813    /**
3814     * Add a listener that will be called when the bounds of the view change due to
3815     * layout processing.
3816     *
3817     * @param listener The listener that will be called when layout bounds change.
3818     */
3819    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3820        ListenerInfo li = getListenerInfo();
3821        if (li.mOnLayoutChangeListeners == null) {
3822            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3823        }
3824        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3825            li.mOnLayoutChangeListeners.add(listener);
3826        }
3827    }
3828
3829    /**
3830     * Remove a listener for layout changes.
3831     *
3832     * @param listener The listener for layout bounds change.
3833     */
3834    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3835        ListenerInfo li = mListenerInfo;
3836        if (li == null || li.mOnLayoutChangeListeners == null) {
3837            return;
3838        }
3839        li.mOnLayoutChangeListeners.remove(listener);
3840    }
3841
3842    /**
3843     * Add a listener for attach state changes.
3844     *
3845     * This listener will be called whenever this view is attached or detached
3846     * from a window. Remove the listener using
3847     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3848     *
3849     * @param listener Listener to attach
3850     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3851     */
3852    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3853        ListenerInfo li = getListenerInfo();
3854        if (li.mOnAttachStateChangeListeners == null) {
3855            li.mOnAttachStateChangeListeners
3856                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3857        }
3858        li.mOnAttachStateChangeListeners.add(listener);
3859    }
3860
3861    /**
3862     * Remove a listener for attach state changes. The listener will receive no further
3863     * notification of window attach/detach events.
3864     *
3865     * @param listener Listener to remove
3866     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3867     */
3868    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3869        ListenerInfo li = mListenerInfo;
3870        if (li == null || li.mOnAttachStateChangeListeners == null) {
3871            return;
3872        }
3873        li.mOnAttachStateChangeListeners.remove(listener);
3874    }
3875
3876    /**
3877     * Returns the focus-change callback registered for this view.
3878     *
3879     * @return The callback, or null if one is not registered.
3880     */
3881    public OnFocusChangeListener getOnFocusChangeListener() {
3882        ListenerInfo li = mListenerInfo;
3883        return li != null ? li.mOnFocusChangeListener : null;
3884    }
3885
3886    /**
3887     * Register a callback to be invoked when this view is clicked. If this view is not
3888     * clickable, it becomes clickable.
3889     *
3890     * @param l The callback that will run
3891     *
3892     * @see #setClickable(boolean)
3893     */
3894    public void setOnClickListener(OnClickListener l) {
3895        if (!isClickable()) {
3896            setClickable(true);
3897        }
3898        getListenerInfo().mOnClickListener = l;
3899    }
3900
3901    /**
3902     * Return whether this view has an attached OnClickListener.  Returns
3903     * true if there is a listener, false if there is none.
3904     */
3905    public boolean hasOnClickListeners() {
3906        ListenerInfo li = mListenerInfo;
3907        return (li != null && li.mOnClickListener != null);
3908    }
3909
3910    /**
3911     * Register a callback to be invoked when this view is clicked and held. If this view is not
3912     * long clickable, it becomes long clickable.
3913     *
3914     * @param l The callback that will run
3915     *
3916     * @see #setLongClickable(boolean)
3917     */
3918    public void setOnLongClickListener(OnLongClickListener l) {
3919        if (!isLongClickable()) {
3920            setLongClickable(true);
3921        }
3922        getListenerInfo().mOnLongClickListener = l;
3923    }
3924
3925    /**
3926     * Register a callback to be invoked when the context menu for this view is
3927     * being built. If this view is not long clickable, it becomes long clickable.
3928     *
3929     * @param l The callback that will run
3930     *
3931     */
3932    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3933        if (!isLongClickable()) {
3934            setLongClickable(true);
3935        }
3936        getListenerInfo().mOnCreateContextMenuListener = l;
3937    }
3938
3939    /**
3940     * Call this view's OnClickListener, if it is defined.  Performs all normal
3941     * actions associated with clicking: reporting accessibility event, playing
3942     * a sound, etc.
3943     *
3944     * @return True there was an assigned OnClickListener that was called, false
3945     *         otherwise is returned.
3946     */
3947    public boolean performClick() {
3948        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3949
3950        ListenerInfo li = mListenerInfo;
3951        if (li != null && li.mOnClickListener != null) {
3952            playSoundEffect(SoundEffectConstants.CLICK);
3953            li.mOnClickListener.onClick(this);
3954            return true;
3955        }
3956
3957        return false;
3958    }
3959
3960    /**
3961     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3962     * this only calls the listener, and does not do any associated clicking
3963     * actions like reporting an accessibility event.
3964     *
3965     * @return True there was an assigned OnClickListener that was called, false
3966     *         otherwise is returned.
3967     */
3968    public boolean callOnClick() {
3969        ListenerInfo li = mListenerInfo;
3970        if (li != null && li.mOnClickListener != null) {
3971            li.mOnClickListener.onClick(this);
3972            return true;
3973        }
3974        return false;
3975    }
3976
3977    /**
3978     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3979     * OnLongClickListener did not consume the event.
3980     *
3981     * @return True if one of the above receivers consumed the event, false otherwise.
3982     */
3983    public boolean performLongClick() {
3984        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3985
3986        boolean handled = false;
3987        ListenerInfo li = mListenerInfo;
3988        if (li != null && li.mOnLongClickListener != null) {
3989            handled = li.mOnLongClickListener.onLongClick(View.this);
3990        }
3991        if (!handled) {
3992            handled = showContextMenu();
3993        }
3994        if (handled) {
3995            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3996        }
3997        return handled;
3998    }
3999
4000    /**
4001     * Performs button-related actions during a touch down event.
4002     *
4003     * @param event The event.
4004     * @return True if the down was consumed.
4005     *
4006     * @hide
4007     */
4008    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4009        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4010            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4011                return true;
4012            }
4013        }
4014        return false;
4015    }
4016
4017    /**
4018     * Bring up the context menu for this view.
4019     *
4020     * @return Whether a context menu was displayed.
4021     */
4022    public boolean showContextMenu() {
4023        return getParent().showContextMenuForChild(this);
4024    }
4025
4026    /**
4027     * Bring up the context menu for this view, referring to the item under the specified point.
4028     *
4029     * @param x The referenced x coordinate.
4030     * @param y The referenced y coordinate.
4031     * @param metaState The keyboard modifiers that were pressed.
4032     * @return Whether a context menu was displayed.
4033     *
4034     * @hide
4035     */
4036    public boolean showContextMenu(float x, float y, int metaState) {
4037        return showContextMenu();
4038    }
4039
4040    /**
4041     * Start an action mode.
4042     *
4043     * @param callback Callback that will control the lifecycle of the action mode
4044     * @return The new action mode if it is started, null otherwise
4045     *
4046     * @see ActionMode
4047     */
4048    public ActionMode startActionMode(ActionMode.Callback callback) {
4049        ViewParent parent = getParent();
4050        if (parent == null) return null;
4051        return parent.startActionModeForChild(this, callback);
4052    }
4053
4054    /**
4055     * Register a callback to be invoked when a hardware key is pressed in this view.
4056     * Key presses in software input methods will generally not trigger the methods of
4057     * this listener.
4058     * @param l the key listener to attach to this view
4059     */
4060    public void setOnKeyListener(OnKeyListener l) {
4061        getListenerInfo().mOnKeyListener = l;
4062    }
4063
4064    /**
4065     * Register a callback to be invoked when a touch event is sent to this view.
4066     * @param l the touch listener to attach to this view
4067     */
4068    public void setOnTouchListener(OnTouchListener l) {
4069        getListenerInfo().mOnTouchListener = l;
4070    }
4071
4072    /**
4073     * Register a callback to be invoked when a generic motion event is sent to this view.
4074     * @param l the generic motion listener to attach to this view
4075     */
4076    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4077        getListenerInfo().mOnGenericMotionListener = l;
4078    }
4079
4080    /**
4081     * Register a callback to be invoked when a hover event is sent to this view.
4082     * @param l the hover listener to attach to this view
4083     */
4084    public void setOnHoverListener(OnHoverListener l) {
4085        getListenerInfo().mOnHoverListener = l;
4086    }
4087
4088    /**
4089     * Register a drag event listener callback object for this View. The parameter is
4090     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4091     * View, the system calls the
4092     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4093     * @param l An implementation of {@link android.view.View.OnDragListener}.
4094     */
4095    public void setOnDragListener(OnDragListener l) {
4096        getListenerInfo().mOnDragListener = l;
4097    }
4098
4099    /**
4100     * Give this view focus. This will cause
4101     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4102     *
4103     * Note: this does not check whether this {@link View} should get focus, it just
4104     * gives it focus no matter what.  It should only be called internally by framework
4105     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4106     *
4107     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4108     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4109     *        focus moved when requestFocus() is called. It may not always
4110     *        apply, in which case use the default View.FOCUS_DOWN.
4111     * @param previouslyFocusedRect The rectangle of the view that had focus
4112     *        prior in this View's coordinate system.
4113     */
4114    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4115        if (DBG) {
4116            System.out.println(this + " requestFocus()");
4117        }
4118
4119        if ((mPrivateFlags & FOCUSED) == 0) {
4120            mPrivateFlags |= FOCUSED;
4121
4122            if (mParent != null) {
4123                mParent.requestChildFocus(this, this);
4124            }
4125
4126            onFocusChanged(true, direction, previouslyFocusedRect);
4127            refreshDrawableState();
4128
4129            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4130                notifyAccessibilityStateChanged();
4131            }
4132        }
4133    }
4134
4135    /**
4136     * Request that a rectangle of this view be visible on the screen,
4137     * scrolling if necessary just enough.
4138     *
4139     * <p>A View should call this if it maintains some notion of which part
4140     * of its content is interesting.  For example, a text editing view
4141     * should call this when its cursor moves.
4142     *
4143     * @param rectangle The rectangle.
4144     * @return Whether any parent scrolled.
4145     */
4146    public boolean requestRectangleOnScreen(Rect rectangle) {
4147        return requestRectangleOnScreen(rectangle, false);
4148    }
4149
4150    /**
4151     * Request that a rectangle of this view be visible on the screen,
4152     * scrolling if necessary just enough.
4153     *
4154     * <p>A View should call this if it maintains some notion of which part
4155     * of its content is interesting.  For example, a text editing view
4156     * should call this when its cursor moves.
4157     *
4158     * <p>When <code>immediate</code> is set to true, scrolling will not be
4159     * animated.
4160     *
4161     * @param rectangle The rectangle.
4162     * @param immediate True to forbid animated scrolling, false otherwise
4163     * @return Whether any parent scrolled.
4164     */
4165    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4166        View child = this;
4167        ViewParent parent = mParent;
4168        boolean scrolled = false;
4169        while (parent != null) {
4170            scrolled |= parent.requestChildRectangleOnScreen(child,
4171                    rectangle, immediate);
4172
4173            // offset rect so next call has the rectangle in the
4174            // coordinate system of its direct child.
4175            rectangle.offset(child.getLeft(), child.getTop());
4176            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4177
4178            if (!(parent instanceof View)) {
4179                break;
4180            }
4181
4182            child = (View) parent;
4183            parent = child.getParent();
4184        }
4185        return scrolled;
4186    }
4187
4188    /**
4189     * Called when this view wants to give up focus. If focus is cleared
4190     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4191     * <p>
4192     * <strong>Note:</strong> When a View clears focus the framework is trying
4193     * to give focus to the first focusable View from the top. Hence, if this
4194     * View is the first from the top that can take focus, then all callbacks
4195     * related to clearing focus will be invoked after wich the framework will
4196     * give focus to this view.
4197     * </p>
4198     */
4199    public void clearFocus() {
4200        if (DBG) {
4201            System.out.println(this + " clearFocus()");
4202        }
4203
4204        if ((mPrivateFlags & FOCUSED) != 0) {
4205            mPrivateFlags &= ~FOCUSED;
4206
4207            if (mParent != null) {
4208                mParent.clearChildFocus(this);
4209            }
4210
4211            onFocusChanged(false, 0, null);
4212
4213            refreshDrawableState();
4214
4215            ensureInputFocusOnFirstFocusable();
4216
4217            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4218                notifyAccessibilityStateChanged();
4219            }
4220        }
4221    }
4222
4223    void ensureInputFocusOnFirstFocusable() {
4224        View root = getRootView();
4225        if (root != null) {
4226            root.requestFocus();
4227        }
4228    }
4229
4230    /**
4231     * Called internally by the view system when a new view is getting focus.
4232     * This is what clears the old focus.
4233     */
4234    void unFocus() {
4235        if (DBG) {
4236            System.out.println(this + " unFocus()");
4237        }
4238
4239        if ((mPrivateFlags & FOCUSED) != 0) {
4240            mPrivateFlags &= ~FOCUSED;
4241
4242            onFocusChanged(false, 0, null);
4243            refreshDrawableState();
4244
4245            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4246                notifyAccessibilityStateChanged();
4247            }
4248        }
4249    }
4250
4251    /**
4252     * Returns true if this view has focus iteself, or is the ancestor of the
4253     * view that has focus.
4254     *
4255     * @return True if this view has or contains focus, false otherwise.
4256     */
4257    @ViewDebug.ExportedProperty(category = "focus")
4258    public boolean hasFocus() {
4259        return (mPrivateFlags & FOCUSED) != 0;
4260    }
4261
4262    /**
4263     * Returns true if this view is focusable or if it contains a reachable View
4264     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4265     * is a View whose parents do not block descendants focus.
4266     *
4267     * Only {@link #VISIBLE} views are considered focusable.
4268     *
4269     * @return True if the view is focusable or if the view contains a focusable
4270     *         View, false otherwise.
4271     *
4272     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4273     */
4274    public boolean hasFocusable() {
4275        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4276    }
4277
4278    /**
4279     * Called by the view system when the focus state of this view changes.
4280     * When the focus change event is caused by directional navigation, direction
4281     * and previouslyFocusedRect provide insight into where the focus is coming from.
4282     * When overriding, be sure to call up through to the super class so that
4283     * the standard focus handling will occur.
4284     *
4285     * @param gainFocus True if the View has focus; false otherwise.
4286     * @param direction The direction focus has moved when requestFocus()
4287     *                  is called to give this view focus. Values are
4288     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4289     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4290     *                  It may not always apply, in which case use the default.
4291     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4292     *        system, of the previously focused view.  If applicable, this will be
4293     *        passed in as finer grained information about where the focus is coming
4294     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4295     */
4296    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4297        if (gainFocus) {
4298            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4299                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4300            }
4301        }
4302
4303        InputMethodManager imm = InputMethodManager.peekInstance();
4304        if (!gainFocus) {
4305            if (isPressed()) {
4306                setPressed(false);
4307            }
4308            if (imm != null && mAttachInfo != null
4309                    && mAttachInfo.mHasWindowFocus) {
4310                imm.focusOut(this);
4311            }
4312            onFocusLost();
4313        } else if (imm != null && mAttachInfo != null
4314                && mAttachInfo.mHasWindowFocus) {
4315            imm.focusIn(this);
4316        }
4317
4318        invalidate(true);
4319        ListenerInfo li = mListenerInfo;
4320        if (li != null && li.mOnFocusChangeListener != null) {
4321            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4322        }
4323
4324        if (mAttachInfo != null) {
4325            mAttachInfo.mKeyDispatchState.reset(this);
4326        }
4327    }
4328
4329    /**
4330     * Sends an accessibility event of the given type. If accessiiblity is
4331     * not enabled this method has no effect. The default implementation calls
4332     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4333     * to populate information about the event source (this View), then calls
4334     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4335     * populate the text content of the event source including its descendants,
4336     * and last calls
4337     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4338     * on its parent to resuest sending of the event to interested parties.
4339     * <p>
4340     * If an {@link AccessibilityDelegate} has been specified via calling
4341     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4342     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4343     * responsible for handling this call.
4344     * </p>
4345     *
4346     * @param eventType The type of the event to send, as defined by several types from
4347     * {@link android.view.accessibility.AccessibilityEvent}, such as
4348     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4349     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4350     *
4351     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4352     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4353     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4354     * @see AccessibilityDelegate
4355     */
4356    public void sendAccessibilityEvent(int eventType) {
4357        if (mAccessibilityDelegate != null) {
4358            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4359        } else {
4360            sendAccessibilityEventInternal(eventType);
4361        }
4362    }
4363
4364    /**
4365     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4366     * {@link AccessibilityEvent} to make an announcement which is related to some
4367     * sort of a context change for which none of the events representing UI transitions
4368     * is a good fit. For example, announcing a new page in a book. If accessibility
4369     * is not enabled this method does nothing.
4370     *
4371     * @param text The announcement text.
4372     */
4373    public void announceForAccessibility(CharSequence text) {
4374        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4375            AccessibilityEvent event = AccessibilityEvent.obtain(
4376                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4377            onInitializeAccessibilityEvent(event);
4378            event.getText().add(text);
4379            event.setContentDescription(null);
4380            mParent.requestSendAccessibilityEvent(this, event);
4381        }
4382    }
4383
4384    /**
4385     * @see #sendAccessibilityEvent(int)
4386     *
4387     * Note: Called from the default {@link AccessibilityDelegate}.
4388     */
4389    void sendAccessibilityEventInternal(int eventType) {
4390        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4391            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4392        }
4393    }
4394
4395    /**
4396     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4397     * takes as an argument an empty {@link AccessibilityEvent} and does not
4398     * perform a check whether accessibility is enabled.
4399     * <p>
4400     * If an {@link AccessibilityDelegate} has been specified via calling
4401     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4402     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4403     * is responsible for handling this call.
4404     * </p>
4405     *
4406     * @param event The event to send.
4407     *
4408     * @see #sendAccessibilityEvent(int)
4409     */
4410    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4411        if (mAccessibilityDelegate != null) {
4412            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4413        } else {
4414            sendAccessibilityEventUncheckedInternal(event);
4415        }
4416    }
4417
4418    /**
4419     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4420     *
4421     * Note: Called from the default {@link AccessibilityDelegate}.
4422     */
4423    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4424        if (!isShown()) {
4425            return;
4426        }
4427        onInitializeAccessibilityEvent(event);
4428        // Only a subset of accessibility events populates text content.
4429        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4430            dispatchPopulateAccessibilityEvent(event);
4431        }
4432        // In the beginning we called #isShown(), so we know that getParent() is not null.
4433        getParent().requestSendAccessibilityEvent(this, event);
4434    }
4435
4436    /**
4437     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4438     * to its children for adding their text content to the event. Note that the
4439     * event text is populated in a separate dispatch path since we add to the
4440     * event not only the text of the source but also the text of all its descendants.
4441     * A typical implementation will call
4442     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4443     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4444     * on each child. Override this method if custom population of the event text
4445     * content is required.
4446     * <p>
4447     * If an {@link AccessibilityDelegate} has been specified via calling
4448     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4449     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4450     * is responsible for handling this call.
4451     * </p>
4452     * <p>
4453     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4454     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4455     * </p>
4456     *
4457     * @param event The event.
4458     *
4459     * @return True if the event population was completed.
4460     */
4461    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4462        if (mAccessibilityDelegate != null) {
4463            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4464        } else {
4465            return dispatchPopulateAccessibilityEventInternal(event);
4466        }
4467    }
4468
4469    /**
4470     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4471     *
4472     * Note: Called from the default {@link AccessibilityDelegate}.
4473     */
4474    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4475        onPopulateAccessibilityEvent(event);
4476        return false;
4477    }
4478
4479    /**
4480     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4481     * giving a chance to this View to populate the accessibility event with its
4482     * text content. While this method is free to modify event
4483     * attributes other than text content, doing so should normally be performed in
4484     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4485     * <p>
4486     * Example: Adding formatted date string to an accessibility event in addition
4487     *          to the text added by the super implementation:
4488     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4489     *     super.onPopulateAccessibilityEvent(event);
4490     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4491     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4492     *         mCurrentDate.getTimeInMillis(), flags);
4493     *     event.getText().add(selectedDateUtterance);
4494     * }</pre>
4495     * <p>
4496     * If an {@link AccessibilityDelegate} has been specified via calling
4497     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4498     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4499     * is responsible for handling this call.
4500     * </p>
4501     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4502     * information to the event, in case the default implementation has basic information to add.
4503     * </p>
4504     *
4505     * @param event The accessibility event which to populate.
4506     *
4507     * @see #sendAccessibilityEvent(int)
4508     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4509     */
4510    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4511        if (mAccessibilityDelegate != null) {
4512            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4513        } else {
4514            onPopulateAccessibilityEventInternal(event);
4515        }
4516    }
4517
4518    /**
4519     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4520     *
4521     * Note: Called from the default {@link AccessibilityDelegate}.
4522     */
4523    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4524
4525    }
4526
4527    /**
4528     * Initializes an {@link AccessibilityEvent} with information about
4529     * this View which is the event source. In other words, the source of
4530     * an accessibility event is the view whose state change triggered firing
4531     * the event.
4532     * <p>
4533     * Example: Setting the password property of an event in addition
4534     *          to properties set by the super implementation:
4535     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4536     *     super.onInitializeAccessibilityEvent(event);
4537     *     event.setPassword(true);
4538     * }</pre>
4539     * <p>
4540     * If an {@link AccessibilityDelegate} has been specified via calling
4541     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4542     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4543     * is responsible for handling this call.
4544     * </p>
4545     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4546     * information to the event, in case the default implementation has basic information to add.
4547     * </p>
4548     * @param event The event to initialize.
4549     *
4550     * @see #sendAccessibilityEvent(int)
4551     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4552     */
4553    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4554        if (mAccessibilityDelegate != null) {
4555            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4556        } else {
4557            onInitializeAccessibilityEventInternal(event);
4558        }
4559    }
4560
4561    /**
4562     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4563     *
4564     * Note: Called from the default {@link AccessibilityDelegate}.
4565     */
4566    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4567        event.setSource(this);
4568        event.setClassName(View.class.getName());
4569        event.setPackageName(getContext().getPackageName());
4570        event.setEnabled(isEnabled());
4571        event.setContentDescription(mContentDescription);
4572
4573        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4574            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4575            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4576                    FOCUSABLES_ALL);
4577            event.setItemCount(focusablesTempList.size());
4578            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4579            focusablesTempList.clear();
4580        }
4581    }
4582
4583    /**
4584     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4585     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4586     * This method is responsible for obtaining an accessibility node info from a
4587     * pool of reusable instances and calling
4588     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4589     * initialize the former.
4590     * <p>
4591     * Note: The client is responsible for recycling the obtained instance by calling
4592     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4593     * </p>
4594     *
4595     * @return A populated {@link AccessibilityNodeInfo}.
4596     *
4597     * @see AccessibilityNodeInfo
4598     */
4599    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4600        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4601        if (provider != null) {
4602            return provider.createAccessibilityNodeInfo(View.NO_ID);
4603        } else {
4604            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4605            onInitializeAccessibilityNodeInfo(info);
4606            return info;
4607        }
4608    }
4609
4610    /**
4611     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4612     * The base implementation sets:
4613     * <ul>
4614     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4615     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4616     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4617     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4618     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4619     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4620     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4621     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4622     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4623     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4624     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4625     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4626     * </ul>
4627     * <p>
4628     * Subclasses should override this method, call the super implementation,
4629     * and set additional attributes.
4630     * </p>
4631     * <p>
4632     * If an {@link AccessibilityDelegate} has been specified via calling
4633     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4634     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4635     * is responsible for handling this call.
4636     * </p>
4637     *
4638     * @param info The instance to initialize.
4639     */
4640    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4641        if (mAccessibilityDelegate != null) {
4642            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4643        } else {
4644            onInitializeAccessibilityNodeInfoInternal(info);
4645        }
4646    }
4647
4648    /**
4649     * Gets the location of this view in screen coordintates.
4650     *
4651     * @param outRect The output location
4652     */
4653    private void getBoundsOnScreen(Rect outRect) {
4654        if (mAttachInfo == null) {
4655            return;
4656        }
4657
4658        RectF position = mAttachInfo.mTmpTransformRect;
4659        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4660
4661        if (!hasIdentityMatrix()) {
4662            getMatrix().mapRect(position);
4663        }
4664
4665        position.offset(mLeft, mTop);
4666
4667        ViewParent parent = mParent;
4668        while (parent instanceof View) {
4669            View parentView = (View) parent;
4670
4671            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4672
4673            if (!parentView.hasIdentityMatrix()) {
4674                parentView.getMatrix().mapRect(position);
4675            }
4676
4677            position.offset(parentView.mLeft, parentView.mTop);
4678
4679            parent = parentView.mParent;
4680        }
4681
4682        if (parent instanceof ViewRootImpl) {
4683            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4684            position.offset(0, -viewRootImpl.mCurScrollY);
4685        }
4686
4687        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4688
4689        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4690                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4691    }
4692
4693    /**
4694     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4695     *
4696     * Note: Called from the default {@link AccessibilityDelegate}.
4697     */
4698    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4699        Rect bounds = mAttachInfo.mTmpInvalRect;
4700
4701        getDrawingRect(bounds);
4702        info.setBoundsInParent(bounds);
4703
4704        getBoundsOnScreen(bounds);
4705        info.setBoundsInScreen(bounds);
4706
4707        ViewParent parent = getParentForAccessibility();
4708        if (parent instanceof View) {
4709            info.setParent((View) parent);
4710        }
4711
4712        info.setVisibleToUser(isVisibleToUser());
4713
4714        info.setPackageName(mContext.getPackageName());
4715        info.setClassName(View.class.getName());
4716        info.setContentDescription(getContentDescription());
4717
4718        info.setEnabled(isEnabled());
4719        info.setClickable(isClickable());
4720        info.setFocusable(isFocusable());
4721        info.setFocused(isFocused());
4722        info.setAccessibilityFocused(isAccessibilityFocused());
4723        info.setSelected(isSelected());
4724        info.setLongClickable(isLongClickable());
4725
4726        // TODO: These make sense only if we are in an AdapterView but all
4727        // views can be selected. Maybe from accessiiblity perspective
4728        // we should report as selectable view in an AdapterView.
4729        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4730        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4731
4732        if (isFocusable()) {
4733            if (isFocused()) {
4734                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4735            } else {
4736                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4737            }
4738        }
4739
4740        if (!isAccessibilityFocused()) {
4741            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4742        } else {
4743            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4744        }
4745
4746        if (isClickable() && isEnabled()) {
4747            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4748        }
4749
4750        if (isLongClickable() && isEnabled()) {
4751            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4752        }
4753
4754        if (mContentDescription != null && mContentDescription.length() > 0) {
4755            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4756            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4757            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4758                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4759                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4760        }
4761    }
4762
4763    /**
4764     * Returns the delta between the actual and last reported window left.
4765     *
4766     * @hide
4767     */
4768    public int getActualAndReportedWindowLeftDelta() {
4769//        if (mAttachInfo != null) {
4770//            return mAttachInfo.mActualWindowLeft - mAttachInfo.mWindowLeft;
4771//        }
4772        return 0;
4773    }
4774
4775    /**
4776     * Returns the delta between the actual and last reported window top.
4777     *
4778     * @hide
4779     */
4780    public int getActualAndReportedWindowTopDelta() {
4781//        if (mAttachInfo != null) {
4782//            return mAttachInfo.mActualWindowTop - mAttachInfo.mWindowTop;
4783//        }
4784        return 0;
4785    }
4786
4787    /**
4788     * Computes whether this view is visible to the user. Such a view is
4789     * attached, visible, all its predecessors are visible, it is not clipped
4790     * entirely by its predecessors, and has an alpha greater than zero.
4791     *
4792     * @return Whether the view is visible on the screen.
4793     *
4794     * @hide
4795     */
4796    protected boolean isVisibleToUser() {
4797        return isVisibleToUser(null);
4798    }
4799
4800    /**
4801     * Computes whether the given portion of this view is visible to the user. Such a view is
4802     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4803     * the specified portion is not clipped entirely by its predecessors.
4804     *
4805     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4806     *                    <code>null</code>, and the entire view will be tested in this case.
4807     *                    When <code>true</code> is returned by the function, the actual visible
4808     *                    region will be stored in this parameter; that is, if boundInView is fully
4809     *                    contained within the view, no modification will be made, otherwise regions
4810     *                    outside of the visible area of the view will be clipped.
4811     *
4812     * @return Whether the specified portion of the view is visible on the screen.
4813     *
4814     * @hide
4815     */
4816    protected boolean isVisibleToUser(Rect boundInView) {
4817        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4818        Point offset = mAttachInfo.mPoint;
4819        // The first two checks are made also made by isShown() which
4820        // however traverses the tree up to the parent to catch that.
4821        // Therefore, we do some fail fast check to minimize the up
4822        // tree traversal.
4823        boolean isVisible = mAttachInfo != null
4824            && mAttachInfo.mWindowVisibility == View.VISIBLE
4825            && getAlpha() > 0
4826            && isShown()
4827            && getGlobalVisibleRect(visibleRect, offset);
4828            if (isVisible && boundInView != null) {
4829                visibleRect.offset(-offset.x, -offset.y);
4830                isVisible &= boundInView.intersect(visibleRect);
4831            }
4832            return isVisible;
4833    }
4834
4835    /**
4836     * Sets a delegate for implementing accessibility support via compositon as
4837     * opposed to inheritance. The delegate's primary use is for implementing
4838     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4839     *
4840     * @param delegate The delegate instance.
4841     *
4842     * @see AccessibilityDelegate
4843     */
4844    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4845        mAccessibilityDelegate = delegate;
4846    }
4847
4848    /**
4849     * Gets the provider for managing a virtual view hierarchy rooted at this View
4850     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4851     * that explore the window content.
4852     * <p>
4853     * If this method returns an instance, this instance is responsible for managing
4854     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4855     * View including the one representing the View itself. Similarly the returned
4856     * instance is responsible for performing accessibility actions on any virtual
4857     * view or the root view itself.
4858     * </p>
4859     * <p>
4860     * If an {@link AccessibilityDelegate} has been specified via calling
4861     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4862     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4863     * is responsible for handling this call.
4864     * </p>
4865     *
4866     * @return The provider.
4867     *
4868     * @see AccessibilityNodeProvider
4869     */
4870    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4871        if (mAccessibilityDelegate != null) {
4872            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4873        } else {
4874            return null;
4875        }
4876    }
4877
4878    /**
4879     * Gets the unique identifier of this view on the screen for accessibility purposes.
4880     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4881     *
4882     * @return The view accessibility id.
4883     *
4884     * @hide
4885     */
4886    public int getAccessibilityViewId() {
4887        if (mAccessibilityViewId == NO_ID) {
4888            mAccessibilityViewId = sNextAccessibilityViewId++;
4889        }
4890        return mAccessibilityViewId;
4891    }
4892
4893    /**
4894     * Gets the unique identifier of the window in which this View reseides.
4895     *
4896     * @return The window accessibility id.
4897     *
4898     * @hide
4899     */
4900    public int getAccessibilityWindowId() {
4901        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4902    }
4903
4904    /**
4905     * Gets the {@link View} description. It briefly describes the view and is
4906     * primarily used for accessibility support. Set this property to enable
4907     * better accessibility support for your application. This is especially
4908     * true for views that do not have textual representation (For example,
4909     * ImageButton).
4910     *
4911     * @return The content description.
4912     *
4913     * @attr ref android.R.styleable#View_contentDescription
4914     */
4915    @ViewDebug.ExportedProperty(category = "accessibility")
4916    public CharSequence getContentDescription() {
4917        return mContentDescription;
4918    }
4919
4920    /**
4921     * Sets the {@link View} description. It briefly describes the view and is
4922     * primarily used for accessibility support. Set this property to enable
4923     * better accessibility support for your application. This is especially
4924     * true for views that do not have textual representation (For example,
4925     * ImageButton).
4926     *
4927     * @param contentDescription The content description.
4928     *
4929     * @attr ref android.R.styleable#View_contentDescription
4930     */
4931    @RemotableViewMethod
4932    public void setContentDescription(CharSequence contentDescription) {
4933        mContentDescription = contentDescription;
4934        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
4935        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
4936             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
4937        }
4938    }
4939
4940    /**
4941     * Invoked whenever this view loses focus, either by losing window focus or by losing
4942     * focus within its window. This method can be used to clear any state tied to the
4943     * focus. For instance, if a button is held pressed with the trackball and the window
4944     * loses focus, this method can be used to cancel the press.
4945     *
4946     * Subclasses of View overriding this method should always call super.onFocusLost().
4947     *
4948     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4949     * @see #onWindowFocusChanged(boolean)
4950     *
4951     * @hide pending API council approval
4952     */
4953    protected void onFocusLost() {
4954        resetPressedState();
4955    }
4956
4957    private void resetPressedState() {
4958        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4959            return;
4960        }
4961
4962        if (isPressed()) {
4963            setPressed(false);
4964
4965            if (!mHasPerformedLongPress) {
4966                removeLongPressCallback();
4967            }
4968        }
4969    }
4970
4971    /**
4972     * Returns true if this view has focus
4973     *
4974     * @return True if this view has focus, false otherwise.
4975     */
4976    @ViewDebug.ExportedProperty(category = "focus")
4977    public boolean isFocused() {
4978        return (mPrivateFlags & FOCUSED) != 0;
4979    }
4980
4981    /**
4982     * Find the view in the hierarchy rooted at this view that currently has
4983     * focus.
4984     *
4985     * @return The view that currently has focus, or null if no focused view can
4986     *         be found.
4987     */
4988    public View findFocus() {
4989        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4990    }
4991
4992    /**
4993     * Indicates whether this view is one of the set of scrollable containers in
4994     * its window.
4995     *
4996     * @return whether this view is one of the set of scrollable containers in
4997     * its window
4998     *
4999     * @attr ref android.R.styleable#View_isScrollContainer
5000     */
5001    public boolean isScrollContainer() {
5002        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5003    }
5004
5005    /**
5006     * Change whether this view is one of the set of scrollable containers in
5007     * its window.  This will be used to determine whether the window can
5008     * resize or must pan when a soft input area is open -- scrollable
5009     * containers allow the window to use resize mode since the container
5010     * will appropriately shrink.
5011     *
5012     * @attr ref android.R.styleable#View_isScrollContainer
5013     */
5014    public void setScrollContainer(boolean isScrollContainer) {
5015        if (isScrollContainer) {
5016            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5017                mAttachInfo.mScrollContainers.add(this);
5018                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5019            }
5020            mPrivateFlags |= SCROLL_CONTAINER;
5021        } else {
5022            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5023                mAttachInfo.mScrollContainers.remove(this);
5024            }
5025            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5026        }
5027    }
5028
5029    /**
5030     * Returns the quality of the drawing cache.
5031     *
5032     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5033     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5034     *
5035     * @see #setDrawingCacheQuality(int)
5036     * @see #setDrawingCacheEnabled(boolean)
5037     * @see #isDrawingCacheEnabled()
5038     *
5039     * @attr ref android.R.styleable#View_drawingCacheQuality
5040     */
5041    public int getDrawingCacheQuality() {
5042        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5043    }
5044
5045    /**
5046     * Set the drawing cache quality of this view. This value is used only when the
5047     * drawing cache is enabled
5048     *
5049     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5050     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5051     *
5052     * @see #getDrawingCacheQuality()
5053     * @see #setDrawingCacheEnabled(boolean)
5054     * @see #isDrawingCacheEnabled()
5055     *
5056     * @attr ref android.R.styleable#View_drawingCacheQuality
5057     */
5058    public void setDrawingCacheQuality(int quality) {
5059        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5060    }
5061
5062    /**
5063     * Returns whether the screen should remain on, corresponding to the current
5064     * value of {@link #KEEP_SCREEN_ON}.
5065     *
5066     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5067     *
5068     * @see #setKeepScreenOn(boolean)
5069     *
5070     * @attr ref android.R.styleable#View_keepScreenOn
5071     */
5072    public boolean getKeepScreenOn() {
5073        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5074    }
5075
5076    /**
5077     * Controls whether the screen should remain on, modifying the
5078     * value of {@link #KEEP_SCREEN_ON}.
5079     *
5080     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5081     *
5082     * @see #getKeepScreenOn()
5083     *
5084     * @attr ref android.R.styleable#View_keepScreenOn
5085     */
5086    public void setKeepScreenOn(boolean keepScreenOn) {
5087        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5088    }
5089
5090    /**
5091     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5092     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5093     *
5094     * @attr ref android.R.styleable#View_nextFocusLeft
5095     */
5096    public int getNextFocusLeftId() {
5097        return mNextFocusLeftId;
5098    }
5099
5100    /**
5101     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5102     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5103     * decide automatically.
5104     *
5105     * @attr ref android.R.styleable#View_nextFocusLeft
5106     */
5107    public void setNextFocusLeftId(int nextFocusLeftId) {
5108        mNextFocusLeftId = nextFocusLeftId;
5109    }
5110
5111    /**
5112     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5113     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5114     *
5115     * @attr ref android.R.styleable#View_nextFocusRight
5116     */
5117    public int getNextFocusRightId() {
5118        return mNextFocusRightId;
5119    }
5120
5121    /**
5122     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5123     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5124     * decide automatically.
5125     *
5126     * @attr ref android.R.styleable#View_nextFocusRight
5127     */
5128    public void setNextFocusRightId(int nextFocusRightId) {
5129        mNextFocusRightId = nextFocusRightId;
5130    }
5131
5132    /**
5133     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5134     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5135     *
5136     * @attr ref android.R.styleable#View_nextFocusUp
5137     */
5138    public int getNextFocusUpId() {
5139        return mNextFocusUpId;
5140    }
5141
5142    /**
5143     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5144     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5145     * decide automatically.
5146     *
5147     * @attr ref android.R.styleable#View_nextFocusUp
5148     */
5149    public void setNextFocusUpId(int nextFocusUpId) {
5150        mNextFocusUpId = nextFocusUpId;
5151    }
5152
5153    /**
5154     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5155     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5156     *
5157     * @attr ref android.R.styleable#View_nextFocusDown
5158     */
5159    public int getNextFocusDownId() {
5160        return mNextFocusDownId;
5161    }
5162
5163    /**
5164     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5165     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5166     * decide automatically.
5167     *
5168     * @attr ref android.R.styleable#View_nextFocusDown
5169     */
5170    public void setNextFocusDownId(int nextFocusDownId) {
5171        mNextFocusDownId = nextFocusDownId;
5172    }
5173
5174    /**
5175     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5176     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5177     *
5178     * @attr ref android.R.styleable#View_nextFocusForward
5179     */
5180    public int getNextFocusForwardId() {
5181        return mNextFocusForwardId;
5182    }
5183
5184    /**
5185     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5186     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5187     * decide automatically.
5188     *
5189     * @attr ref android.R.styleable#View_nextFocusForward
5190     */
5191    public void setNextFocusForwardId(int nextFocusForwardId) {
5192        mNextFocusForwardId = nextFocusForwardId;
5193    }
5194
5195    /**
5196     * Returns the visibility of this view and all of its ancestors
5197     *
5198     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5199     */
5200    public boolean isShown() {
5201        View current = this;
5202        //noinspection ConstantConditions
5203        do {
5204            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5205                return false;
5206            }
5207            ViewParent parent = current.mParent;
5208            if (parent == null) {
5209                return false; // We are not attached to the view root
5210            }
5211            if (!(parent instanceof View)) {
5212                return true;
5213            }
5214            current = (View) parent;
5215        } while (current != null);
5216
5217        return false;
5218    }
5219
5220    /**
5221     * Called by the view hierarchy when the content insets for a window have
5222     * changed, to allow it to adjust its content to fit within those windows.
5223     * The content insets tell you the space that the status bar, input method,
5224     * and other system windows infringe on the application's window.
5225     *
5226     * <p>You do not normally need to deal with this function, since the default
5227     * window decoration given to applications takes care of applying it to the
5228     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5229     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5230     * and your content can be placed under those system elements.  You can then
5231     * use this method within your view hierarchy if you have parts of your UI
5232     * which you would like to ensure are not being covered.
5233     *
5234     * <p>The default implementation of this method simply applies the content
5235     * inset's to the view's padding, consuming that content (modifying the
5236     * insets to be 0), and returning true.  This behavior is off by default, but can
5237     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5238     *
5239     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5240     * insets object is propagated down the hierarchy, so any changes made to it will
5241     * be seen by all following views (including potentially ones above in
5242     * the hierarchy since this is a depth-first traversal).  The first view
5243     * that returns true will abort the entire traversal.
5244     *
5245     * <p>The default implementation works well for a situation where it is
5246     * used with a container that covers the entire window, allowing it to
5247     * apply the appropriate insets to its content on all edges.  If you need
5248     * a more complicated layout (such as two different views fitting system
5249     * windows, one on the top of the window, and one on the bottom),
5250     * you can override the method and handle the insets however you would like.
5251     * Note that the insets provided by the framework are always relative to the
5252     * far edges of the window, not accounting for the location of the called view
5253     * within that window.  (In fact when this method is called you do not yet know
5254     * where the layout will place the view, as it is done before layout happens.)
5255     *
5256     * <p>Note: unlike many View methods, there is no dispatch phase to this
5257     * call.  If you are overriding it in a ViewGroup and want to allow the
5258     * call to continue to your children, you must be sure to call the super
5259     * implementation.
5260     *
5261     * <p>Here is a sample layout that makes use of fitting system windows
5262     * to have controls for a video view placed inside of the window decorations
5263     * that it hides and shows.  This can be used with code like the second
5264     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5265     *
5266     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5267     *
5268     * @param insets Current content insets of the window.  Prior to
5269     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5270     * the insets or else you and Android will be unhappy.
5271     *
5272     * @return Return true if this view applied the insets and it should not
5273     * continue propagating further down the hierarchy, false otherwise.
5274     * @see #getFitsSystemWindows()
5275     * @see #setFitsSystemWindows()
5276     * @see #setSystemUiVisibility(int)
5277     */
5278    protected boolean fitSystemWindows(Rect insets) {
5279        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5280            mUserPaddingStart = -1;
5281            mUserPaddingEnd = -1;
5282            mUserPaddingRelative = false;
5283            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5284                    || mAttachInfo == null
5285                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5286                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5287                return true;
5288            } else {
5289                internalSetPadding(0, 0, 0, 0);
5290                return false;
5291            }
5292        }
5293        return false;
5294    }
5295
5296    /**
5297     * Sets whether or not this view should account for system screen decorations
5298     * such as the status bar and inset its content; that is, controlling whether
5299     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5300     * executed.  See that method for more details.
5301     *
5302     * <p>Note that if you are providing your own implementation of
5303     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5304     * flag to true -- your implementation will be overriding the default
5305     * implementation that checks this flag.
5306     *
5307     * @param fitSystemWindows If true, then the default implementation of
5308     * {@link #fitSystemWindows(Rect)} will be executed.
5309     *
5310     * @attr ref android.R.styleable#View_fitsSystemWindows
5311     * @see #getFitsSystemWindows()
5312     * @see #fitSystemWindows(Rect)
5313     * @see #setSystemUiVisibility(int)
5314     */
5315    public void setFitsSystemWindows(boolean fitSystemWindows) {
5316        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5317    }
5318
5319    /**
5320     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5321     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5322     * will be executed.
5323     *
5324     * @return Returns true if the default implementation of
5325     * {@link #fitSystemWindows(Rect)} will be executed.
5326     *
5327     * @attr ref android.R.styleable#View_fitsSystemWindows
5328     * @see #setFitsSystemWindows()
5329     * @see #fitSystemWindows(Rect)
5330     * @see #setSystemUiVisibility(int)
5331     */
5332    public boolean getFitsSystemWindows() {
5333        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5334    }
5335
5336    /** @hide */
5337    public boolean fitsSystemWindows() {
5338        return getFitsSystemWindows();
5339    }
5340
5341    /**
5342     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5343     */
5344    public void requestFitSystemWindows() {
5345        if (mParent != null) {
5346            mParent.requestFitSystemWindows();
5347        }
5348    }
5349
5350    /**
5351     * For use by PhoneWindow to make its own system window fitting optional.
5352     * @hide
5353     */
5354    public void makeOptionalFitsSystemWindows() {
5355        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5356    }
5357
5358    /**
5359     * Returns the visibility status for this view.
5360     *
5361     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5362     * @attr ref android.R.styleable#View_visibility
5363     */
5364    @ViewDebug.ExportedProperty(mapping = {
5365        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5366        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5367        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5368    })
5369    public int getVisibility() {
5370        return mViewFlags & VISIBILITY_MASK;
5371    }
5372
5373    /**
5374     * Set the enabled state of this view.
5375     *
5376     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5377     * @attr ref android.R.styleable#View_visibility
5378     */
5379    @RemotableViewMethod
5380    public void setVisibility(int visibility) {
5381        setFlags(visibility, VISIBILITY_MASK);
5382        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5383    }
5384
5385    /**
5386     * Returns the enabled status for this view. The interpretation of the
5387     * enabled state varies by subclass.
5388     *
5389     * @return True if this view is enabled, false otherwise.
5390     */
5391    @ViewDebug.ExportedProperty
5392    public boolean isEnabled() {
5393        return (mViewFlags & ENABLED_MASK) == ENABLED;
5394    }
5395
5396    /**
5397     * Set the enabled state of this view. The interpretation of the enabled
5398     * state varies by subclass.
5399     *
5400     * @param enabled True if this view is enabled, false otherwise.
5401     */
5402    @RemotableViewMethod
5403    public void setEnabled(boolean enabled) {
5404        if (enabled == isEnabled()) return;
5405
5406        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5407
5408        /*
5409         * The View most likely has to change its appearance, so refresh
5410         * the drawable state.
5411         */
5412        refreshDrawableState();
5413
5414        // Invalidate too, since the default behavior for views is to be
5415        // be drawn at 50% alpha rather than to change the drawable.
5416        invalidate(true);
5417    }
5418
5419    /**
5420     * Set whether this view can receive the focus.
5421     *
5422     * Setting this to false will also ensure that this view is not focusable
5423     * in touch mode.
5424     *
5425     * @param focusable If true, this view can receive the focus.
5426     *
5427     * @see #setFocusableInTouchMode(boolean)
5428     * @attr ref android.R.styleable#View_focusable
5429     */
5430    public void setFocusable(boolean focusable) {
5431        if (!focusable) {
5432            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5433        }
5434        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5435    }
5436
5437    /**
5438     * Set whether this view can receive focus while in touch mode.
5439     *
5440     * Setting this to true will also ensure that this view is focusable.
5441     *
5442     * @param focusableInTouchMode If true, this view can receive the focus while
5443     *   in touch mode.
5444     *
5445     * @see #setFocusable(boolean)
5446     * @attr ref android.R.styleable#View_focusableInTouchMode
5447     */
5448    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5449        // Focusable in touch mode should always be set before the focusable flag
5450        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5451        // which, in touch mode, will not successfully request focus on this view
5452        // because the focusable in touch mode flag is not set
5453        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5454        if (focusableInTouchMode) {
5455            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5456        }
5457    }
5458
5459    /**
5460     * Set whether this view should have sound effects enabled for events such as
5461     * clicking and touching.
5462     *
5463     * <p>You may wish to disable sound effects for a view if you already play sounds,
5464     * for instance, a dial key that plays dtmf tones.
5465     *
5466     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5467     * @see #isSoundEffectsEnabled()
5468     * @see #playSoundEffect(int)
5469     * @attr ref android.R.styleable#View_soundEffectsEnabled
5470     */
5471    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5472        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5473    }
5474
5475    /**
5476     * @return whether this view should have sound effects enabled for events such as
5477     *     clicking and touching.
5478     *
5479     * @see #setSoundEffectsEnabled(boolean)
5480     * @see #playSoundEffect(int)
5481     * @attr ref android.R.styleable#View_soundEffectsEnabled
5482     */
5483    @ViewDebug.ExportedProperty
5484    public boolean isSoundEffectsEnabled() {
5485        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5486    }
5487
5488    /**
5489     * Set whether this view should have haptic feedback for events such as
5490     * long presses.
5491     *
5492     * <p>You may wish to disable haptic feedback if your view already controls
5493     * its own haptic feedback.
5494     *
5495     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5496     * @see #isHapticFeedbackEnabled()
5497     * @see #performHapticFeedback(int)
5498     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5499     */
5500    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5501        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5502    }
5503
5504    /**
5505     * @return whether this view should have haptic feedback enabled for events
5506     * long presses.
5507     *
5508     * @see #setHapticFeedbackEnabled(boolean)
5509     * @see #performHapticFeedback(int)
5510     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5511     */
5512    @ViewDebug.ExportedProperty
5513    public boolean isHapticFeedbackEnabled() {
5514        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5515    }
5516
5517    /**
5518     * Returns the layout direction for this view.
5519     *
5520     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5521     *   {@link #LAYOUT_DIRECTION_RTL},
5522     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5523     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5524     * @attr ref android.R.styleable#View_layoutDirection
5525     */
5526    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5527        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5528        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5529        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5530        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5531    })
5532    public int getLayoutDirection() {
5533        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5534    }
5535
5536    /**
5537     * Set the layout direction for this view. This will propagate a reset of layout direction
5538     * resolution to the view's children and resolve layout direction for this view.
5539     *
5540     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5541     *   {@link #LAYOUT_DIRECTION_RTL},
5542     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5543     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5544     *
5545     * @attr ref android.R.styleable#View_layoutDirection
5546     */
5547    @RemotableViewMethod
5548    public void setLayoutDirection(int layoutDirection) {
5549        if (getLayoutDirection() != layoutDirection) {
5550            // Reset the current layout direction and the resolved one
5551            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5552            resetResolvedLayoutDirection();
5553            // Set the new layout direction (filtered) and ask for a layout pass
5554            mPrivateFlags2 |=
5555                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5556            requestLayout();
5557        }
5558    }
5559
5560    /**
5561     * Returns the resolved layout direction for this view.
5562     *
5563     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5564     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5565     */
5566    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5567        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5568        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5569    })
5570    public int getResolvedLayoutDirection() {
5571        // The layout direction will be resolved only if needed
5572        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5573            resolveLayoutDirection();
5574        }
5575        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5576                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5577    }
5578
5579    /**
5580     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5581     * layout attribute and/or the inherited value from the parent
5582     *
5583     * @return true if the layout is right-to-left.
5584     */
5585    @ViewDebug.ExportedProperty(category = "layout")
5586    public boolean isLayoutRtl() {
5587        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5588    }
5589
5590    /**
5591     * Indicates whether the view is currently tracking transient state that the
5592     * app should not need to concern itself with saving and restoring, but that
5593     * the framework should take special note to preserve when possible.
5594     *
5595     * <p>A view with transient state cannot be trivially rebound from an external
5596     * data source, such as an adapter binding item views in a list. This may be
5597     * because the view is performing an animation, tracking user selection
5598     * of content, or similar.</p>
5599     *
5600     * @return true if the view has transient state
5601     */
5602    @ViewDebug.ExportedProperty(category = "layout")
5603    public boolean hasTransientState() {
5604        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5605    }
5606
5607    /**
5608     * Set whether this view is currently tracking transient state that the
5609     * framework should attempt to preserve when possible. This flag is reference counted,
5610     * so every call to setHasTransientState(true) should be paired with a later call
5611     * to setHasTransientState(false).
5612     *
5613     * <p>A view with transient state cannot be trivially rebound from an external
5614     * data source, such as an adapter binding item views in a list. This may be
5615     * because the view is performing an animation, tracking user selection
5616     * of content, or similar.</p>
5617     *
5618     * @param hasTransientState true if this view has transient state
5619     */
5620    public void setHasTransientState(boolean hasTransientState) {
5621        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5622                mTransientStateCount - 1;
5623        if (mTransientStateCount < 0) {
5624            mTransientStateCount = 0;
5625            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5626                    "unmatched pair of setHasTransientState calls");
5627        }
5628        if ((hasTransientState && mTransientStateCount == 1) ||
5629                (!hasTransientState && mTransientStateCount == 0)) {
5630            // update flag if we've just incremented up from 0 or decremented down to 0
5631            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5632                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5633            if (mParent != null) {
5634                try {
5635                    mParent.childHasTransientStateChanged(this, hasTransientState);
5636                } catch (AbstractMethodError e) {
5637                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5638                            " does not fully implement ViewParent", e);
5639                }
5640            }
5641        }
5642    }
5643
5644    /**
5645     * If this view doesn't do any drawing on its own, set this flag to
5646     * allow further optimizations. By default, this flag is not set on
5647     * View, but could be set on some View subclasses such as ViewGroup.
5648     *
5649     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5650     * you should clear this flag.
5651     *
5652     * @param willNotDraw whether or not this View draw on its own
5653     */
5654    public void setWillNotDraw(boolean willNotDraw) {
5655        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5656    }
5657
5658    /**
5659     * Returns whether or not this View draws on its own.
5660     *
5661     * @return true if this view has nothing to draw, false otherwise
5662     */
5663    @ViewDebug.ExportedProperty(category = "drawing")
5664    public boolean willNotDraw() {
5665        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5666    }
5667
5668    /**
5669     * When a View's drawing cache is enabled, drawing is redirected to an
5670     * offscreen bitmap. Some views, like an ImageView, must be able to
5671     * bypass this mechanism if they already draw a single bitmap, to avoid
5672     * unnecessary usage of the memory.
5673     *
5674     * @param willNotCacheDrawing true if this view does not cache its
5675     *        drawing, false otherwise
5676     */
5677    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5678        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5679    }
5680
5681    /**
5682     * Returns whether or not this View can cache its drawing or not.
5683     *
5684     * @return true if this view does not cache its drawing, false otherwise
5685     */
5686    @ViewDebug.ExportedProperty(category = "drawing")
5687    public boolean willNotCacheDrawing() {
5688        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5689    }
5690
5691    /**
5692     * Indicates whether this view reacts to click events or not.
5693     *
5694     * @return true if the view is clickable, false otherwise
5695     *
5696     * @see #setClickable(boolean)
5697     * @attr ref android.R.styleable#View_clickable
5698     */
5699    @ViewDebug.ExportedProperty
5700    public boolean isClickable() {
5701        return (mViewFlags & CLICKABLE) == CLICKABLE;
5702    }
5703
5704    /**
5705     * Enables or disables click events for this view. When a view
5706     * is clickable it will change its state to "pressed" on every click.
5707     * Subclasses should set the view clickable to visually react to
5708     * user's clicks.
5709     *
5710     * @param clickable true to make the view clickable, false otherwise
5711     *
5712     * @see #isClickable()
5713     * @attr ref android.R.styleable#View_clickable
5714     */
5715    public void setClickable(boolean clickable) {
5716        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5717    }
5718
5719    /**
5720     * Indicates whether this view reacts to long click events or not.
5721     *
5722     * @return true if the view is long clickable, false otherwise
5723     *
5724     * @see #setLongClickable(boolean)
5725     * @attr ref android.R.styleable#View_longClickable
5726     */
5727    public boolean isLongClickable() {
5728        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5729    }
5730
5731    /**
5732     * Enables or disables long click events for this view. When a view is long
5733     * clickable it reacts to the user holding down the button for a longer
5734     * duration than a tap. This event can either launch the listener or a
5735     * context menu.
5736     *
5737     * @param longClickable true to make the view long clickable, false otherwise
5738     * @see #isLongClickable()
5739     * @attr ref android.R.styleable#View_longClickable
5740     */
5741    public void setLongClickable(boolean longClickable) {
5742        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5743    }
5744
5745    /**
5746     * Sets the pressed state for this view.
5747     *
5748     * @see #isClickable()
5749     * @see #setClickable(boolean)
5750     *
5751     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5752     *        the View's internal state from a previously set "pressed" state.
5753     */
5754    public void setPressed(boolean pressed) {
5755        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5756
5757        if (pressed) {
5758            mPrivateFlags |= PRESSED;
5759        } else {
5760            mPrivateFlags &= ~PRESSED;
5761        }
5762
5763        if (needsRefresh) {
5764            refreshDrawableState();
5765        }
5766        dispatchSetPressed(pressed);
5767    }
5768
5769    /**
5770     * Dispatch setPressed to all of this View's children.
5771     *
5772     * @see #setPressed(boolean)
5773     *
5774     * @param pressed The new pressed state
5775     */
5776    protected void dispatchSetPressed(boolean pressed) {
5777    }
5778
5779    /**
5780     * Indicates whether the view is currently in pressed state. Unless
5781     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5782     * the pressed state.
5783     *
5784     * @see #setPressed(boolean)
5785     * @see #isClickable()
5786     * @see #setClickable(boolean)
5787     *
5788     * @return true if the view is currently pressed, false otherwise
5789     */
5790    public boolean isPressed() {
5791        return (mPrivateFlags & PRESSED) == PRESSED;
5792    }
5793
5794    /**
5795     * Indicates whether this view will save its state (that is,
5796     * whether its {@link #onSaveInstanceState} method will be called).
5797     *
5798     * @return Returns true if the view state saving is enabled, else false.
5799     *
5800     * @see #setSaveEnabled(boolean)
5801     * @attr ref android.R.styleable#View_saveEnabled
5802     */
5803    public boolean isSaveEnabled() {
5804        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5805    }
5806
5807    /**
5808     * Controls whether the saving of this view's state is
5809     * enabled (that is, whether its {@link #onSaveInstanceState} method
5810     * will be called).  Note that even if freezing is enabled, the
5811     * view still must have an id assigned to it (via {@link #setId(int)})
5812     * for its state to be saved.  This flag can only disable the
5813     * saving of this view; any child views may still have their state saved.
5814     *
5815     * @param enabled Set to false to <em>disable</em> state saving, or true
5816     * (the default) to allow it.
5817     *
5818     * @see #isSaveEnabled()
5819     * @see #setId(int)
5820     * @see #onSaveInstanceState()
5821     * @attr ref android.R.styleable#View_saveEnabled
5822     */
5823    public void setSaveEnabled(boolean enabled) {
5824        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5825    }
5826
5827    /**
5828     * Gets whether the framework should discard touches when the view's
5829     * window is obscured by another visible window.
5830     * Refer to the {@link View} security documentation for more details.
5831     *
5832     * @return True if touch filtering is enabled.
5833     *
5834     * @see #setFilterTouchesWhenObscured(boolean)
5835     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5836     */
5837    @ViewDebug.ExportedProperty
5838    public boolean getFilterTouchesWhenObscured() {
5839        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5840    }
5841
5842    /**
5843     * Sets whether the framework should discard touches when the view's
5844     * window is obscured by another visible window.
5845     * Refer to the {@link View} security documentation for more details.
5846     *
5847     * @param enabled True if touch filtering should be enabled.
5848     *
5849     * @see #getFilterTouchesWhenObscured
5850     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5851     */
5852    public void setFilterTouchesWhenObscured(boolean enabled) {
5853        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5854                FILTER_TOUCHES_WHEN_OBSCURED);
5855    }
5856
5857    /**
5858     * Indicates whether the entire hierarchy under this view will save its
5859     * state when a state saving traversal occurs from its parent.  The default
5860     * is true; if false, these views will not be saved unless
5861     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5862     *
5863     * @return Returns true if the view state saving from parent is enabled, else false.
5864     *
5865     * @see #setSaveFromParentEnabled(boolean)
5866     */
5867    public boolean isSaveFromParentEnabled() {
5868        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5869    }
5870
5871    /**
5872     * Controls whether the entire hierarchy under this view will save its
5873     * state when a state saving traversal occurs from its parent.  The default
5874     * is true; if false, these views will not be saved unless
5875     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5876     *
5877     * @param enabled Set to false to <em>disable</em> state saving, or true
5878     * (the default) to allow it.
5879     *
5880     * @see #isSaveFromParentEnabled()
5881     * @see #setId(int)
5882     * @see #onSaveInstanceState()
5883     */
5884    public void setSaveFromParentEnabled(boolean enabled) {
5885        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5886    }
5887
5888
5889    /**
5890     * Returns whether this View is able to take focus.
5891     *
5892     * @return True if this view can take focus, or false otherwise.
5893     * @attr ref android.R.styleable#View_focusable
5894     */
5895    @ViewDebug.ExportedProperty(category = "focus")
5896    public final boolean isFocusable() {
5897        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5898    }
5899
5900    /**
5901     * When a view is focusable, it may not want to take focus when in touch mode.
5902     * For example, a button would like focus when the user is navigating via a D-pad
5903     * so that the user can click on it, but once the user starts touching the screen,
5904     * the button shouldn't take focus
5905     * @return Whether the view is focusable in touch mode.
5906     * @attr ref android.R.styleable#View_focusableInTouchMode
5907     */
5908    @ViewDebug.ExportedProperty
5909    public final boolean isFocusableInTouchMode() {
5910        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5911    }
5912
5913    /**
5914     * Find the nearest view in the specified direction that can take focus.
5915     * This does not actually give focus to that view.
5916     *
5917     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5918     *
5919     * @return The nearest focusable in the specified direction, or null if none
5920     *         can be found.
5921     */
5922    public View focusSearch(int direction) {
5923        if (mParent != null) {
5924            return mParent.focusSearch(this, direction);
5925        } else {
5926            return null;
5927        }
5928    }
5929
5930    /**
5931     * This method is the last chance for the focused view and its ancestors to
5932     * respond to an arrow key. This is called when the focused view did not
5933     * consume the key internally, nor could the view system find a new view in
5934     * the requested direction to give focus to.
5935     *
5936     * @param focused The currently focused view.
5937     * @param direction The direction focus wants to move. One of FOCUS_UP,
5938     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5939     * @return True if the this view consumed this unhandled move.
5940     */
5941    public boolean dispatchUnhandledMove(View focused, int direction) {
5942        return false;
5943    }
5944
5945    /**
5946     * If a user manually specified the next view id for a particular direction,
5947     * use the root to look up the view.
5948     * @param root The root view of the hierarchy containing this view.
5949     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5950     * or FOCUS_BACKWARD.
5951     * @return The user specified next view, or null if there is none.
5952     */
5953    View findUserSetNextFocus(View root, int direction) {
5954        switch (direction) {
5955            case FOCUS_LEFT:
5956                if (mNextFocusLeftId == View.NO_ID) return null;
5957                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5958            case FOCUS_RIGHT:
5959                if (mNextFocusRightId == View.NO_ID) return null;
5960                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5961            case FOCUS_UP:
5962                if (mNextFocusUpId == View.NO_ID) return null;
5963                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5964            case FOCUS_DOWN:
5965                if (mNextFocusDownId == View.NO_ID) return null;
5966                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5967            case FOCUS_FORWARD:
5968                if (mNextFocusForwardId == View.NO_ID) return null;
5969                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5970            case FOCUS_BACKWARD: {
5971                if (mID == View.NO_ID) return null;
5972                final int id = mID;
5973                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5974                    @Override
5975                    public boolean apply(View t) {
5976                        return t.mNextFocusForwardId == id;
5977                    }
5978                });
5979            }
5980        }
5981        return null;
5982    }
5983
5984    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5985        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5986            @Override
5987            public boolean apply(View t) {
5988                return t.mID == childViewId;
5989            }
5990        });
5991
5992        if (result == null) {
5993            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5994                    + "by user for id " + childViewId);
5995        }
5996        return result;
5997    }
5998
5999    /**
6000     * Find and return all focusable views that are descendants of this view,
6001     * possibly including this view if it is focusable itself.
6002     *
6003     * @param direction The direction of the focus
6004     * @return A list of focusable views
6005     */
6006    public ArrayList<View> getFocusables(int direction) {
6007        ArrayList<View> result = new ArrayList<View>(24);
6008        addFocusables(result, direction);
6009        return result;
6010    }
6011
6012    /**
6013     * Add any focusable views that are descendants of this view (possibly
6014     * including this view if it is focusable itself) to views.  If we are in touch mode,
6015     * only add views that are also focusable in touch mode.
6016     *
6017     * @param views Focusable views found so far
6018     * @param direction The direction of the focus
6019     */
6020    public void addFocusables(ArrayList<View> views, int direction) {
6021        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6022    }
6023
6024    /**
6025     * Adds any focusable views that are descendants of this view (possibly
6026     * including this view if it is focusable itself) to views. This method
6027     * adds all focusable views regardless if we are in touch mode or
6028     * only views focusable in touch mode if we are in touch mode or
6029     * only views that can take accessibility focus if accessibility is enabeld
6030     * depending on the focusable mode paramater.
6031     *
6032     * @param views Focusable views found so far or null if all we are interested is
6033     *        the number of focusables.
6034     * @param direction The direction of the focus.
6035     * @param focusableMode The type of focusables to be added.
6036     *
6037     * @see #FOCUSABLES_ALL
6038     * @see #FOCUSABLES_TOUCH_MODE
6039     */
6040    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6041        if (views == null) {
6042            return;
6043        }
6044        if (!isFocusable()) {
6045            return;
6046        }
6047        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6048                && isInTouchMode() && !isFocusableInTouchMode()) {
6049            return;
6050        }
6051        views.add(this);
6052    }
6053
6054    /**
6055     * Finds the Views that contain given text. The containment is case insensitive.
6056     * The search is performed by either the text that the View renders or the content
6057     * description that describes the view for accessibility purposes and the view does
6058     * not render or both. Clients can specify how the search is to be performed via
6059     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6060     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6061     *
6062     * @param outViews The output list of matching Views.
6063     * @param searched The text to match against.
6064     *
6065     * @see #FIND_VIEWS_WITH_TEXT
6066     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6067     * @see #setContentDescription(CharSequence)
6068     */
6069    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6070        if (getAccessibilityNodeProvider() != null) {
6071            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6072                outViews.add(this);
6073            }
6074        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6075                && (searched != null && searched.length() > 0)
6076                && (mContentDescription != null && mContentDescription.length() > 0)) {
6077            String searchedLowerCase = searched.toString().toLowerCase();
6078            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6079            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6080                outViews.add(this);
6081            }
6082        }
6083    }
6084
6085    /**
6086     * Find and return all touchable views that are descendants of this view,
6087     * possibly including this view if it is touchable itself.
6088     *
6089     * @return A list of touchable views
6090     */
6091    public ArrayList<View> getTouchables() {
6092        ArrayList<View> result = new ArrayList<View>();
6093        addTouchables(result);
6094        return result;
6095    }
6096
6097    /**
6098     * Add any touchable views that are descendants of this view (possibly
6099     * including this view if it is touchable itself) to views.
6100     *
6101     * @param views Touchable views found so far
6102     */
6103    public void addTouchables(ArrayList<View> views) {
6104        final int viewFlags = mViewFlags;
6105
6106        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6107                && (viewFlags & ENABLED_MASK) == ENABLED) {
6108            views.add(this);
6109        }
6110    }
6111
6112    /**
6113     * Returns whether this View is accessibility focused.
6114     *
6115     * @return True if this View is accessibility focused.
6116     */
6117    boolean isAccessibilityFocused() {
6118        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6119    }
6120
6121    /**
6122     * Call this to try to give accessibility focus to this view.
6123     *
6124     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6125     * returns false or the view is no visible or the view already has accessibility
6126     * focus.
6127     *
6128     * See also {@link #focusSearch(int)}, which is what you call to say that you
6129     * have focus, and you want your parent to look for the next one.
6130     *
6131     * @return Whether this view actually took accessibility focus.
6132     *
6133     * @hide
6134     */
6135    public boolean requestAccessibilityFocus() {
6136        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6137        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6138            return false;
6139        }
6140        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6141            return false;
6142        }
6143        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6144            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6145            ViewRootImpl viewRootImpl = getViewRootImpl();
6146            if (viewRootImpl != null) {
6147                viewRootImpl.setAccessibilityFocus(this, null);
6148            }
6149            invalidate();
6150            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6151            notifyAccessibilityStateChanged();
6152            return true;
6153        }
6154        return false;
6155    }
6156
6157    /**
6158     * Call this to try to clear accessibility focus of this view.
6159     *
6160     * See also {@link #focusSearch(int)}, which is what you call to say that you
6161     * have focus, and you want your parent to look for the next one.
6162     *
6163     * @hide
6164     */
6165    public void clearAccessibilityFocus() {
6166        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6167            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6168            invalidate();
6169            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6170            notifyAccessibilityStateChanged();
6171        }
6172        // Clear the global reference of accessibility focus if this
6173        // view or any of its descendants had accessibility focus.
6174        ViewRootImpl viewRootImpl = getViewRootImpl();
6175        if (viewRootImpl != null) {
6176            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6177            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6178                viewRootImpl.setAccessibilityFocus(null, null);
6179            }
6180        }
6181    }
6182
6183    private void sendAccessibilityHoverEvent(int eventType) {
6184        // Since we are not delivering to a client accessibility events from not
6185        // important views (unless the clinet request that) we need to fire the
6186        // event from the deepest view exposed to the client. As a consequence if
6187        // the user crosses a not exposed view the client will see enter and exit
6188        // of the exposed predecessor followed by and enter and exit of that same
6189        // predecessor when entering and exiting the not exposed descendant. This
6190        // is fine since the client has a clear idea which view is hovered at the
6191        // price of a couple more events being sent. This is a simple and
6192        // working solution.
6193        View source = this;
6194        while (true) {
6195            if (source.includeForAccessibility()) {
6196                source.sendAccessibilityEvent(eventType);
6197                return;
6198            }
6199            ViewParent parent = source.getParent();
6200            if (parent instanceof View) {
6201                source = (View) parent;
6202            } else {
6203                return;
6204            }
6205        }
6206    }
6207
6208    /**
6209     * Clears accessibility focus without calling any callback methods
6210     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6211     * is used for clearing accessibility focus when giving this focus to
6212     * another view.
6213     */
6214    void clearAccessibilityFocusNoCallbacks() {
6215        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6216            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6217            invalidate();
6218        }
6219    }
6220
6221    /**
6222     * Call this to try to give focus to a specific view or to one of its
6223     * descendants.
6224     *
6225     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6226     * false), or if it is focusable and it is not focusable in touch mode
6227     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6228     *
6229     * See also {@link #focusSearch(int)}, which is what you call to say that you
6230     * have focus, and you want your parent to look for the next one.
6231     *
6232     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6233     * {@link #FOCUS_DOWN} and <code>null</code>.
6234     *
6235     * @return Whether this view or one of its descendants actually took focus.
6236     */
6237    public final boolean requestFocus() {
6238        return requestFocus(View.FOCUS_DOWN);
6239    }
6240
6241    /**
6242     * Call this to try to give focus to a specific view or to one of its
6243     * descendants and give it a hint about what direction focus is heading.
6244     *
6245     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6246     * false), or if it is focusable and it is not focusable in touch mode
6247     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6248     *
6249     * See also {@link #focusSearch(int)}, which is what you call to say that you
6250     * have focus, and you want your parent to look for the next one.
6251     *
6252     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6253     * <code>null</code> set for the previously focused rectangle.
6254     *
6255     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6256     * @return Whether this view or one of its descendants actually took focus.
6257     */
6258    public final boolean requestFocus(int direction) {
6259        return requestFocus(direction, null);
6260    }
6261
6262    /**
6263     * Call this to try to give focus to a specific view or to one of its descendants
6264     * and give it hints about the direction and a specific rectangle that the focus
6265     * is coming from.  The rectangle can help give larger views a finer grained hint
6266     * about where focus is coming from, and therefore, where to show selection, or
6267     * forward focus change internally.
6268     *
6269     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6270     * false), or if it is focusable and it is not focusable in touch mode
6271     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6272     *
6273     * A View will not take focus if it is not visible.
6274     *
6275     * A View will not take focus if one of its parents has
6276     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6277     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6278     *
6279     * See also {@link #focusSearch(int)}, which is what you call to say that you
6280     * have focus, and you want your parent to look for the next one.
6281     *
6282     * You may wish to override this method if your custom {@link View} has an internal
6283     * {@link View} that it wishes to forward the request to.
6284     *
6285     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6286     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6287     *        to give a finer grained hint about where focus is coming from.  May be null
6288     *        if there is no hint.
6289     * @return Whether this view or one of its descendants actually took focus.
6290     */
6291    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6292        return requestFocusNoSearch(direction, previouslyFocusedRect);
6293    }
6294
6295    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6296        // need to be focusable
6297        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6298                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6299            return false;
6300        }
6301
6302        // need to be focusable in touch mode if in touch mode
6303        if (isInTouchMode() &&
6304            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6305               return false;
6306        }
6307
6308        // need to not have any parents blocking us
6309        if (hasAncestorThatBlocksDescendantFocus()) {
6310            return false;
6311        }
6312
6313        handleFocusGainInternal(direction, previouslyFocusedRect);
6314        return true;
6315    }
6316
6317    /**
6318     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6319     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6320     * touch mode to request focus when they are touched.
6321     *
6322     * @return Whether this view or one of its descendants actually took focus.
6323     *
6324     * @see #isInTouchMode()
6325     *
6326     */
6327    public final boolean requestFocusFromTouch() {
6328        // Leave touch mode if we need to
6329        if (isInTouchMode()) {
6330            ViewRootImpl viewRoot = getViewRootImpl();
6331            if (viewRoot != null) {
6332                viewRoot.ensureTouchMode(false);
6333            }
6334        }
6335        return requestFocus(View.FOCUS_DOWN);
6336    }
6337
6338    /**
6339     * @return Whether any ancestor of this view blocks descendant focus.
6340     */
6341    private boolean hasAncestorThatBlocksDescendantFocus() {
6342        ViewParent ancestor = mParent;
6343        while (ancestor instanceof ViewGroup) {
6344            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6345            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6346                return true;
6347            } else {
6348                ancestor = vgAncestor.getParent();
6349            }
6350        }
6351        return false;
6352    }
6353
6354    /**
6355     * Gets the mode for determining whether this View is important for accessibility
6356     * which is if it fires accessibility events and if it is reported to
6357     * accessibility services that query the screen.
6358     *
6359     * @return The mode for determining whether a View is important for accessibility.
6360     *
6361     * @attr ref android.R.styleable#View_importantForAccessibility
6362     *
6363     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6364     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6365     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6366     */
6367    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6368            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6369            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6370            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6371        })
6372    public int getImportantForAccessibility() {
6373        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6374                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6375    }
6376
6377    /**
6378     * Sets how to determine whether this view is important for accessibility
6379     * which is if it fires accessibility events and if it is reported to
6380     * accessibility services that query the screen.
6381     *
6382     * @param mode How to determine whether this view is important for accessibility.
6383     *
6384     * @attr ref android.R.styleable#View_importantForAccessibility
6385     *
6386     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6387     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6388     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6389     */
6390    public void setImportantForAccessibility(int mode) {
6391        if (mode != getImportantForAccessibility()) {
6392            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6393            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6394                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6395            notifyAccessibilityStateChanged();
6396        }
6397    }
6398
6399    /**
6400     * Gets whether this view should be exposed for accessibility.
6401     *
6402     * @return Whether the view is exposed for accessibility.
6403     *
6404     * @hide
6405     */
6406    public boolean isImportantForAccessibility() {
6407        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6408                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6409        switch (mode) {
6410            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6411                return true;
6412            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6413                return false;
6414            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6415                return isActionableForAccessibility() || hasListenersForAccessibility();
6416            default:
6417                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6418                        + mode);
6419        }
6420    }
6421
6422    /**
6423     * Gets the parent for accessibility purposes. Note that the parent for
6424     * accessibility is not necessary the immediate parent. It is the first
6425     * predecessor that is important for accessibility.
6426     *
6427     * @return The parent for accessibility purposes.
6428     */
6429    public ViewParent getParentForAccessibility() {
6430        if (mParent instanceof View) {
6431            View parentView = (View) mParent;
6432            if (parentView.includeForAccessibility()) {
6433                return mParent;
6434            } else {
6435                return mParent.getParentForAccessibility();
6436            }
6437        }
6438        return null;
6439    }
6440
6441    /**
6442     * Adds the children of a given View for accessibility. Since some Views are
6443     * not important for accessibility the children for accessibility are not
6444     * necessarily direct children of the riew, rather they are the first level of
6445     * descendants important for accessibility.
6446     *
6447     * @param children The list of children for accessibility.
6448     */
6449    public void addChildrenForAccessibility(ArrayList<View> children) {
6450        if (includeForAccessibility()) {
6451            children.add(this);
6452        }
6453    }
6454
6455    /**
6456     * Whether to regard this view for accessibility. A view is regarded for
6457     * accessibility if it is important for accessibility or the querying
6458     * accessibility service has explicitly requested that view not
6459     * important for accessibility are regarded.
6460     *
6461     * @return Whether to regard the view for accessibility.
6462     *
6463     * @hide
6464     */
6465    public boolean includeForAccessibility() {
6466        if (mAttachInfo != null) {
6467            if (!mAttachInfo.mIncludeNotImportantViews) {
6468                return isImportantForAccessibility();
6469            }
6470            return true;
6471        }
6472        return false;
6473    }
6474
6475    /**
6476     * Returns whether the View is considered actionable from
6477     * accessibility perspective. Such view are important for
6478     * accessiiblity.
6479     *
6480     * @return True if the view is actionable for accessibility.
6481     *
6482     * @hide
6483     */
6484    public boolean isActionableForAccessibility() {
6485        return (isClickable() || isLongClickable() || isFocusable());
6486    }
6487
6488    /**
6489     * Returns whether the View has registered callbacks wich makes it
6490     * important for accessiiblity.
6491     *
6492     * @return True if the view is actionable for accessibility.
6493     */
6494    private boolean hasListenersForAccessibility() {
6495        ListenerInfo info = getListenerInfo();
6496        return mTouchDelegate != null || info.mOnKeyListener != null
6497                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6498                || info.mOnHoverListener != null || info.mOnDragListener != null;
6499    }
6500
6501    /**
6502     * Notifies accessibility services that some view's important for
6503     * accessibility state has changed. Note that such notifications
6504     * are made at most once every
6505     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6506     * to avoid unnecessary load to the system. Also once a view has
6507     * made a notifucation this method is a NOP until the notification has
6508     * been sent to clients.
6509     *
6510     * @hide
6511     *
6512     * TODO: Makse sure this method is called for any view state change
6513     *       that is interesting for accessilility purposes.
6514     */
6515    public void notifyAccessibilityStateChanged() {
6516        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6517            return;
6518        }
6519        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6520            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6521            if (mParent != null) {
6522                mParent.childAccessibilityStateChanged(this);
6523            }
6524        }
6525    }
6526
6527    /**
6528     * Reset the state indicating the this view has requested clients
6529     * interested in its accessiblity state to be notified.
6530     *
6531     * @hide
6532     */
6533    public void resetAccessibilityStateChanged() {
6534        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6535    }
6536
6537    /**
6538     * Performs the specified accessibility action on the view. For
6539     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6540    * <p>
6541    * If an {@link AccessibilityDelegate} has been specified via calling
6542    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6543    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6544    * is responsible for handling this call.
6545    * </p>
6546     *
6547     * @param action The action to perform.
6548     * @param arguments Optional action arguments.
6549     * @return Whether the action was performed.
6550     */
6551    public boolean performAccessibilityAction(int action, Bundle arguments) {
6552      if (mAccessibilityDelegate != null) {
6553          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6554      } else {
6555          return performAccessibilityActionInternal(action, arguments);
6556      }
6557    }
6558
6559   /**
6560    * @see #performAccessibilityAction(int, Bundle)
6561    *
6562    * Note: Called from the default {@link AccessibilityDelegate}.
6563    */
6564    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6565        switch (action) {
6566            case AccessibilityNodeInfo.ACTION_CLICK: {
6567                if (isClickable()) {
6568                    return performClick();
6569                }
6570            } break;
6571            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6572                if (isLongClickable()) {
6573                    return performLongClick();
6574                }
6575            } break;
6576            case AccessibilityNodeInfo.ACTION_FOCUS: {
6577                if (!hasFocus()) {
6578                    // Get out of touch mode since accessibility
6579                    // wants to move focus around.
6580                    getViewRootImpl().ensureTouchMode(false);
6581                    return requestFocus();
6582                }
6583            } break;
6584            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6585                if (hasFocus()) {
6586                    clearFocus();
6587                    return !isFocused();
6588                }
6589            } break;
6590            case AccessibilityNodeInfo.ACTION_SELECT: {
6591                if (!isSelected()) {
6592                    setSelected(true);
6593                    return isSelected();
6594                }
6595            } break;
6596            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6597                if (isSelected()) {
6598                    setSelected(false);
6599                    return !isSelected();
6600                }
6601            } break;
6602            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6603                if (!isAccessibilityFocused()) {
6604                    return requestAccessibilityFocus();
6605                }
6606            } break;
6607            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6608                if (isAccessibilityFocused()) {
6609                    clearAccessibilityFocus();
6610                    return true;
6611                }
6612            } break;
6613            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6614                if (arguments != null) {
6615                    final int granularity = arguments.getInt(
6616                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6617                    return nextAtGranularity(granularity);
6618                }
6619            } break;
6620            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6621                if (arguments != null) {
6622                    final int granularity = arguments.getInt(
6623                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6624                    return previousAtGranularity(granularity);
6625                }
6626            } break;
6627        }
6628        return false;
6629    }
6630
6631    private boolean nextAtGranularity(int granularity) {
6632        CharSequence text = getIterableTextForAccessibility();
6633        if (text == null || text.length() == 0) {
6634            return false;
6635        }
6636        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6637        if (iterator == null) {
6638            return false;
6639        }
6640        final int current = getAccessibilityCursorPosition();
6641        final int[] range = iterator.following(current);
6642        if (range == null) {
6643            return false;
6644        }
6645        final int start = range[0];
6646        final int end = range[1];
6647        setAccessibilityCursorPosition(end);
6648        sendViewTextTraversedAtGranularityEvent(
6649                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6650                granularity, start, end);
6651        return true;
6652    }
6653
6654    private boolean previousAtGranularity(int granularity) {
6655        CharSequence text = getIterableTextForAccessibility();
6656        if (text == null || text.length() == 0) {
6657            return false;
6658        }
6659        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6660        if (iterator == null) {
6661            return false;
6662        }
6663        int current = getAccessibilityCursorPosition();
6664        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6665            current = text.length();
6666        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6667            // When traversing by character we always put the cursor after the character
6668            // to ease edit and have to compensate before asking the for previous segment.
6669            current--;
6670        }
6671        final int[] range = iterator.preceding(current);
6672        if (range == null) {
6673            return false;
6674        }
6675        final int start = range[0];
6676        final int end = range[1];
6677        // Always put the cursor after the character to ease edit.
6678        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6679            setAccessibilityCursorPosition(end);
6680        } else {
6681            setAccessibilityCursorPosition(start);
6682        }
6683        sendViewTextTraversedAtGranularityEvent(
6684                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6685                granularity, start, end);
6686        return true;
6687    }
6688
6689    /**
6690     * Gets the text reported for accessibility purposes.
6691     *
6692     * @return The accessibility text.
6693     *
6694     * @hide
6695     */
6696    public CharSequence getIterableTextForAccessibility() {
6697        return mContentDescription;
6698    }
6699
6700    /**
6701     * @hide
6702     */
6703    public int getAccessibilityCursorPosition() {
6704        return mAccessibilityCursorPosition;
6705    }
6706
6707    /**
6708     * @hide
6709     */
6710    public void setAccessibilityCursorPosition(int position) {
6711        mAccessibilityCursorPosition = position;
6712    }
6713
6714    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6715            int fromIndex, int toIndex) {
6716        if (mParent == null) {
6717            return;
6718        }
6719        AccessibilityEvent event = AccessibilityEvent.obtain(
6720                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6721        onInitializeAccessibilityEvent(event);
6722        onPopulateAccessibilityEvent(event);
6723        event.setFromIndex(fromIndex);
6724        event.setToIndex(toIndex);
6725        event.setAction(action);
6726        event.setMovementGranularity(granularity);
6727        mParent.requestSendAccessibilityEvent(this, event);
6728    }
6729
6730    /**
6731     * @hide
6732     */
6733    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6734        switch (granularity) {
6735            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6736                CharSequence text = getIterableTextForAccessibility();
6737                if (text != null && text.length() > 0) {
6738                    CharacterTextSegmentIterator iterator =
6739                        CharacterTextSegmentIterator.getInstance(
6740                                mContext.getResources().getConfiguration().locale);
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(
6750                                mContext.getResources().getConfiguration().locale);
6751                    iterator.initialize(text.toString());
6752                    return iterator;
6753                }
6754            } break;
6755            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6756                CharSequence text = getIterableTextForAccessibility();
6757                if (text != null && text.length() > 0) {
6758                    ParagraphTextSegmentIterator iterator =
6759                        ParagraphTextSegmentIterator.getInstance();
6760                    iterator.initialize(text.toString());
6761                    return iterator;
6762                }
6763            } break;
6764        }
6765        return null;
6766    }
6767
6768    /**
6769     * @hide
6770     */
6771    public void dispatchStartTemporaryDetach() {
6772        clearAccessibilityFocus();
6773        clearDisplayList();
6774
6775        onStartTemporaryDetach();
6776    }
6777
6778    /**
6779     * This is called when a container is going to temporarily detach a child, with
6780     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6781     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6782     * {@link #onDetachedFromWindow()} when the container is done.
6783     */
6784    public void onStartTemporaryDetach() {
6785        removeUnsetPressCallback();
6786        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6787    }
6788
6789    /**
6790     * @hide
6791     */
6792    public void dispatchFinishTemporaryDetach() {
6793        onFinishTemporaryDetach();
6794    }
6795
6796    /**
6797     * Called after {@link #onStartTemporaryDetach} when the container is done
6798     * changing the view.
6799     */
6800    public void onFinishTemporaryDetach() {
6801    }
6802
6803    /**
6804     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6805     * for this view's window.  Returns null if the view is not currently attached
6806     * to the window.  Normally you will not need to use this directly, but
6807     * just use the standard high-level event callbacks like
6808     * {@link #onKeyDown(int, KeyEvent)}.
6809     */
6810    public KeyEvent.DispatcherState getKeyDispatcherState() {
6811        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6812    }
6813
6814    /**
6815     * Dispatch a key event before it is processed by any input method
6816     * associated with the view hierarchy.  This can be used to intercept
6817     * key events in special situations before the IME consumes them; a
6818     * typical example would be handling the BACK key to update the application's
6819     * UI instead of allowing the IME to see it and close itself.
6820     *
6821     * @param event The key event to be dispatched.
6822     * @return True if the event was handled, false otherwise.
6823     */
6824    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6825        return onKeyPreIme(event.getKeyCode(), event);
6826    }
6827
6828    /**
6829     * Dispatch a key event to the next view on the focus path. This path runs
6830     * from the top of the view tree down to the currently focused view. If this
6831     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6832     * the next node down the focus path. This method also fires any key
6833     * listeners.
6834     *
6835     * @param event The key event to be dispatched.
6836     * @return True if the event was handled, false otherwise.
6837     */
6838    public boolean dispatchKeyEvent(KeyEvent event) {
6839        if (mInputEventConsistencyVerifier != null) {
6840            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6841        }
6842
6843        // Give any attached key listener a first crack at the event.
6844        //noinspection SimplifiableIfStatement
6845        ListenerInfo li = mListenerInfo;
6846        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6847                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6848            return true;
6849        }
6850
6851        if (event.dispatch(this, mAttachInfo != null
6852                ? mAttachInfo.mKeyDispatchState : null, this)) {
6853            return true;
6854        }
6855
6856        if (mInputEventConsistencyVerifier != null) {
6857            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6858        }
6859        return false;
6860    }
6861
6862    /**
6863     * Dispatches a key shortcut event.
6864     *
6865     * @param event The key event to be dispatched.
6866     * @return True if the event was handled by the view, false otherwise.
6867     */
6868    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6869        return onKeyShortcut(event.getKeyCode(), event);
6870    }
6871
6872    /**
6873     * Pass the touch screen motion event down to the target view, or this
6874     * view if it is the target.
6875     *
6876     * @param event The motion event to be dispatched.
6877     * @return True if the event was handled by the view, false otherwise.
6878     */
6879    public boolean dispatchTouchEvent(MotionEvent event) {
6880        if (mInputEventConsistencyVerifier != null) {
6881            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6882        }
6883
6884        if (onFilterTouchEventForSecurity(event)) {
6885            //noinspection SimplifiableIfStatement
6886            ListenerInfo li = mListenerInfo;
6887            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6888                    && li.mOnTouchListener.onTouch(this, event)) {
6889                return true;
6890            }
6891
6892            if (onTouchEvent(event)) {
6893                return true;
6894            }
6895        }
6896
6897        if (mInputEventConsistencyVerifier != null) {
6898            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6899        }
6900        return false;
6901    }
6902
6903    /**
6904     * Filter the touch event to apply security policies.
6905     *
6906     * @param event The motion event to be filtered.
6907     * @return True if the event should be dispatched, false if the event should be dropped.
6908     *
6909     * @see #getFilterTouchesWhenObscured
6910     */
6911    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6912        //noinspection RedundantIfStatement
6913        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6914                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6915            // Window is obscured, drop this touch.
6916            return false;
6917        }
6918        return true;
6919    }
6920
6921    /**
6922     * Pass a trackball motion event down to the focused view.
6923     *
6924     * @param event The motion event to be dispatched.
6925     * @return True if the event was handled by the view, false otherwise.
6926     */
6927    public boolean dispatchTrackballEvent(MotionEvent event) {
6928        if (mInputEventConsistencyVerifier != null) {
6929            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6930        }
6931
6932        return onTrackballEvent(event);
6933    }
6934
6935    /**
6936     * Dispatch a generic motion event.
6937     * <p>
6938     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6939     * are delivered to the view under the pointer.  All other generic motion events are
6940     * delivered to the focused view.  Hover events are handled specially and are delivered
6941     * to {@link #onHoverEvent(MotionEvent)}.
6942     * </p>
6943     *
6944     * @param event The motion event to be dispatched.
6945     * @return True if the event was handled by the view, false otherwise.
6946     */
6947    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6948        if (mInputEventConsistencyVerifier != null) {
6949            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6950        }
6951
6952        final int source = event.getSource();
6953        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6954            final int action = event.getAction();
6955            if (action == MotionEvent.ACTION_HOVER_ENTER
6956                    || action == MotionEvent.ACTION_HOVER_MOVE
6957                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6958                if (dispatchHoverEvent(event)) {
6959                    return true;
6960                }
6961            } else if (dispatchGenericPointerEvent(event)) {
6962                return true;
6963            }
6964        } else if (dispatchGenericFocusedEvent(event)) {
6965            return true;
6966        }
6967
6968        if (dispatchGenericMotionEventInternal(event)) {
6969            return true;
6970        }
6971
6972        if (mInputEventConsistencyVerifier != null) {
6973            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6974        }
6975        return false;
6976    }
6977
6978    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6979        //noinspection SimplifiableIfStatement
6980        ListenerInfo li = mListenerInfo;
6981        if (li != null && li.mOnGenericMotionListener != null
6982                && (mViewFlags & ENABLED_MASK) == ENABLED
6983                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6984            return true;
6985        }
6986
6987        if (onGenericMotionEvent(event)) {
6988            return true;
6989        }
6990
6991        if (mInputEventConsistencyVerifier != null) {
6992            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6993        }
6994        return false;
6995    }
6996
6997    /**
6998     * Dispatch a hover event.
6999     * <p>
7000     * Do not call this method directly.
7001     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7002     * </p>
7003     *
7004     * @param event The motion event to be dispatched.
7005     * @return True if the event was handled by the view, false otherwise.
7006     */
7007    protected boolean dispatchHoverEvent(MotionEvent event) {
7008        //noinspection SimplifiableIfStatement
7009        ListenerInfo li = mListenerInfo;
7010        if (li != null && li.mOnHoverListener != null
7011                && (mViewFlags & ENABLED_MASK) == ENABLED
7012                && li.mOnHoverListener.onHover(this, event)) {
7013            return true;
7014        }
7015
7016        return onHoverEvent(event);
7017    }
7018
7019    /**
7020     * Returns true if the view has a child to which it has recently sent
7021     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7022     * it does not have a hovered child, then it must be the innermost hovered view.
7023     * @hide
7024     */
7025    protected boolean hasHoveredChild() {
7026        return false;
7027    }
7028
7029    /**
7030     * Dispatch a generic motion event to the view under the first pointer.
7031     * <p>
7032     * Do not call this method directly.
7033     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7034     * </p>
7035     *
7036     * @param event The motion event to be dispatched.
7037     * @return True if the event was handled by the view, false otherwise.
7038     */
7039    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7040        return false;
7041    }
7042
7043    /**
7044     * Dispatch a generic motion event to the currently focused view.
7045     * <p>
7046     * Do not call this method directly.
7047     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7048     * </p>
7049     *
7050     * @param event The motion event to be dispatched.
7051     * @return True if the event was handled by the view, false otherwise.
7052     */
7053    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7054        return false;
7055    }
7056
7057    /**
7058     * Dispatch a pointer event.
7059     * <p>
7060     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7061     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7062     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7063     * and should not be expected to handle other pointing device features.
7064     * </p>
7065     *
7066     * @param event The motion event to be dispatched.
7067     * @return True if the event was handled by the view, false otherwise.
7068     * @hide
7069     */
7070    public final boolean dispatchPointerEvent(MotionEvent event) {
7071        if (event.isTouchEvent()) {
7072            return dispatchTouchEvent(event);
7073        } else {
7074            return dispatchGenericMotionEvent(event);
7075        }
7076    }
7077
7078    /**
7079     * Called when the window containing this view gains or loses window focus.
7080     * ViewGroups should override to route to their children.
7081     *
7082     * @param hasFocus True if the window containing this view now has focus,
7083     *        false otherwise.
7084     */
7085    public void dispatchWindowFocusChanged(boolean hasFocus) {
7086        onWindowFocusChanged(hasFocus);
7087    }
7088
7089    /**
7090     * Called when the window containing this view gains or loses focus.  Note
7091     * that this is separate from view focus: to receive key events, both
7092     * your view and its window must have focus.  If a window is displayed
7093     * on top of yours that takes input focus, then your own window will lose
7094     * focus but the view focus will remain unchanged.
7095     *
7096     * @param hasWindowFocus True if the window containing this view now has
7097     *        focus, false otherwise.
7098     */
7099    public void onWindowFocusChanged(boolean hasWindowFocus) {
7100        InputMethodManager imm = InputMethodManager.peekInstance();
7101        if (!hasWindowFocus) {
7102            if (isPressed()) {
7103                setPressed(false);
7104            }
7105            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7106                imm.focusOut(this);
7107            }
7108            removeLongPressCallback();
7109            removeTapCallback();
7110            onFocusLost();
7111        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7112            imm.focusIn(this);
7113        }
7114        refreshDrawableState();
7115    }
7116
7117    /**
7118     * Returns true if this view is in a window that currently has window focus.
7119     * Note that this is not the same as the view itself having focus.
7120     *
7121     * @return True if this view is in a window that currently has window focus.
7122     */
7123    public boolean hasWindowFocus() {
7124        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7125    }
7126
7127    /**
7128     * Dispatch a view visibility change down the view hierarchy.
7129     * ViewGroups should override to route to their children.
7130     * @param changedView The view whose visibility changed. Could be 'this' or
7131     * an ancestor view.
7132     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7133     * {@link #INVISIBLE} or {@link #GONE}.
7134     */
7135    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7136        onVisibilityChanged(changedView, visibility);
7137    }
7138
7139    /**
7140     * Called when the visibility of the view or an ancestor of the view is changed.
7141     * @param changedView The view whose visibility changed. Could be 'this' or
7142     * an ancestor view.
7143     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7144     * {@link #INVISIBLE} or {@link #GONE}.
7145     */
7146    protected void onVisibilityChanged(View changedView, int visibility) {
7147        if (visibility == VISIBLE) {
7148            if (mAttachInfo != null) {
7149                initialAwakenScrollBars();
7150            } else {
7151                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7152            }
7153        }
7154    }
7155
7156    /**
7157     * Dispatch a hint about whether this view is displayed. For instance, when
7158     * a View moves out of the screen, it might receives a display hint indicating
7159     * the view is not displayed. Applications should not <em>rely</em> on this hint
7160     * as there is no guarantee that they will receive one.
7161     *
7162     * @param hint A hint about whether or not this view is displayed:
7163     * {@link #VISIBLE} or {@link #INVISIBLE}.
7164     */
7165    public void dispatchDisplayHint(int hint) {
7166        onDisplayHint(hint);
7167    }
7168
7169    /**
7170     * Gives this view a hint about whether is displayed or not. For instance, when
7171     * a View moves out of the screen, it might receives a display hint indicating
7172     * the view is not displayed. Applications should not <em>rely</em> on this hint
7173     * as there is no guarantee that they will receive one.
7174     *
7175     * @param hint A hint about whether or not this view is displayed:
7176     * {@link #VISIBLE} or {@link #INVISIBLE}.
7177     */
7178    protected void onDisplayHint(int hint) {
7179    }
7180
7181    /**
7182     * Dispatch a window visibility change down the view hierarchy.
7183     * ViewGroups should override to route to their children.
7184     *
7185     * @param visibility The new visibility of the window.
7186     *
7187     * @see #onWindowVisibilityChanged(int)
7188     */
7189    public void dispatchWindowVisibilityChanged(int visibility) {
7190        onWindowVisibilityChanged(visibility);
7191    }
7192
7193    /**
7194     * Called when the window containing has change its visibility
7195     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7196     * that this tells you whether or not your window is being made visible
7197     * to the window manager; this does <em>not</em> tell you whether or not
7198     * your window is obscured by other windows on the screen, even if it
7199     * is itself visible.
7200     *
7201     * @param visibility The new visibility of the window.
7202     */
7203    protected void onWindowVisibilityChanged(int visibility) {
7204        if (visibility == VISIBLE) {
7205            initialAwakenScrollBars();
7206        }
7207    }
7208
7209    /**
7210     * Returns the current visibility of the window this view is attached to
7211     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7212     *
7213     * @return Returns the current visibility of the view's window.
7214     */
7215    public int getWindowVisibility() {
7216        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7217    }
7218
7219    /**
7220     * Retrieve the overall visible display size in which the window this view is
7221     * attached to has been positioned in.  This takes into account screen
7222     * decorations above the window, for both cases where the window itself
7223     * is being position inside of them or the window is being placed under
7224     * then and covered insets are used for the window to position its content
7225     * inside.  In effect, this tells you the available area where content can
7226     * be placed and remain visible to users.
7227     *
7228     * <p>This function requires an IPC back to the window manager to retrieve
7229     * the requested information, so should not be used in performance critical
7230     * code like drawing.
7231     *
7232     * @param outRect Filled in with the visible display frame.  If the view
7233     * is not attached to a window, this is simply the raw display size.
7234     */
7235    public void getWindowVisibleDisplayFrame(Rect outRect) {
7236        if (mAttachInfo != null) {
7237            try {
7238                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7239            } catch (RemoteException e) {
7240                return;
7241            }
7242            // XXX This is really broken, and probably all needs to be done
7243            // in the window manager, and we need to know more about whether
7244            // we want the area behind or in front of the IME.
7245            final Rect insets = mAttachInfo.mVisibleInsets;
7246            outRect.left += insets.left;
7247            outRect.top += insets.top;
7248            outRect.right -= insets.right;
7249            outRect.bottom -= insets.bottom;
7250            return;
7251        }
7252        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7253        d.getRectSize(outRect);
7254    }
7255
7256    /**
7257     * Dispatch a notification about a resource configuration change down
7258     * the view hierarchy.
7259     * ViewGroups should override to route to their children.
7260     *
7261     * @param newConfig The new resource configuration.
7262     *
7263     * @see #onConfigurationChanged(android.content.res.Configuration)
7264     */
7265    public void dispatchConfigurationChanged(Configuration newConfig) {
7266        onConfigurationChanged(newConfig);
7267    }
7268
7269    /**
7270     * Called when the current configuration of the resources being used
7271     * by the application have changed.  You can use this to decide when
7272     * to reload resources that can changed based on orientation and other
7273     * configuration characterstics.  You only need to use this if you are
7274     * not relying on the normal {@link android.app.Activity} mechanism of
7275     * recreating the activity instance upon a configuration change.
7276     *
7277     * @param newConfig The new resource configuration.
7278     */
7279    protected void onConfigurationChanged(Configuration newConfig) {
7280    }
7281
7282    /**
7283     * Private function to aggregate all per-view attributes in to the view
7284     * root.
7285     */
7286    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7287        performCollectViewAttributes(attachInfo, visibility);
7288    }
7289
7290    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7291        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7292            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7293                attachInfo.mKeepScreenOn = true;
7294            }
7295            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7296            ListenerInfo li = mListenerInfo;
7297            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7298                attachInfo.mHasSystemUiListeners = true;
7299            }
7300        }
7301    }
7302
7303    void needGlobalAttributesUpdate(boolean force) {
7304        final AttachInfo ai = mAttachInfo;
7305        if (ai != null) {
7306            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7307                    || ai.mHasSystemUiListeners) {
7308                ai.mRecomputeGlobalAttributes = true;
7309            }
7310        }
7311    }
7312
7313    /**
7314     * Returns whether the device is currently in touch mode.  Touch mode is entered
7315     * once the user begins interacting with the device by touch, and affects various
7316     * things like whether focus is always visible to the user.
7317     *
7318     * @return Whether the device is in touch mode.
7319     */
7320    @ViewDebug.ExportedProperty
7321    public boolean isInTouchMode() {
7322        if (mAttachInfo != null) {
7323            return mAttachInfo.mInTouchMode;
7324        } else {
7325            return ViewRootImpl.isInTouchMode();
7326        }
7327    }
7328
7329    /**
7330     * Returns the context the view is running in, through which it can
7331     * access the current theme, resources, etc.
7332     *
7333     * @return The view's Context.
7334     */
7335    @ViewDebug.CapturedViewProperty
7336    public final Context getContext() {
7337        return mContext;
7338    }
7339
7340    /**
7341     * Handle a key event before it is processed by any input method
7342     * associated with the view hierarchy.  This can be used to intercept
7343     * key events in special situations before the IME consumes them; a
7344     * typical example would be handling the BACK key to update the application's
7345     * UI instead of allowing the IME to see it and close itself.
7346     *
7347     * @param keyCode The value in event.getKeyCode().
7348     * @param event Description of the key event.
7349     * @return If you handled the event, return true. If you want to allow the
7350     *         event to be handled by the next receiver, return false.
7351     */
7352    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7353        return false;
7354    }
7355
7356    /**
7357     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7358     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7359     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7360     * is released, if the view is enabled and clickable.
7361     *
7362     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7363     * although some may elect to do so in some situations. Do not rely on this to
7364     * catch software key presses.
7365     *
7366     * @param keyCode A key code that represents the button pressed, from
7367     *                {@link android.view.KeyEvent}.
7368     * @param event   The KeyEvent object that defines the button action.
7369     */
7370    public boolean onKeyDown(int keyCode, KeyEvent event) {
7371        boolean result = false;
7372
7373        switch (keyCode) {
7374            case KeyEvent.KEYCODE_DPAD_CENTER:
7375            case KeyEvent.KEYCODE_ENTER: {
7376                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7377                    return true;
7378                }
7379                // Long clickable items don't necessarily have to be clickable
7380                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7381                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7382                        (event.getRepeatCount() == 0)) {
7383                    setPressed(true);
7384                    checkForLongClick(0);
7385                    return true;
7386                }
7387                break;
7388            }
7389        }
7390        return result;
7391    }
7392
7393    /**
7394     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7395     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7396     * the event).
7397     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7398     * although some may elect to do so in some situations. Do not rely on this to
7399     * catch software key presses.
7400     */
7401    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7402        return false;
7403    }
7404
7405    /**
7406     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7407     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7408     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7409     * {@link KeyEvent#KEYCODE_ENTER} is released.
7410     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7411     * although some may elect to do so in some situations. Do not rely on this to
7412     * catch software key presses.
7413     *
7414     * @param keyCode A key code that represents the button pressed, from
7415     *                {@link android.view.KeyEvent}.
7416     * @param event   The KeyEvent object that defines the button action.
7417     */
7418    public boolean onKeyUp(int keyCode, KeyEvent event) {
7419        boolean result = false;
7420
7421        switch (keyCode) {
7422            case KeyEvent.KEYCODE_DPAD_CENTER:
7423            case KeyEvent.KEYCODE_ENTER: {
7424                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7425                    return true;
7426                }
7427                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7428                    setPressed(false);
7429
7430                    if (!mHasPerformedLongPress) {
7431                        // This is a tap, so remove the longpress check
7432                        removeLongPressCallback();
7433
7434                        result = performClick();
7435                    }
7436                }
7437                break;
7438            }
7439        }
7440        return result;
7441    }
7442
7443    /**
7444     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7445     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7446     * the event).
7447     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7448     * although some may elect to do so in some situations. Do not rely on this to
7449     * catch software key presses.
7450     *
7451     * @param keyCode     A key code that represents the button pressed, from
7452     *                    {@link android.view.KeyEvent}.
7453     * @param repeatCount The number of times the action was made.
7454     * @param event       The KeyEvent object that defines the button action.
7455     */
7456    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7457        return false;
7458    }
7459
7460    /**
7461     * Called on the focused view when a key shortcut event is not handled.
7462     * Override this method to implement local key shortcuts for the View.
7463     * Key shortcuts can also be implemented by setting the
7464     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7465     *
7466     * @param keyCode The value in event.getKeyCode().
7467     * @param event Description of the key event.
7468     * @return If you handled the event, return true. If you want to allow the
7469     *         event to be handled by the next receiver, return false.
7470     */
7471    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7472        return false;
7473    }
7474
7475    /**
7476     * Check whether the called view is a text editor, in which case it
7477     * would make sense to automatically display a soft input window for
7478     * it.  Subclasses should override this if they implement
7479     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7480     * a call on that method would return a non-null InputConnection, and
7481     * they are really a first-class editor that the user would normally
7482     * start typing on when the go into a window containing your view.
7483     *
7484     * <p>The default implementation always returns false.  This does
7485     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7486     * will not be called or the user can not otherwise perform edits on your
7487     * view; it is just a hint to the system that this is not the primary
7488     * purpose of this view.
7489     *
7490     * @return Returns true if this view is a text editor, else false.
7491     */
7492    public boolean onCheckIsTextEditor() {
7493        return false;
7494    }
7495
7496    /**
7497     * Create a new InputConnection for an InputMethod to interact
7498     * with the view.  The default implementation returns null, since it doesn't
7499     * support input methods.  You can override this to implement such support.
7500     * This is only needed for views that take focus and text input.
7501     *
7502     * <p>When implementing this, you probably also want to implement
7503     * {@link #onCheckIsTextEditor()} to indicate you will return a
7504     * non-null InputConnection.
7505     *
7506     * @param outAttrs Fill in with attribute information about the connection.
7507     */
7508    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7509        return null;
7510    }
7511
7512    /**
7513     * Called by the {@link android.view.inputmethod.InputMethodManager}
7514     * when a view who is not the current
7515     * input connection target is trying to make a call on the manager.  The
7516     * default implementation returns false; you can override this to return
7517     * true for certain views if you are performing InputConnection proxying
7518     * to them.
7519     * @param view The View that is making the InputMethodManager call.
7520     * @return Return true to allow the call, false to reject.
7521     */
7522    public boolean checkInputConnectionProxy(View view) {
7523        return false;
7524    }
7525
7526    /**
7527     * Show the context menu for this view. It is not safe to hold on to the
7528     * menu after returning from this method.
7529     *
7530     * You should normally not overload this method. Overload
7531     * {@link #onCreateContextMenu(ContextMenu)} or define an
7532     * {@link OnCreateContextMenuListener} to add items to the context menu.
7533     *
7534     * @param menu The context menu to populate
7535     */
7536    public void createContextMenu(ContextMenu menu) {
7537        ContextMenuInfo menuInfo = getContextMenuInfo();
7538
7539        // Sets the current menu info so all items added to menu will have
7540        // my extra info set.
7541        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7542
7543        onCreateContextMenu(menu);
7544        ListenerInfo li = mListenerInfo;
7545        if (li != null && li.mOnCreateContextMenuListener != null) {
7546            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7547        }
7548
7549        // Clear the extra information so subsequent items that aren't mine don't
7550        // have my extra info.
7551        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7552
7553        if (mParent != null) {
7554            mParent.createContextMenu(menu);
7555        }
7556    }
7557
7558    /**
7559     * Views should implement this if they have extra information to associate
7560     * with the context menu. The return result is supplied as a parameter to
7561     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7562     * callback.
7563     *
7564     * @return Extra information about the item for which the context menu
7565     *         should be shown. This information will vary across different
7566     *         subclasses of View.
7567     */
7568    protected ContextMenuInfo getContextMenuInfo() {
7569        return null;
7570    }
7571
7572    /**
7573     * Views should implement this if the view itself is going to add items to
7574     * the context menu.
7575     *
7576     * @param menu the context menu to populate
7577     */
7578    protected void onCreateContextMenu(ContextMenu menu) {
7579    }
7580
7581    /**
7582     * Implement this method to handle trackball motion events.  The
7583     * <em>relative</em> movement of the trackball since the last event
7584     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7585     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7586     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7587     * they will often be fractional values, representing the more fine-grained
7588     * movement information available from a trackball).
7589     *
7590     * @param event The motion event.
7591     * @return True if the event was handled, false otherwise.
7592     */
7593    public boolean onTrackballEvent(MotionEvent event) {
7594        return false;
7595    }
7596
7597    /**
7598     * Implement this method to handle generic motion events.
7599     * <p>
7600     * Generic motion events describe joystick movements, mouse hovers, track pad
7601     * touches, scroll wheel movements and other input events.  The
7602     * {@link MotionEvent#getSource() source} of the motion event specifies
7603     * the class of input that was received.  Implementations of this method
7604     * must examine the bits in the source before processing the event.
7605     * The following code example shows how this is done.
7606     * </p><p>
7607     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7608     * are delivered to the view under the pointer.  All other generic motion events are
7609     * delivered to the focused view.
7610     * </p>
7611     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7612     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7613     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7614     *             // process the joystick movement...
7615     *             return true;
7616     *         }
7617     *     }
7618     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7619     *         switch (event.getAction()) {
7620     *             case MotionEvent.ACTION_HOVER_MOVE:
7621     *                 // process the mouse hover movement...
7622     *                 return true;
7623     *             case MotionEvent.ACTION_SCROLL:
7624     *                 // process the scroll wheel movement...
7625     *                 return true;
7626     *         }
7627     *     }
7628     *     return super.onGenericMotionEvent(event);
7629     * }</pre>
7630     *
7631     * @param event The generic motion event being processed.
7632     * @return True if the event was handled, false otherwise.
7633     */
7634    public boolean onGenericMotionEvent(MotionEvent event) {
7635        return false;
7636    }
7637
7638    /**
7639     * Implement this method to handle hover events.
7640     * <p>
7641     * This method is called whenever a pointer is hovering into, over, or out of the
7642     * bounds of a view and the view is not currently being touched.
7643     * Hover events are represented as pointer events with action
7644     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7645     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7646     * </p>
7647     * <ul>
7648     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7649     * when the pointer enters the bounds of the view.</li>
7650     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7651     * when the pointer has already entered the bounds of the view and has moved.</li>
7652     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7653     * when the pointer has exited the bounds of the view or when the pointer is
7654     * about to go down due to a button click, tap, or similar user action that
7655     * causes the view to be touched.</li>
7656     * </ul>
7657     * <p>
7658     * The view should implement this method to return true to indicate that it is
7659     * handling the hover event, such as by changing its drawable state.
7660     * </p><p>
7661     * The default implementation calls {@link #setHovered} to update the hovered state
7662     * of the view when a hover enter or hover exit event is received, if the view
7663     * is enabled and is clickable.  The default implementation also sends hover
7664     * accessibility events.
7665     * </p>
7666     *
7667     * @param event The motion event that describes the hover.
7668     * @return True if the view handled the hover event.
7669     *
7670     * @see #isHovered
7671     * @see #setHovered
7672     * @see #onHoverChanged
7673     */
7674    public boolean onHoverEvent(MotionEvent event) {
7675        // The root view may receive hover (or touch) events that are outside the bounds of
7676        // the window.  This code ensures that we only send accessibility events for
7677        // hovers that are actually within the bounds of the root view.
7678        final int action = event.getActionMasked();
7679        if (!mSendingHoverAccessibilityEvents) {
7680            if ((action == MotionEvent.ACTION_HOVER_ENTER
7681                    || action == MotionEvent.ACTION_HOVER_MOVE)
7682                    && !hasHoveredChild()
7683                    && pointInView(event.getX(), event.getY())) {
7684                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7685                mSendingHoverAccessibilityEvents = true;
7686            }
7687        } else {
7688            if (action == MotionEvent.ACTION_HOVER_EXIT
7689                    || (action == MotionEvent.ACTION_MOVE
7690                            && !pointInView(event.getX(), event.getY()))) {
7691                mSendingHoverAccessibilityEvents = false;
7692                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7693                // If the window does not have input focus we take away accessibility
7694                // focus as soon as the user stop hovering over the view.
7695                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7696                    getViewRootImpl().setAccessibilityFocus(null, null);
7697                }
7698            }
7699        }
7700
7701        if (isHoverable()) {
7702            switch (action) {
7703                case MotionEvent.ACTION_HOVER_ENTER:
7704                    setHovered(true);
7705                    break;
7706                case MotionEvent.ACTION_HOVER_EXIT:
7707                    setHovered(false);
7708                    break;
7709            }
7710
7711            // Dispatch the event to onGenericMotionEvent before returning true.
7712            // This is to provide compatibility with existing applications that
7713            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7714            // break because of the new default handling for hoverable views
7715            // in onHoverEvent.
7716            // Note that onGenericMotionEvent will be called by default when
7717            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7718            dispatchGenericMotionEventInternal(event);
7719            return true;
7720        }
7721
7722        return false;
7723    }
7724
7725    /**
7726     * Returns true if the view should handle {@link #onHoverEvent}
7727     * by calling {@link #setHovered} to change its hovered state.
7728     *
7729     * @return True if the view is hoverable.
7730     */
7731    private boolean isHoverable() {
7732        final int viewFlags = mViewFlags;
7733        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7734            return false;
7735        }
7736
7737        return (viewFlags & CLICKABLE) == CLICKABLE
7738                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7739    }
7740
7741    /**
7742     * Returns true if the view is currently hovered.
7743     *
7744     * @return True if the view is currently hovered.
7745     *
7746     * @see #setHovered
7747     * @see #onHoverChanged
7748     */
7749    @ViewDebug.ExportedProperty
7750    public boolean isHovered() {
7751        return (mPrivateFlags & HOVERED) != 0;
7752    }
7753
7754    /**
7755     * Sets whether the view is currently hovered.
7756     * <p>
7757     * Calling this method also changes the drawable state of the view.  This
7758     * enables the view to react to hover by using different drawable resources
7759     * to change its appearance.
7760     * </p><p>
7761     * The {@link #onHoverChanged} method is called when the hovered state changes.
7762     * </p>
7763     *
7764     * @param hovered True if the view is hovered.
7765     *
7766     * @see #isHovered
7767     * @see #onHoverChanged
7768     */
7769    public void setHovered(boolean hovered) {
7770        if (hovered) {
7771            if ((mPrivateFlags & HOVERED) == 0) {
7772                mPrivateFlags |= HOVERED;
7773                refreshDrawableState();
7774                onHoverChanged(true);
7775            }
7776        } else {
7777            if ((mPrivateFlags & HOVERED) != 0) {
7778                mPrivateFlags &= ~HOVERED;
7779                refreshDrawableState();
7780                onHoverChanged(false);
7781            }
7782        }
7783    }
7784
7785    /**
7786     * Implement this method to handle hover state changes.
7787     * <p>
7788     * This method is called whenever the hover state changes as a result of a
7789     * call to {@link #setHovered}.
7790     * </p>
7791     *
7792     * @param hovered The current hover state, as returned by {@link #isHovered}.
7793     *
7794     * @see #isHovered
7795     * @see #setHovered
7796     */
7797    public void onHoverChanged(boolean hovered) {
7798    }
7799
7800    /**
7801     * Implement this method to handle touch screen motion events.
7802     *
7803     * @param event The motion event.
7804     * @return True if the event was handled, false otherwise.
7805     */
7806    public boolean onTouchEvent(MotionEvent event) {
7807        final int viewFlags = mViewFlags;
7808
7809        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7810            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7811                setPressed(false);
7812            }
7813            // A disabled view that is clickable still consumes the touch
7814            // events, it just doesn't respond to them.
7815            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7816                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7817        }
7818
7819        if (mTouchDelegate != null) {
7820            if (mTouchDelegate.onTouchEvent(event)) {
7821                return true;
7822            }
7823        }
7824
7825        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7826                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7827            switch (event.getAction()) {
7828                case MotionEvent.ACTION_UP:
7829                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7830                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7831                        // take focus if we don't have it already and we should in
7832                        // touch mode.
7833                        boolean focusTaken = false;
7834                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7835                            focusTaken = requestFocus();
7836                        }
7837
7838                        if (prepressed) {
7839                            // The button is being released before we actually
7840                            // showed it as pressed.  Make it show the pressed
7841                            // state now (before scheduling the click) to ensure
7842                            // the user sees it.
7843                            setPressed(true);
7844                       }
7845
7846                        if (!mHasPerformedLongPress) {
7847                            // This is a tap, so remove the longpress check
7848                            removeLongPressCallback();
7849
7850                            // Only perform take click actions if we were in the pressed state
7851                            if (!focusTaken) {
7852                                // Use a Runnable and post this rather than calling
7853                                // performClick directly. This lets other visual state
7854                                // of the view update before click actions start.
7855                                if (mPerformClick == null) {
7856                                    mPerformClick = new PerformClick();
7857                                }
7858                                if (!post(mPerformClick)) {
7859                                    performClick();
7860                                }
7861                            }
7862                        }
7863
7864                        if (mUnsetPressedState == null) {
7865                            mUnsetPressedState = new UnsetPressedState();
7866                        }
7867
7868                        if (prepressed) {
7869                            postDelayed(mUnsetPressedState,
7870                                    ViewConfiguration.getPressedStateDuration());
7871                        } else if (!post(mUnsetPressedState)) {
7872                            // If the post failed, unpress right now
7873                            mUnsetPressedState.run();
7874                        }
7875                        removeTapCallback();
7876                    }
7877                    break;
7878
7879                case MotionEvent.ACTION_DOWN:
7880                    mHasPerformedLongPress = false;
7881
7882                    if (performButtonActionOnTouchDown(event)) {
7883                        break;
7884                    }
7885
7886                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7887                    boolean isInScrollingContainer = isInScrollingContainer();
7888
7889                    // For views inside a scrolling container, delay the pressed feedback for
7890                    // a short period in case this is a scroll.
7891                    if (isInScrollingContainer) {
7892                        mPrivateFlags |= PREPRESSED;
7893                        if (mPendingCheckForTap == null) {
7894                            mPendingCheckForTap = new CheckForTap();
7895                        }
7896                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7897                    } else {
7898                        // Not inside a scrolling container, so show the feedback right away
7899                        setPressed(true);
7900                        checkForLongClick(0);
7901                    }
7902                    break;
7903
7904                case MotionEvent.ACTION_CANCEL:
7905                    setPressed(false);
7906                    removeTapCallback();
7907                    break;
7908
7909                case MotionEvent.ACTION_MOVE:
7910                    final int x = (int) event.getX();
7911                    final int y = (int) event.getY();
7912
7913                    // Be lenient about moving outside of buttons
7914                    if (!pointInView(x, y, mTouchSlop)) {
7915                        // Outside button
7916                        removeTapCallback();
7917                        if ((mPrivateFlags & PRESSED) != 0) {
7918                            // Remove any future long press/tap checks
7919                            removeLongPressCallback();
7920
7921                            setPressed(false);
7922                        }
7923                    }
7924                    break;
7925            }
7926            return true;
7927        }
7928
7929        return false;
7930    }
7931
7932    /**
7933     * @hide
7934     */
7935    public boolean isInScrollingContainer() {
7936        ViewParent p = getParent();
7937        while (p != null && p instanceof ViewGroup) {
7938            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7939                return true;
7940            }
7941            p = p.getParent();
7942        }
7943        return false;
7944    }
7945
7946    /**
7947     * Remove the longpress detection timer.
7948     */
7949    private void removeLongPressCallback() {
7950        if (mPendingCheckForLongPress != null) {
7951          removeCallbacks(mPendingCheckForLongPress);
7952        }
7953    }
7954
7955    /**
7956     * Remove the pending click action
7957     */
7958    private void removePerformClickCallback() {
7959        if (mPerformClick != null) {
7960            removeCallbacks(mPerformClick);
7961        }
7962    }
7963
7964    /**
7965     * Remove the prepress detection timer.
7966     */
7967    private void removeUnsetPressCallback() {
7968        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7969            setPressed(false);
7970            removeCallbacks(mUnsetPressedState);
7971        }
7972    }
7973
7974    /**
7975     * Remove the tap detection timer.
7976     */
7977    private void removeTapCallback() {
7978        if (mPendingCheckForTap != null) {
7979            mPrivateFlags &= ~PREPRESSED;
7980            removeCallbacks(mPendingCheckForTap);
7981        }
7982    }
7983
7984    /**
7985     * Cancels a pending long press.  Your subclass can use this if you
7986     * want the context menu to come up if the user presses and holds
7987     * at the same place, but you don't want it to come up if they press
7988     * and then move around enough to cause scrolling.
7989     */
7990    public void cancelLongPress() {
7991        removeLongPressCallback();
7992
7993        /*
7994         * The prepressed state handled by the tap callback is a display
7995         * construct, but the tap callback will post a long press callback
7996         * less its own timeout. Remove it here.
7997         */
7998        removeTapCallback();
7999    }
8000
8001    /**
8002     * Remove the pending callback for sending a
8003     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8004     */
8005    private void removeSendViewScrolledAccessibilityEventCallback() {
8006        if (mSendViewScrolledAccessibilityEvent != null) {
8007            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8008            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8009        }
8010    }
8011
8012    /**
8013     * Sets the TouchDelegate for this View.
8014     */
8015    public void setTouchDelegate(TouchDelegate delegate) {
8016        mTouchDelegate = delegate;
8017    }
8018
8019    /**
8020     * Gets the TouchDelegate for this View.
8021     */
8022    public TouchDelegate getTouchDelegate() {
8023        return mTouchDelegate;
8024    }
8025
8026    /**
8027     * Set flags controlling behavior of this view.
8028     *
8029     * @param flags Constant indicating the value which should be set
8030     * @param mask Constant indicating the bit range that should be changed
8031     */
8032    void setFlags(int flags, int mask) {
8033        int old = mViewFlags;
8034        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8035
8036        int changed = mViewFlags ^ old;
8037        if (changed == 0) {
8038            return;
8039        }
8040        int privateFlags = mPrivateFlags;
8041
8042        /* Check if the FOCUSABLE bit has changed */
8043        if (((changed & FOCUSABLE_MASK) != 0) &&
8044                ((privateFlags & HAS_BOUNDS) !=0)) {
8045            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8046                    && ((privateFlags & FOCUSED) != 0)) {
8047                /* Give up focus if we are no longer focusable */
8048                clearFocus();
8049            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8050                    && ((privateFlags & FOCUSED) == 0)) {
8051                /*
8052                 * Tell the view system that we are now available to take focus
8053                 * if no one else already has it.
8054                 */
8055                if (mParent != null) mParent.focusableViewAvailable(this);
8056            }
8057            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8058                notifyAccessibilityStateChanged();
8059            }
8060        }
8061
8062        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8063            if ((changed & VISIBILITY_MASK) != 0) {
8064                /*
8065                 * If this view is becoming visible, invalidate it in case it changed while
8066                 * it was not visible. Marking it drawn ensures that the invalidation will
8067                 * go through.
8068                 */
8069                mPrivateFlags |= DRAWN;
8070                invalidate(true);
8071
8072                needGlobalAttributesUpdate(true);
8073
8074                // a view becoming visible is worth notifying the parent
8075                // about in case nothing has focus.  even if this specific view
8076                // isn't focusable, it may contain something that is, so let
8077                // the root view try to give this focus if nothing else does.
8078                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8079                    mParent.focusableViewAvailable(this);
8080                }
8081            }
8082        }
8083
8084        /* Check if the GONE bit has changed */
8085        if ((changed & GONE) != 0) {
8086            needGlobalAttributesUpdate(false);
8087            requestLayout();
8088
8089            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8090                if (hasFocus()) clearFocus();
8091                clearAccessibilityFocus();
8092                destroyDrawingCache();
8093                if (mParent instanceof View) {
8094                    // GONE views noop invalidation, so invalidate the parent
8095                    ((View) mParent).invalidate(true);
8096                }
8097                // Mark the view drawn to ensure that it gets invalidated properly the next
8098                // time it is visible and gets invalidated
8099                mPrivateFlags |= DRAWN;
8100            }
8101            if (mAttachInfo != null) {
8102                mAttachInfo.mViewVisibilityChanged = true;
8103            }
8104        }
8105
8106        /* Check if the VISIBLE bit has changed */
8107        if ((changed & INVISIBLE) != 0) {
8108            needGlobalAttributesUpdate(false);
8109            /*
8110             * If this view is becoming invisible, set the DRAWN flag so that
8111             * the next invalidate() will not be skipped.
8112             */
8113            mPrivateFlags |= DRAWN;
8114
8115            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8116                // root view becoming invisible shouldn't clear focus and accessibility focus
8117                if (getRootView() != this) {
8118                    clearFocus();
8119                    clearAccessibilityFocus();
8120                }
8121            }
8122            if (mAttachInfo != null) {
8123                mAttachInfo.mViewVisibilityChanged = true;
8124            }
8125        }
8126
8127        if ((changed & VISIBILITY_MASK) != 0) {
8128            if (mParent instanceof ViewGroup) {
8129                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8130                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8131                ((View) mParent).invalidate(true);
8132            } else if (mParent != null) {
8133                mParent.invalidateChild(this, null);
8134            }
8135            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8136        }
8137
8138        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8139            destroyDrawingCache();
8140        }
8141
8142        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8143            destroyDrawingCache();
8144            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8145            invalidateParentCaches();
8146        }
8147
8148        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8149            destroyDrawingCache();
8150            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8151        }
8152
8153        if ((changed & DRAW_MASK) != 0) {
8154            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8155                if (mBackground != null) {
8156                    mPrivateFlags &= ~SKIP_DRAW;
8157                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8158                } else {
8159                    mPrivateFlags |= SKIP_DRAW;
8160                }
8161            } else {
8162                mPrivateFlags &= ~SKIP_DRAW;
8163            }
8164            requestLayout();
8165            invalidate(true);
8166        }
8167
8168        if ((changed & KEEP_SCREEN_ON) != 0) {
8169            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8170                mParent.recomputeViewAttributes(this);
8171            }
8172        }
8173
8174        if (AccessibilityManager.getInstance(mContext).isEnabled()
8175                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8176                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8177            notifyAccessibilityStateChanged();
8178        }
8179    }
8180
8181    /**
8182     * Change the view's z order in the tree, so it's on top of other sibling
8183     * views
8184     */
8185    public void bringToFront() {
8186        if (mParent != null) {
8187            mParent.bringChildToFront(this);
8188        }
8189    }
8190
8191    /**
8192     * This is called in response to an internal scroll in this view (i.e., the
8193     * view scrolled its own contents). This is typically as a result of
8194     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8195     * called.
8196     *
8197     * @param l Current horizontal scroll origin.
8198     * @param t Current vertical scroll origin.
8199     * @param oldl Previous horizontal scroll origin.
8200     * @param oldt Previous vertical scroll origin.
8201     */
8202    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8203        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8204            postSendViewScrolledAccessibilityEventCallback();
8205        }
8206
8207        mBackgroundSizeChanged = true;
8208
8209        final AttachInfo ai = mAttachInfo;
8210        if (ai != null) {
8211            ai.mViewScrollChanged = true;
8212        }
8213    }
8214
8215    /**
8216     * Interface definition for a callback to be invoked when the layout bounds of a view
8217     * changes due to layout processing.
8218     */
8219    public interface OnLayoutChangeListener {
8220        /**
8221         * Called when the focus state of a view has changed.
8222         *
8223         * @param v The view whose state has changed.
8224         * @param left The new value of the view's left property.
8225         * @param top The new value of the view's top property.
8226         * @param right The new value of the view's right property.
8227         * @param bottom The new value of the view's bottom property.
8228         * @param oldLeft The previous value of the view's left property.
8229         * @param oldTop The previous value of the view's top property.
8230         * @param oldRight The previous value of the view's right property.
8231         * @param oldBottom The previous value of the view's bottom property.
8232         */
8233        void onLayoutChange(View v, int left, int top, int right, int bottom,
8234            int oldLeft, int oldTop, int oldRight, int oldBottom);
8235    }
8236
8237    /**
8238     * This is called during layout when the size of this view has changed. If
8239     * you were just added to the view hierarchy, you're called with the old
8240     * values of 0.
8241     *
8242     * @param w Current width of this view.
8243     * @param h Current height of this view.
8244     * @param oldw Old width of this view.
8245     * @param oldh Old height of this view.
8246     */
8247    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8248    }
8249
8250    /**
8251     * Called by draw to draw the child views. This may be overridden
8252     * by derived classes to gain control just before its children are drawn
8253     * (but after its own view has been drawn).
8254     * @param canvas the canvas on which to draw the view
8255     */
8256    protected void dispatchDraw(Canvas canvas) {
8257
8258    }
8259
8260    /**
8261     * Gets the parent of this view. Note that the parent is a
8262     * ViewParent and not necessarily a View.
8263     *
8264     * @return Parent of this view.
8265     */
8266    public final ViewParent getParent() {
8267        return mParent;
8268    }
8269
8270    /**
8271     * Set the horizontal scrolled position of your view. This will cause a call to
8272     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8273     * invalidated.
8274     * @param value the x position to scroll to
8275     */
8276    public void setScrollX(int value) {
8277        scrollTo(value, mScrollY);
8278    }
8279
8280    /**
8281     * Set the vertical scrolled position of your view. This will cause a call to
8282     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8283     * invalidated.
8284     * @param value the y position to scroll to
8285     */
8286    public void setScrollY(int value) {
8287        scrollTo(mScrollX, value);
8288    }
8289
8290    /**
8291     * Return the scrolled left position of this view. This is the left edge of
8292     * the displayed part of your view. You do not need to draw any pixels
8293     * farther left, since those are outside of the frame of your view on
8294     * screen.
8295     *
8296     * @return The left edge of the displayed part of your view, in pixels.
8297     */
8298    public final int getScrollX() {
8299        return mScrollX;
8300    }
8301
8302    /**
8303     * Return the scrolled top position of this view. This is the top edge of
8304     * the displayed part of your view. You do not need to draw any pixels above
8305     * it, since those are outside of the frame of your view on screen.
8306     *
8307     * @return The top edge of the displayed part of your view, in pixels.
8308     */
8309    public final int getScrollY() {
8310        return mScrollY;
8311    }
8312
8313    /**
8314     * Return the width of the your view.
8315     *
8316     * @return The width of your view, in pixels.
8317     */
8318    @ViewDebug.ExportedProperty(category = "layout")
8319    public final int getWidth() {
8320        return mRight - mLeft;
8321    }
8322
8323    /**
8324     * Return the height of your view.
8325     *
8326     * @return The height of your view, in pixels.
8327     */
8328    @ViewDebug.ExportedProperty(category = "layout")
8329    public final int getHeight() {
8330        return mBottom - mTop;
8331    }
8332
8333    /**
8334     * Return the visible drawing bounds of your view. Fills in the output
8335     * rectangle with the values from getScrollX(), getScrollY(),
8336     * getWidth(), and getHeight().
8337     *
8338     * @param outRect The (scrolled) drawing bounds of the view.
8339     */
8340    public void getDrawingRect(Rect outRect) {
8341        outRect.left = mScrollX;
8342        outRect.top = mScrollY;
8343        outRect.right = mScrollX + (mRight - mLeft);
8344        outRect.bottom = mScrollY + (mBottom - mTop);
8345    }
8346
8347    /**
8348     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8349     * raw width component (that is the result is masked by
8350     * {@link #MEASURED_SIZE_MASK}).
8351     *
8352     * @return The raw measured width of this view.
8353     */
8354    public final int getMeasuredWidth() {
8355        return mMeasuredWidth & MEASURED_SIZE_MASK;
8356    }
8357
8358    /**
8359     * Return the full width measurement information for this view as computed
8360     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8361     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8362     * This should be used during measurement and layout calculations only. Use
8363     * {@link #getWidth()} to see how wide a view is after layout.
8364     *
8365     * @return The measured width of this view as a bit mask.
8366     */
8367    public final int getMeasuredWidthAndState() {
8368        return mMeasuredWidth;
8369    }
8370
8371    /**
8372     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8373     * raw width component (that is the result is masked by
8374     * {@link #MEASURED_SIZE_MASK}).
8375     *
8376     * @return The raw measured height of this view.
8377     */
8378    public final int getMeasuredHeight() {
8379        return mMeasuredHeight & MEASURED_SIZE_MASK;
8380    }
8381
8382    /**
8383     * Return the full height measurement information for this view as computed
8384     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8385     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8386     * This should be used during measurement and layout calculations only. Use
8387     * {@link #getHeight()} to see how wide a view is after layout.
8388     *
8389     * @return The measured width of this view as a bit mask.
8390     */
8391    public final int getMeasuredHeightAndState() {
8392        return mMeasuredHeight;
8393    }
8394
8395    /**
8396     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8397     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8398     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8399     * and the height component is at the shifted bits
8400     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8401     */
8402    public final int getMeasuredState() {
8403        return (mMeasuredWidth&MEASURED_STATE_MASK)
8404                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8405                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8406    }
8407
8408    /**
8409     * The transform matrix of this view, which is calculated based on the current
8410     * roation, scale, and pivot properties.
8411     *
8412     * @see #getRotation()
8413     * @see #getScaleX()
8414     * @see #getScaleY()
8415     * @see #getPivotX()
8416     * @see #getPivotY()
8417     * @return The current transform matrix for the view
8418     */
8419    public Matrix getMatrix() {
8420        if (mTransformationInfo != null) {
8421            updateMatrix();
8422            return mTransformationInfo.mMatrix;
8423        }
8424        return Matrix.IDENTITY_MATRIX;
8425    }
8426
8427    /**
8428     * Utility function to determine if the value is far enough away from zero to be
8429     * considered non-zero.
8430     * @param value A floating point value to check for zero-ness
8431     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8432     */
8433    private static boolean nonzero(float value) {
8434        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8435    }
8436
8437    /**
8438     * Returns true if the transform matrix is the identity matrix.
8439     * Recomputes the matrix if necessary.
8440     *
8441     * @return True if the transform matrix is the identity matrix, false otherwise.
8442     */
8443    final boolean hasIdentityMatrix() {
8444        if (mTransformationInfo != null) {
8445            updateMatrix();
8446            return mTransformationInfo.mMatrixIsIdentity;
8447        }
8448        return true;
8449    }
8450
8451    void ensureTransformationInfo() {
8452        if (mTransformationInfo == null) {
8453            mTransformationInfo = new TransformationInfo();
8454        }
8455    }
8456
8457    /**
8458     * Recomputes the transform matrix if necessary.
8459     */
8460    private void updateMatrix() {
8461        final TransformationInfo info = mTransformationInfo;
8462        if (info == null) {
8463            return;
8464        }
8465        if (info.mMatrixDirty) {
8466            // transform-related properties have changed since the last time someone
8467            // asked for the matrix; recalculate it with the current values
8468
8469            // Figure out if we need to update the pivot point
8470            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8471                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8472                    info.mPrevWidth = mRight - mLeft;
8473                    info.mPrevHeight = mBottom - mTop;
8474                    info.mPivotX = info.mPrevWidth / 2f;
8475                    info.mPivotY = info.mPrevHeight / 2f;
8476                }
8477            }
8478            info.mMatrix.reset();
8479            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8480                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8481                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8482                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8483            } else {
8484                if (info.mCamera == null) {
8485                    info.mCamera = new Camera();
8486                    info.matrix3D = new Matrix();
8487                }
8488                info.mCamera.save();
8489                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8490                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8491                info.mCamera.getMatrix(info.matrix3D);
8492                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8493                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8494                        info.mPivotY + info.mTranslationY);
8495                info.mMatrix.postConcat(info.matrix3D);
8496                info.mCamera.restore();
8497            }
8498            info.mMatrixDirty = false;
8499            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8500            info.mInverseMatrixDirty = true;
8501        }
8502    }
8503
8504    /**
8505     * When searching for a view to focus this rectangle is used when considering if this view is
8506     * a good candidate for receiving focus.
8507     *
8508     * By default, the rectangle is the {@link #getDrawingRect}) of the view.
8509     *
8510     * @param r The rectangle to fill in, in this view's coordinates.
8511     */
8512    public void getFocusRect(Rect r) {
8513        getDrawingRect(r);
8514    }
8515
8516   /**
8517     * Utility method to retrieve the inverse of the current mMatrix property.
8518     * We cache the matrix to avoid recalculating it when transform properties
8519     * have not changed.
8520     *
8521     * @return The inverse of the current matrix of this view.
8522     */
8523    final Matrix getInverseMatrix() {
8524        final TransformationInfo info = mTransformationInfo;
8525        if (info != null) {
8526            updateMatrix();
8527            if (info.mInverseMatrixDirty) {
8528                if (info.mInverseMatrix == null) {
8529                    info.mInverseMatrix = new Matrix();
8530                }
8531                info.mMatrix.invert(info.mInverseMatrix);
8532                info.mInverseMatrixDirty = false;
8533            }
8534            return info.mInverseMatrix;
8535        }
8536        return Matrix.IDENTITY_MATRIX;
8537    }
8538
8539    /**
8540     * Gets the distance along the Z axis from the camera to this view.
8541     *
8542     * @see #setCameraDistance(float)
8543     *
8544     * @return The distance along the Z axis.
8545     */
8546    public float getCameraDistance() {
8547        ensureTransformationInfo();
8548        final float dpi = mResources.getDisplayMetrics().densityDpi;
8549        final TransformationInfo info = mTransformationInfo;
8550        if (info.mCamera == null) {
8551            info.mCamera = new Camera();
8552            info.matrix3D = new Matrix();
8553        }
8554        return -(info.mCamera.getLocationZ() * dpi);
8555    }
8556
8557    /**
8558     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8559     * views are drawn) from the camera to this view. The camera's distance
8560     * affects 3D transformations, for instance rotations around the X and Y
8561     * axis. If the rotationX or rotationY properties are changed and this view is
8562     * large (more than half the size of the screen), it is recommended to always
8563     * use a camera distance that's greater than the height (X axis rotation) or
8564     * the width (Y axis rotation) of this view.</p>
8565     *
8566     * <p>The distance of the camera from the view plane can have an affect on the
8567     * perspective distortion of the view when it is rotated around the x or y axis.
8568     * For example, a large distance will result in a large viewing angle, and there
8569     * will not be much perspective distortion of the view as it rotates. A short
8570     * distance may cause much more perspective distortion upon rotation, and can
8571     * also result in some drawing artifacts if the rotated view ends up partially
8572     * behind the camera (which is why the recommendation is to use a distance at
8573     * least as far as the size of the view, if the view is to be rotated.)</p>
8574     *
8575     * <p>The distance is expressed in "depth pixels." The default distance depends
8576     * on the screen density. For instance, on a medium density display, the
8577     * default distance is 1280. On a high density display, the default distance
8578     * is 1920.</p>
8579     *
8580     * <p>If you want to specify a distance that leads to visually consistent
8581     * results across various densities, use the following formula:</p>
8582     * <pre>
8583     * float scale = context.getResources().getDisplayMetrics().density;
8584     * view.setCameraDistance(distance * scale);
8585     * </pre>
8586     *
8587     * <p>The density scale factor of a high density display is 1.5,
8588     * and 1920 = 1280 * 1.5.</p>
8589     *
8590     * @param distance The distance in "depth pixels", if negative the opposite
8591     *        value is used
8592     *
8593     * @see #setRotationX(float)
8594     * @see #setRotationY(float)
8595     */
8596    public void setCameraDistance(float distance) {
8597        invalidateViewProperty(true, false);
8598
8599        ensureTransformationInfo();
8600        final float dpi = mResources.getDisplayMetrics().densityDpi;
8601        final TransformationInfo info = mTransformationInfo;
8602        if (info.mCamera == null) {
8603            info.mCamera = new Camera();
8604            info.matrix3D = new Matrix();
8605        }
8606
8607        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8608        info.mMatrixDirty = true;
8609
8610        invalidateViewProperty(false, false);
8611        if (mDisplayList != null) {
8612            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8613        }
8614        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8615            // View was rejected last time it was drawn by its parent; this may have changed
8616            invalidateParentIfNeeded();
8617        }
8618    }
8619
8620    /**
8621     * The degrees that the view is rotated around the pivot point.
8622     *
8623     * @see #setRotation(float)
8624     * @see #getPivotX()
8625     * @see #getPivotY()
8626     *
8627     * @return The degrees of rotation.
8628     */
8629    @ViewDebug.ExportedProperty(category = "drawing")
8630    public float getRotation() {
8631        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8632    }
8633
8634    /**
8635     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8636     * result in clockwise rotation.
8637     *
8638     * @param rotation The degrees of rotation.
8639     *
8640     * @see #getRotation()
8641     * @see #getPivotX()
8642     * @see #getPivotY()
8643     * @see #setRotationX(float)
8644     * @see #setRotationY(float)
8645     *
8646     * @attr ref android.R.styleable#View_rotation
8647     */
8648    public void setRotation(float rotation) {
8649        ensureTransformationInfo();
8650        final TransformationInfo info = mTransformationInfo;
8651        if (info.mRotation != rotation) {
8652            // Double-invalidation is necessary to capture view's old and new areas
8653            invalidateViewProperty(true, false);
8654            info.mRotation = rotation;
8655            info.mMatrixDirty = true;
8656            invalidateViewProperty(false, true);
8657            if (mDisplayList != null) {
8658                mDisplayList.setRotation(rotation);
8659            }
8660            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8661                // View was rejected last time it was drawn by its parent; this may have changed
8662                invalidateParentIfNeeded();
8663            }
8664        }
8665    }
8666
8667    /**
8668     * The degrees that the view is rotated around the vertical axis through the pivot point.
8669     *
8670     * @see #getPivotX()
8671     * @see #getPivotY()
8672     * @see #setRotationY(float)
8673     *
8674     * @return The degrees of Y rotation.
8675     */
8676    @ViewDebug.ExportedProperty(category = "drawing")
8677    public float getRotationY() {
8678        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8679    }
8680
8681    /**
8682     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8683     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8684     * down the y axis.
8685     *
8686     * When rotating large views, it is recommended to adjust the camera distance
8687     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8688     *
8689     * @param rotationY The degrees of Y rotation.
8690     *
8691     * @see #getRotationY()
8692     * @see #getPivotX()
8693     * @see #getPivotY()
8694     * @see #setRotation(float)
8695     * @see #setRotationX(float)
8696     * @see #setCameraDistance(float)
8697     *
8698     * @attr ref android.R.styleable#View_rotationY
8699     */
8700    public void setRotationY(float rotationY) {
8701        ensureTransformationInfo();
8702        final TransformationInfo info = mTransformationInfo;
8703        if (info.mRotationY != rotationY) {
8704            invalidateViewProperty(true, false);
8705            info.mRotationY = rotationY;
8706            info.mMatrixDirty = true;
8707            invalidateViewProperty(false, true);
8708            if (mDisplayList != null) {
8709                mDisplayList.setRotationY(rotationY);
8710            }
8711            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8712                // View was rejected last time it was drawn by its parent; this may have changed
8713                invalidateParentIfNeeded();
8714            }
8715        }
8716    }
8717
8718    /**
8719     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8720     *
8721     * @see #getPivotX()
8722     * @see #getPivotY()
8723     * @see #setRotationX(float)
8724     *
8725     * @return The degrees of X rotation.
8726     */
8727    @ViewDebug.ExportedProperty(category = "drawing")
8728    public float getRotationX() {
8729        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8730    }
8731
8732    /**
8733     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8734     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8735     * x axis.
8736     *
8737     * When rotating large views, it is recommended to adjust the camera distance
8738     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8739     *
8740     * @param rotationX The degrees of X rotation.
8741     *
8742     * @see #getRotationX()
8743     * @see #getPivotX()
8744     * @see #getPivotY()
8745     * @see #setRotation(float)
8746     * @see #setRotationY(float)
8747     * @see #setCameraDistance(float)
8748     *
8749     * @attr ref android.R.styleable#View_rotationX
8750     */
8751    public void setRotationX(float rotationX) {
8752        ensureTransformationInfo();
8753        final TransformationInfo info = mTransformationInfo;
8754        if (info.mRotationX != rotationX) {
8755            invalidateViewProperty(true, false);
8756            info.mRotationX = rotationX;
8757            info.mMatrixDirty = true;
8758            invalidateViewProperty(false, true);
8759            if (mDisplayList != null) {
8760                mDisplayList.setRotationX(rotationX);
8761            }
8762            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8763                // View was rejected last time it was drawn by its parent; this may have changed
8764                invalidateParentIfNeeded();
8765            }
8766        }
8767    }
8768
8769    /**
8770     * The amount that the view is scaled in x around the pivot point, as a proportion of
8771     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8772     *
8773     * <p>By default, this is 1.0f.
8774     *
8775     * @see #getPivotX()
8776     * @see #getPivotY()
8777     * @return The scaling factor.
8778     */
8779    @ViewDebug.ExportedProperty(category = "drawing")
8780    public float getScaleX() {
8781        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8782    }
8783
8784    /**
8785     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8786     * the view's unscaled width. A value of 1 means that no scaling is applied.
8787     *
8788     * @param scaleX The scaling factor.
8789     * @see #getPivotX()
8790     * @see #getPivotY()
8791     *
8792     * @attr ref android.R.styleable#View_scaleX
8793     */
8794    public void setScaleX(float scaleX) {
8795        ensureTransformationInfo();
8796        final TransformationInfo info = mTransformationInfo;
8797        if (info.mScaleX != scaleX) {
8798            invalidateViewProperty(true, false);
8799            info.mScaleX = scaleX;
8800            info.mMatrixDirty = true;
8801            invalidateViewProperty(false, true);
8802            if (mDisplayList != null) {
8803                mDisplayList.setScaleX(scaleX);
8804            }
8805            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8806                // View was rejected last time it was drawn by its parent; this may have changed
8807                invalidateParentIfNeeded();
8808            }
8809        }
8810    }
8811
8812    /**
8813     * The amount that the view is scaled in y around the pivot point, as a proportion of
8814     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8815     *
8816     * <p>By default, this is 1.0f.
8817     *
8818     * @see #getPivotX()
8819     * @see #getPivotY()
8820     * @return The scaling factor.
8821     */
8822    @ViewDebug.ExportedProperty(category = "drawing")
8823    public float getScaleY() {
8824        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8825    }
8826
8827    /**
8828     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8829     * the view's unscaled width. A value of 1 means that no scaling is applied.
8830     *
8831     * @param scaleY The scaling factor.
8832     * @see #getPivotX()
8833     * @see #getPivotY()
8834     *
8835     * @attr ref android.R.styleable#View_scaleY
8836     */
8837    public void setScaleY(float scaleY) {
8838        ensureTransformationInfo();
8839        final TransformationInfo info = mTransformationInfo;
8840        if (info.mScaleY != scaleY) {
8841            invalidateViewProperty(true, false);
8842            info.mScaleY = scaleY;
8843            info.mMatrixDirty = true;
8844            invalidateViewProperty(false, true);
8845            if (mDisplayList != null) {
8846                mDisplayList.setScaleY(scaleY);
8847            }
8848            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8849                // View was rejected last time it was drawn by its parent; this may have changed
8850                invalidateParentIfNeeded();
8851            }
8852        }
8853    }
8854
8855    /**
8856     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8857     * and {@link #setScaleX(float) scaled}.
8858     *
8859     * @see #getRotation()
8860     * @see #getScaleX()
8861     * @see #getScaleY()
8862     * @see #getPivotY()
8863     * @return The x location of the pivot point.
8864     *
8865     * @attr ref android.R.styleable#View_transformPivotX
8866     */
8867    @ViewDebug.ExportedProperty(category = "drawing")
8868    public float getPivotX() {
8869        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8870    }
8871
8872    /**
8873     * Sets the x location of the point around which the view is
8874     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8875     * By default, the pivot point is centered on the object.
8876     * Setting this property disables this behavior and causes the view to use only the
8877     * explicitly set pivotX and pivotY values.
8878     *
8879     * @param pivotX The x location of the pivot point.
8880     * @see #getRotation()
8881     * @see #getScaleX()
8882     * @see #getScaleY()
8883     * @see #getPivotY()
8884     *
8885     * @attr ref android.R.styleable#View_transformPivotX
8886     */
8887    public void setPivotX(float pivotX) {
8888        ensureTransformationInfo();
8889        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8890        final TransformationInfo info = mTransformationInfo;
8891        if (info.mPivotX != pivotX) {
8892            invalidateViewProperty(true, false);
8893            info.mPivotX = pivotX;
8894            info.mMatrixDirty = true;
8895            invalidateViewProperty(false, true);
8896            if (mDisplayList != null) {
8897                mDisplayList.setPivotX(pivotX);
8898            }
8899            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8900                // View was rejected last time it was drawn by its parent; this may have changed
8901                invalidateParentIfNeeded();
8902            }
8903        }
8904    }
8905
8906    /**
8907     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8908     * and {@link #setScaleY(float) scaled}.
8909     *
8910     * @see #getRotation()
8911     * @see #getScaleX()
8912     * @see #getScaleY()
8913     * @see #getPivotY()
8914     * @return The y location of the pivot point.
8915     *
8916     * @attr ref android.R.styleable#View_transformPivotY
8917     */
8918    @ViewDebug.ExportedProperty(category = "drawing")
8919    public float getPivotY() {
8920        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8921    }
8922
8923    /**
8924     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8925     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8926     * Setting this property disables this behavior and causes the view to use only the
8927     * explicitly set pivotX and pivotY values.
8928     *
8929     * @param pivotY The y location of the pivot point.
8930     * @see #getRotation()
8931     * @see #getScaleX()
8932     * @see #getScaleY()
8933     * @see #getPivotY()
8934     *
8935     * @attr ref android.R.styleable#View_transformPivotY
8936     */
8937    public void setPivotY(float pivotY) {
8938        ensureTransformationInfo();
8939        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8940        final TransformationInfo info = mTransformationInfo;
8941        if (info.mPivotY != pivotY) {
8942            invalidateViewProperty(true, false);
8943            info.mPivotY = pivotY;
8944            info.mMatrixDirty = true;
8945            invalidateViewProperty(false, true);
8946            if (mDisplayList != null) {
8947                mDisplayList.setPivotY(pivotY);
8948            }
8949            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8950                // View was rejected last time it was drawn by its parent; this may have changed
8951                invalidateParentIfNeeded();
8952            }
8953        }
8954    }
8955
8956    /**
8957     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8958     * completely transparent and 1 means the view is completely opaque.
8959     *
8960     * <p>By default this is 1.0f.
8961     * @return The opacity of the view.
8962     */
8963    @ViewDebug.ExportedProperty(category = "drawing")
8964    public float getAlpha() {
8965        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8966    }
8967
8968    /**
8969     * Returns whether this View has content which overlaps. This function, intended to be
8970     * overridden by specific View types, is an optimization when alpha is set on a view. If
8971     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8972     * and then composited it into place, which can be expensive. If the view has no overlapping
8973     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8974     * An example of overlapping rendering is a TextView with a background image, such as a
8975     * Button. An example of non-overlapping rendering is a TextView with no background, or
8976     * an ImageView with only the foreground image. The default implementation returns true;
8977     * subclasses should override if they have cases which can be optimized.
8978     *
8979     * @return true if the content in this view might overlap, false otherwise.
8980     */
8981    public boolean hasOverlappingRendering() {
8982        return true;
8983    }
8984
8985    /**
8986     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8987     * completely transparent and 1 means the view is completely opaque.</p>
8988     *
8989     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8990     * responsible for applying the opacity itself. Otherwise, calling this method is
8991     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8992     * setting a hardware layer.</p>
8993     *
8994     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8995     * performance implications. It is generally best to use the alpha property sparingly and
8996     * transiently, as in the case of fading animations.</p>
8997     *
8998     * @param alpha The opacity of the view.
8999     *
9000     * @see #setLayerType(int, android.graphics.Paint)
9001     *
9002     * @attr ref android.R.styleable#View_alpha
9003     */
9004    public void setAlpha(float alpha) {
9005        ensureTransformationInfo();
9006        if (mTransformationInfo.mAlpha != alpha) {
9007            mTransformationInfo.mAlpha = alpha;
9008            if (onSetAlpha((int) (alpha * 255))) {
9009                mPrivateFlags |= ALPHA_SET;
9010                // subclass is handling alpha - don't optimize rendering cache invalidation
9011                invalidateParentCaches();
9012                invalidate(true);
9013            } else {
9014                mPrivateFlags &= ~ALPHA_SET;
9015                invalidateViewProperty(true, false);
9016                if (mDisplayList != null) {
9017                    mDisplayList.setAlpha(alpha);
9018                }
9019            }
9020        }
9021    }
9022
9023    /**
9024     * Faster version of setAlpha() which performs the same steps except there are
9025     * no calls to invalidate(). The caller of this function should perform proper invalidation
9026     * on the parent and this object. The return value indicates whether the subclass handles
9027     * alpha (the return value for onSetAlpha()).
9028     *
9029     * @param alpha The new value for the alpha property
9030     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9031     *         the new value for the alpha property is different from the old value
9032     */
9033    boolean setAlphaNoInvalidation(float alpha) {
9034        ensureTransformationInfo();
9035        if (mTransformationInfo.mAlpha != alpha) {
9036            mTransformationInfo.mAlpha = alpha;
9037            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9038            if (subclassHandlesAlpha) {
9039                mPrivateFlags |= ALPHA_SET;
9040                return true;
9041            } else {
9042                mPrivateFlags &= ~ALPHA_SET;
9043                if (mDisplayList != null) {
9044                    mDisplayList.setAlpha(alpha);
9045                }
9046            }
9047        }
9048        return false;
9049    }
9050
9051    /**
9052     * Top position of this view relative to its parent.
9053     *
9054     * @return The top of this view, in pixels.
9055     */
9056    @ViewDebug.CapturedViewProperty
9057    public final int getTop() {
9058        return mTop;
9059    }
9060
9061    /**
9062     * Sets the top position of this view relative to its parent. This method is meant to be called
9063     * by the layout system and should not generally be called otherwise, because the property
9064     * may be changed at any time by the layout.
9065     *
9066     * @param top The top of this view, in pixels.
9067     */
9068    public final void setTop(int top) {
9069        if (top != mTop) {
9070            updateMatrix();
9071            final boolean matrixIsIdentity = mTransformationInfo == null
9072                    || mTransformationInfo.mMatrixIsIdentity;
9073            if (matrixIsIdentity) {
9074                if (mAttachInfo != null) {
9075                    int minTop;
9076                    int yLoc;
9077                    if (top < mTop) {
9078                        minTop = top;
9079                        yLoc = top - mTop;
9080                    } else {
9081                        minTop = mTop;
9082                        yLoc = 0;
9083                    }
9084                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9085                }
9086            } else {
9087                // Double-invalidation is necessary to capture view's old and new areas
9088                invalidate(true);
9089            }
9090
9091            int width = mRight - mLeft;
9092            int oldHeight = mBottom - mTop;
9093
9094            mTop = top;
9095            if (mDisplayList != null) {
9096                mDisplayList.setTop(mTop);
9097            }
9098
9099            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9100
9101            if (!matrixIsIdentity) {
9102                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9103                    // A change in dimension means an auto-centered pivot point changes, too
9104                    mTransformationInfo.mMatrixDirty = true;
9105                }
9106                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9107                invalidate(true);
9108            }
9109            mBackgroundSizeChanged = true;
9110            invalidateParentIfNeeded();
9111            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9112                // View was rejected last time it was drawn by its parent; this may have changed
9113                invalidateParentIfNeeded();
9114            }
9115        }
9116    }
9117
9118    /**
9119     * Bottom position of this view relative to its parent.
9120     *
9121     * @return The bottom of this view, in pixels.
9122     */
9123    @ViewDebug.CapturedViewProperty
9124    public final int getBottom() {
9125        return mBottom;
9126    }
9127
9128    /**
9129     * True if this view has changed since the last time being drawn.
9130     *
9131     * @return The dirty state of this view.
9132     */
9133    public boolean isDirty() {
9134        return (mPrivateFlags & DIRTY_MASK) != 0;
9135    }
9136
9137    /**
9138     * Sets the bottom position of this view relative to its parent. This method is meant to be
9139     * called by the layout system and should not generally be called otherwise, because the
9140     * property may be changed at any time by the layout.
9141     *
9142     * @param bottom The bottom of this view, in pixels.
9143     */
9144    public final void setBottom(int bottom) {
9145        if (bottom != mBottom) {
9146            updateMatrix();
9147            final boolean matrixIsIdentity = mTransformationInfo == null
9148                    || mTransformationInfo.mMatrixIsIdentity;
9149            if (matrixIsIdentity) {
9150                if (mAttachInfo != null) {
9151                    int maxBottom;
9152                    if (bottom < mBottom) {
9153                        maxBottom = mBottom;
9154                    } else {
9155                        maxBottom = bottom;
9156                    }
9157                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9158                }
9159            } else {
9160                // Double-invalidation is necessary to capture view's old and new areas
9161                invalidate(true);
9162            }
9163
9164            int width = mRight - mLeft;
9165            int oldHeight = mBottom - mTop;
9166
9167            mBottom = bottom;
9168            if (mDisplayList != null) {
9169                mDisplayList.setBottom(mBottom);
9170            }
9171
9172            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9173
9174            if (!matrixIsIdentity) {
9175                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9176                    // A change in dimension means an auto-centered pivot point changes, too
9177                    mTransformationInfo.mMatrixDirty = true;
9178                }
9179                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9180                invalidate(true);
9181            }
9182            mBackgroundSizeChanged = true;
9183            invalidateParentIfNeeded();
9184            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9185                // View was rejected last time it was drawn by its parent; this may have changed
9186                invalidateParentIfNeeded();
9187            }
9188        }
9189    }
9190
9191    /**
9192     * Left position of this view relative to its parent.
9193     *
9194     * @return The left edge of this view, in pixels.
9195     */
9196    @ViewDebug.CapturedViewProperty
9197    public final int getLeft() {
9198        return mLeft;
9199    }
9200
9201    /**
9202     * Sets the left position of this view relative to its parent. This method is meant to be called
9203     * by the layout system and should not generally be called otherwise, because the property
9204     * may be changed at any time by the layout.
9205     *
9206     * @param left The bottom of this view, in pixels.
9207     */
9208    public final void setLeft(int left) {
9209        if (left != mLeft) {
9210            updateMatrix();
9211            final boolean matrixIsIdentity = mTransformationInfo == null
9212                    || mTransformationInfo.mMatrixIsIdentity;
9213            if (matrixIsIdentity) {
9214                if (mAttachInfo != null) {
9215                    int minLeft;
9216                    int xLoc;
9217                    if (left < mLeft) {
9218                        minLeft = left;
9219                        xLoc = left - mLeft;
9220                    } else {
9221                        minLeft = mLeft;
9222                        xLoc = 0;
9223                    }
9224                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9225                }
9226            } else {
9227                // Double-invalidation is necessary to capture view's old and new areas
9228                invalidate(true);
9229            }
9230
9231            int oldWidth = mRight - mLeft;
9232            int height = mBottom - mTop;
9233
9234            mLeft = left;
9235            if (mDisplayList != null) {
9236                mDisplayList.setLeft(left);
9237            }
9238
9239            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9240
9241            if (!matrixIsIdentity) {
9242                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9243                    // A change in dimension means an auto-centered pivot point changes, too
9244                    mTransformationInfo.mMatrixDirty = true;
9245                }
9246                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9247                invalidate(true);
9248            }
9249            mBackgroundSizeChanged = true;
9250            invalidateParentIfNeeded();
9251            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9252                // View was rejected last time it was drawn by its parent; this may have changed
9253                invalidateParentIfNeeded();
9254            }
9255        }
9256    }
9257
9258    /**
9259     * Right position of this view relative to its parent.
9260     *
9261     * @return The right edge of this view, in pixels.
9262     */
9263    @ViewDebug.CapturedViewProperty
9264    public final int getRight() {
9265        return mRight;
9266    }
9267
9268    /**
9269     * Sets the right position of this view relative to its parent. This method is meant to be called
9270     * by the layout system and should not generally be called otherwise, because the property
9271     * may be changed at any time by the layout.
9272     *
9273     * @param right The bottom of this view, in pixels.
9274     */
9275    public final void setRight(int right) {
9276        if (right != mRight) {
9277            updateMatrix();
9278            final boolean matrixIsIdentity = mTransformationInfo == null
9279                    || mTransformationInfo.mMatrixIsIdentity;
9280            if (matrixIsIdentity) {
9281                if (mAttachInfo != null) {
9282                    int maxRight;
9283                    if (right < mRight) {
9284                        maxRight = mRight;
9285                    } else {
9286                        maxRight = right;
9287                    }
9288                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9289                }
9290            } else {
9291                // Double-invalidation is necessary to capture view's old and new areas
9292                invalidate(true);
9293            }
9294
9295            int oldWidth = mRight - mLeft;
9296            int height = mBottom - mTop;
9297
9298            mRight = right;
9299            if (mDisplayList != null) {
9300                mDisplayList.setRight(mRight);
9301            }
9302
9303            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9304
9305            if (!matrixIsIdentity) {
9306                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9307                    // A change in dimension means an auto-centered pivot point changes, too
9308                    mTransformationInfo.mMatrixDirty = true;
9309                }
9310                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9311                invalidate(true);
9312            }
9313            mBackgroundSizeChanged = true;
9314            invalidateParentIfNeeded();
9315            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9316                // View was rejected last time it was drawn by its parent; this may have changed
9317                invalidateParentIfNeeded();
9318            }
9319        }
9320    }
9321
9322    /**
9323     * The visual x position of this view, in pixels. This is equivalent to the
9324     * {@link #setTranslationX(float) translationX} property plus the current
9325     * {@link #getLeft() left} property.
9326     *
9327     * @return The visual x position of this view, in pixels.
9328     */
9329    @ViewDebug.ExportedProperty(category = "drawing")
9330    public float getX() {
9331        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9332    }
9333
9334    /**
9335     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9336     * {@link #setTranslationX(float) translationX} property to be the difference between
9337     * the x value passed in and the current {@link #getLeft() left} property.
9338     *
9339     * @param x The visual x position of this view, in pixels.
9340     */
9341    public void setX(float x) {
9342        setTranslationX(x - mLeft);
9343    }
9344
9345    /**
9346     * The visual y position of this view, in pixels. This is equivalent to the
9347     * {@link #setTranslationY(float) translationY} property plus the current
9348     * {@link #getTop() top} property.
9349     *
9350     * @return The visual y position of this view, in pixels.
9351     */
9352    @ViewDebug.ExportedProperty(category = "drawing")
9353    public float getY() {
9354        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9355    }
9356
9357    /**
9358     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9359     * {@link #setTranslationY(float) translationY} property to be the difference between
9360     * the y value passed in and the current {@link #getTop() top} property.
9361     *
9362     * @param y The visual y position of this view, in pixels.
9363     */
9364    public void setY(float y) {
9365        setTranslationY(y - mTop);
9366    }
9367
9368
9369    /**
9370     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9371     * This position is post-layout, in addition to wherever the object's
9372     * layout placed it.
9373     *
9374     * @return The horizontal position of this view relative to its left position, in pixels.
9375     */
9376    @ViewDebug.ExportedProperty(category = "drawing")
9377    public float getTranslationX() {
9378        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9379    }
9380
9381    /**
9382     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9383     * This effectively positions the object post-layout, in addition to wherever the object's
9384     * layout placed it.
9385     *
9386     * @param translationX The horizontal position of this view relative to its left position,
9387     * in pixels.
9388     *
9389     * @attr ref android.R.styleable#View_translationX
9390     */
9391    public void setTranslationX(float translationX) {
9392        ensureTransformationInfo();
9393        final TransformationInfo info = mTransformationInfo;
9394        if (info.mTranslationX != translationX) {
9395            // Double-invalidation is necessary to capture view's old and new areas
9396            invalidateViewProperty(true, false);
9397            info.mTranslationX = translationX;
9398            info.mMatrixDirty = true;
9399            invalidateViewProperty(false, true);
9400            if (mDisplayList != null) {
9401                mDisplayList.setTranslationX(translationX);
9402            }
9403            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9404                // View was rejected last time it was drawn by its parent; this may have changed
9405                invalidateParentIfNeeded();
9406            }
9407        }
9408    }
9409
9410    /**
9411     * The horizontal location of this view relative to its {@link #getTop() top} position.
9412     * This position is post-layout, in addition to wherever the object's
9413     * layout placed it.
9414     *
9415     * @return The vertical position of this view relative to its top position,
9416     * in pixels.
9417     */
9418    @ViewDebug.ExportedProperty(category = "drawing")
9419    public float getTranslationY() {
9420        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9421    }
9422
9423    /**
9424     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9425     * This effectively positions the object post-layout, in addition to wherever the object's
9426     * layout placed it.
9427     *
9428     * @param translationY The vertical position of this view relative to its top position,
9429     * in pixels.
9430     *
9431     * @attr ref android.R.styleable#View_translationY
9432     */
9433    public void setTranslationY(float translationY) {
9434        ensureTransformationInfo();
9435        final TransformationInfo info = mTransformationInfo;
9436        if (info.mTranslationY != translationY) {
9437            invalidateViewProperty(true, false);
9438            info.mTranslationY = translationY;
9439            info.mMatrixDirty = true;
9440            invalidateViewProperty(false, true);
9441            if (mDisplayList != null) {
9442                mDisplayList.setTranslationY(translationY);
9443            }
9444            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9445                // View was rejected last time it was drawn by its parent; this may have changed
9446                invalidateParentIfNeeded();
9447            }
9448        }
9449    }
9450
9451    /**
9452     * Hit rectangle in parent's coordinates
9453     *
9454     * @param outRect The hit rectangle of the view.
9455     */
9456    public void getHitRect(Rect outRect) {
9457        updateMatrix();
9458        final TransformationInfo info = mTransformationInfo;
9459        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9460            outRect.set(mLeft, mTop, mRight, mBottom);
9461        } else {
9462            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9463            tmpRect.set(-info.mPivotX, -info.mPivotY,
9464                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9465            info.mMatrix.mapRect(tmpRect);
9466            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9467                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9468        }
9469    }
9470
9471    /**
9472     * Determines whether the given point, in local coordinates is inside the view.
9473     */
9474    /*package*/ final boolean pointInView(float localX, float localY) {
9475        return localX >= 0 && localX < (mRight - mLeft)
9476                && localY >= 0 && localY < (mBottom - mTop);
9477    }
9478
9479    /**
9480     * Utility method to determine whether the given point, in local coordinates,
9481     * is inside the view, where the area of the view is expanded by the slop factor.
9482     * This method is called while processing touch-move events to determine if the event
9483     * is still within the view.
9484     */
9485    private boolean pointInView(float localX, float localY, float slop) {
9486        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9487                localY < ((mBottom - mTop) + slop);
9488    }
9489
9490    /**
9491     * When a view has focus and the user navigates away from it, the next view is searched for
9492     * starting from the rectangle filled in by this method.
9493     *
9494     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9495     * of the view.  However, if your view maintains some idea of internal selection,
9496     * such as a cursor, or a selected row or column, you should override this method and
9497     * fill in a more specific rectangle.
9498     *
9499     * @param r The rectangle to fill in, in this view's coordinates.
9500     */
9501    public void getFocusedRect(Rect r) {
9502        getDrawingRect(r);
9503    }
9504
9505    /**
9506     * If some part of this view is not clipped by any of its parents, then
9507     * return that area in r in global (root) coordinates. To convert r to local
9508     * coordinates (without taking possible View rotations into account), offset
9509     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9510     * If the view is completely clipped or translated out, return false.
9511     *
9512     * @param r If true is returned, r holds the global coordinates of the
9513     *        visible portion of this view.
9514     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9515     *        between this view and its root. globalOffet may be null.
9516     * @return true if r is non-empty (i.e. part of the view is visible at the
9517     *         root level.
9518     */
9519    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9520        int width = mRight - mLeft;
9521        int height = mBottom - mTop;
9522        if (width > 0 && height > 0) {
9523            r.set(0, 0, width, height);
9524            if (globalOffset != null) {
9525                globalOffset.set(-mScrollX, -mScrollY);
9526            }
9527            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9528        }
9529        return false;
9530    }
9531
9532    public final boolean getGlobalVisibleRect(Rect r) {
9533        return getGlobalVisibleRect(r, null);
9534    }
9535
9536    public final boolean getLocalVisibleRect(Rect r) {
9537        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9538        if (getGlobalVisibleRect(r, offset)) {
9539            r.offset(-offset.x, -offset.y); // make r local
9540            return true;
9541        }
9542        return false;
9543    }
9544
9545    /**
9546     * Offset this view's vertical location by the specified number of pixels.
9547     *
9548     * @param offset the number of pixels to offset the view by
9549     */
9550    public void offsetTopAndBottom(int offset) {
9551        if (offset != 0) {
9552            updateMatrix();
9553            final boolean matrixIsIdentity = mTransformationInfo == null
9554                    || mTransformationInfo.mMatrixIsIdentity;
9555            if (matrixIsIdentity) {
9556                if (mDisplayList != null) {
9557                    invalidateViewProperty(false, false);
9558                } else {
9559                    final ViewParent p = mParent;
9560                    if (p != null && mAttachInfo != null) {
9561                        final Rect r = mAttachInfo.mTmpInvalRect;
9562                        int minTop;
9563                        int maxBottom;
9564                        int yLoc;
9565                        if (offset < 0) {
9566                            minTop = mTop + offset;
9567                            maxBottom = mBottom;
9568                            yLoc = offset;
9569                        } else {
9570                            minTop = mTop;
9571                            maxBottom = mBottom + offset;
9572                            yLoc = 0;
9573                        }
9574                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9575                        p.invalidateChild(this, r);
9576                    }
9577                }
9578            } else {
9579                invalidateViewProperty(false, false);
9580            }
9581
9582            mTop += offset;
9583            mBottom += offset;
9584            if (mDisplayList != null) {
9585                mDisplayList.offsetTopBottom(offset);
9586                invalidateViewProperty(false, false);
9587            } else {
9588                if (!matrixIsIdentity) {
9589                    invalidateViewProperty(false, true);
9590                }
9591                invalidateParentIfNeeded();
9592            }
9593        }
9594    }
9595
9596    /**
9597     * Offset this view's horizontal location by the specified amount of pixels.
9598     *
9599     * @param offset the numer of pixels to offset the view by
9600     */
9601    public void offsetLeftAndRight(int offset) {
9602        if (offset != 0) {
9603            updateMatrix();
9604            final boolean matrixIsIdentity = mTransformationInfo == null
9605                    || mTransformationInfo.mMatrixIsIdentity;
9606            if (matrixIsIdentity) {
9607                if (mDisplayList != null) {
9608                    invalidateViewProperty(false, false);
9609                } else {
9610                    final ViewParent p = mParent;
9611                    if (p != null && mAttachInfo != null) {
9612                        final Rect r = mAttachInfo.mTmpInvalRect;
9613                        int minLeft;
9614                        int maxRight;
9615                        if (offset < 0) {
9616                            minLeft = mLeft + offset;
9617                            maxRight = mRight;
9618                        } else {
9619                            minLeft = mLeft;
9620                            maxRight = mRight + offset;
9621                        }
9622                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9623                        p.invalidateChild(this, r);
9624                    }
9625                }
9626            } else {
9627                invalidateViewProperty(false, false);
9628            }
9629
9630            mLeft += offset;
9631            mRight += offset;
9632            if (mDisplayList != null) {
9633                mDisplayList.offsetLeftRight(offset);
9634                invalidateViewProperty(false, false);
9635            } else {
9636                if (!matrixIsIdentity) {
9637                    invalidateViewProperty(false, true);
9638                }
9639                invalidateParentIfNeeded();
9640            }
9641        }
9642    }
9643
9644    /**
9645     * Get the LayoutParams associated with this view. All views should have
9646     * layout parameters. These supply parameters to the <i>parent</i> of this
9647     * view specifying how it should be arranged. There are many subclasses of
9648     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9649     * of ViewGroup that are responsible for arranging their children.
9650     *
9651     * This method may return null if this View is not attached to a parent
9652     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9653     * was not invoked successfully. When a View is attached to a parent
9654     * ViewGroup, this method must not return null.
9655     *
9656     * @return The LayoutParams associated with this view, or null if no
9657     *         parameters have been set yet
9658     */
9659    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9660    public ViewGroup.LayoutParams getLayoutParams() {
9661        return mLayoutParams;
9662    }
9663
9664    /**
9665     * Set the layout parameters associated with this view. These supply
9666     * parameters to the <i>parent</i> of this view specifying how it should be
9667     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9668     * correspond to the different subclasses of ViewGroup that are responsible
9669     * for arranging their children.
9670     *
9671     * @param params The layout parameters for this view, cannot be null
9672     */
9673    public void setLayoutParams(ViewGroup.LayoutParams params) {
9674        if (params == null) {
9675            throw new NullPointerException("Layout parameters cannot be null");
9676        }
9677        mLayoutParams = params;
9678        if (mParent instanceof ViewGroup) {
9679            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9680        }
9681        requestLayout();
9682    }
9683
9684    /**
9685     * Set the scrolled position of your view. This will cause a call to
9686     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9687     * invalidated.
9688     * @param x the x position to scroll to
9689     * @param y the y position to scroll to
9690     */
9691    public void scrollTo(int x, int y) {
9692        if (mScrollX != x || mScrollY != y) {
9693            int oldX = mScrollX;
9694            int oldY = mScrollY;
9695            mScrollX = x;
9696            mScrollY = y;
9697            invalidateParentCaches();
9698            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9699            if (!awakenScrollBars()) {
9700                postInvalidateOnAnimation();
9701            }
9702        }
9703    }
9704
9705    /**
9706     * Move the scrolled position of your view. This will cause a call to
9707     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9708     * invalidated.
9709     * @param x the amount of pixels to scroll by horizontally
9710     * @param y the amount of pixels to scroll by vertically
9711     */
9712    public void scrollBy(int x, int y) {
9713        scrollTo(mScrollX + x, mScrollY + y);
9714    }
9715
9716    /**
9717     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9718     * animation to fade the scrollbars out after a default delay. If a subclass
9719     * provides animated scrolling, the start delay should equal the duration
9720     * of the scrolling animation.</p>
9721     *
9722     * <p>The animation starts only if at least one of the scrollbars is
9723     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9724     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9725     * this method returns true, and false otherwise. If the animation is
9726     * started, this method calls {@link #invalidate()}; in that case the
9727     * caller should not call {@link #invalidate()}.</p>
9728     *
9729     * <p>This method should be invoked every time a subclass directly updates
9730     * the scroll parameters.</p>
9731     *
9732     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9733     * and {@link #scrollTo(int, int)}.</p>
9734     *
9735     * @return true if the animation is played, false otherwise
9736     *
9737     * @see #awakenScrollBars(int)
9738     * @see #scrollBy(int, int)
9739     * @see #scrollTo(int, int)
9740     * @see #isHorizontalScrollBarEnabled()
9741     * @see #isVerticalScrollBarEnabled()
9742     * @see #setHorizontalScrollBarEnabled(boolean)
9743     * @see #setVerticalScrollBarEnabled(boolean)
9744     */
9745    protected boolean awakenScrollBars() {
9746        return mScrollCache != null &&
9747                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9748    }
9749
9750    /**
9751     * Trigger the scrollbars to draw.
9752     * This method differs from awakenScrollBars() only in its default duration.
9753     * initialAwakenScrollBars() will show the scroll bars for longer than
9754     * usual to give the user more of a chance to notice them.
9755     *
9756     * @return true if the animation is played, false otherwise.
9757     */
9758    private boolean initialAwakenScrollBars() {
9759        return mScrollCache != null &&
9760                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9761    }
9762
9763    /**
9764     * <p>
9765     * Trigger the scrollbars to draw. When invoked this method starts an
9766     * animation to fade the scrollbars out after a fixed delay. If a subclass
9767     * provides animated scrolling, the start delay should equal the duration of
9768     * the scrolling animation.
9769     * </p>
9770     *
9771     * <p>
9772     * The animation starts only if at least one of the scrollbars is enabled,
9773     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9774     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9775     * this method returns true, and false otherwise. If the animation is
9776     * started, this method calls {@link #invalidate()}; in that case the caller
9777     * should not call {@link #invalidate()}.
9778     * </p>
9779     *
9780     * <p>
9781     * This method should be invoked everytime a subclass directly updates the
9782     * scroll parameters.
9783     * </p>
9784     *
9785     * @param startDelay the delay, in milliseconds, after which the animation
9786     *        should start; when the delay is 0, the animation starts
9787     *        immediately
9788     * @return true if the animation is played, false otherwise
9789     *
9790     * @see #scrollBy(int, int)
9791     * @see #scrollTo(int, int)
9792     * @see #isHorizontalScrollBarEnabled()
9793     * @see #isVerticalScrollBarEnabled()
9794     * @see #setHorizontalScrollBarEnabled(boolean)
9795     * @see #setVerticalScrollBarEnabled(boolean)
9796     */
9797    protected boolean awakenScrollBars(int startDelay) {
9798        return awakenScrollBars(startDelay, true);
9799    }
9800
9801    /**
9802     * <p>
9803     * Trigger the scrollbars to draw. When invoked this method starts an
9804     * animation to fade the scrollbars out after a fixed delay. If a subclass
9805     * provides animated scrolling, the start delay should equal the duration of
9806     * the scrolling animation.
9807     * </p>
9808     *
9809     * <p>
9810     * The animation starts only if at least one of the scrollbars is enabled,
9811     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9812     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9813     * this method returns true, and false otherwise. If the animation is
9814     * started, this method calls {@link #invalidate()} if the invalidate parameter
9815     * is set to true; in that case the caller
9816     * should not call {@link #invalidate()}.
9817     * </p>
9818     *
9819     * <p>
9820     * This method should be invoked everytime a subclass directly updates the
9821     * scroll parameters.
9822     * </p>
9823     *
9824     * @param startDelay the delay, in milliseconds, after which the animation
9825     *        should start; when the delay is 0, the animation starts
9826     *        immediately
9827     *
9828     * @param invalidate Wheter this method should call invalidate
9829     *
9830     * @return true if the animation is played, false otherwise
9831     *
9832     * @see #scrollBy(int, int)
9833     * @see #scrollTo(int, int)
9834     * @see #isHorizontalScrollBarEnabled()
9835     * @see #isVerticalScrollBarEnabled()
9836     * @see #setHorizontalScrollBarEnabled(boolean)
9837     * @see #setVerticalScrollBarEnabled(boolean)
9838     */
9839    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9840        final ScrollabilityCache scrollCache = mScrollCache;
9841
9842        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9843            return false;
9844        }
9845
9846        if (scrollCache.scrollBar == null) {
9847            scrollCache.scrollBar = new ScrollBarDrawable();
9848        }
9849
9850        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9851
9852            if (invalidate) {
9853                // Invalidate to show the scrollbars
9854                postInvalidateOnAnimation();
9855            }
9856
9857            if (scrollCache.state == ScrollabilityCache.OFF) {
9858                // FIXME: this is copied from WindowManagerService.
9859                // We should get this value from the system when it
9860                // is possible to do so.
9861                final int KEY_REPEAT_FIRST_DELAY = 750;
9862                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9863            }
9864
9865            // Tell mScrollCache when we should start fading. This may
9866            // extend the fade start time if one was already scheduled
9867            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9868            scrollCache.fadeStartTime = fadeStartTime;
9869            scrollCache.state = ScrollabilityCache.ON;
9870
9871            // Schedule our fader to run, unscheduling any old ones first
9872            if (mAttachInfo != null) {
9873                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9874                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9875            }
9876
9877            return true;
9878        }
9879
9880        return false;
9881    }
9882
9883    /**
9884     * Do not invalidate views which are not visible and which are not running an animation. They
9885     * will not get drawn and they should not set dirty flags as if they will be drawn
9886     */
9887    private boolean skipInvalidate() {
9888        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9889                (!(mParent instanceof ViewGroup) ||
9890                        !((ViewGroup) mParent).isViewTransitioning(this));
9891    }
9892    /**
9893     * Mark the area defined by dirty as needing to be drawn. If the view is
9894     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9895     * in the future. This must be called from a UI thread. To call from a non-UI
9896     * thread, call {@link #postInvalidate()}.
9897     *
9898     * WARNING: This method is destructive to dirty.
9899     * @param dirty the rectangle representing the bounds of the dirty region
9900     */
9901    public void invalidate(Rect dirty) {
9902        if (skipInvalidate()) {
9903            return;
9904        }
9905        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9906                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9907                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9908            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9909            mPrivateFlags |= INVALIDATED;
9910            mPrivateFlags |= DIRTY;
9911            final ViewParent p = mParent;
9912            final AttachInfo ai = mAttachInfo;
9913            //noinspection PointlessBooleanExpression,ConstantConditions
9914            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9915                if (p != null && ai != null && ai.mHardwareAccelerated) {
9916                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9917                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9918                    p.invalidateChild(this, null);
9919                    return;
9920                }
9921            }
9922            if (p != null && ai != null) {
9923                final int scrollX = mScrollX;
9924                final int scrollY = mScrollY;
9925                final Rect r = ai.mTmpInvalRect;
9926                r.set(dirty.left - scrollX, dirty.top - scrollY,
9927                        dirty.right - scrollX, dirty.bottom - scrollY);
9928                mParent.invalidateChild(this, r);
9929            }
9930        }
9931    }
9932
9933    /**
9934     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9935     * The coordinates of the dirty rect are relative to the view.
9936     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9937     * will be called at some point in the future. This must be called from
9938     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9939     * @param l the left position of the dirty region
9940     * @param t the top position of the dirty region
9941     * @param r the right position of the dirty region
9942     * @param b the bottom position of the dirty region
9943     */
9944    public void invalidate(int l, int t, int r, int b) {
9945        if (skipInvalidate()) {
9946            return;
9947        }
9948        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9949                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9950                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9951            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9952            mPrivateFlags |= INVALIDATED;
9953            mPrivateFlags |= DIRTY;
9954            final ViewParent p = mParent;
9955            final AttachInfo ai = mAttachInfo;
9956            //noinspection PointlessBooleanExpression,ConstantConditions
9957            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9958                if (p != null && ai != null && ai.mHardwareAccelerated) {
9959                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9960                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9961                    p.invalidateChild(this, null);
9962                    return;
9963                }
9964            }
9965            if (p != null && ai != null && l < r && t < b) {
9966                final int scrollX = mScrollX;
9967                final int scrollY = mScrollY;
9968                final Rect tmpr = ai.mTmpInvalRect;
9969                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9970                p.invalidateChild(this, tmpr);
9971            }
9972        }
9973    }
9974
9975    /**
9976     * Invalidate the whole view. If the view is visible,
9977     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9978     * the future. This must be called from a UI thread. To call from a non-UI thread,
9979     * call {@link #postInvalidate()}.
9980     */
9981    public void invalidate() {
9982        invalidate(true);
9983    }
9984
9985    /**
9986     * This is where the invalidate() work actually happens. A full invalidate()
9987     * causes the drawing cache to be invalidated, but this function can be called with
9988     * invalidateCache set to false to skip that invalidation step for cases that do not
9989     * need it (for example, a component that remains at the same dimensions with the same
9990     * content).
9991     *
9992     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9993     * well. This is usually true for a full invalidate, but may be set to false if the
9994     * View's contents or dimensions have not changed.
9995     */
9996    void invalidate(boolean invalidateCache) {
9997        if (skipInvalidate()) {
9998            return;
9999        }
10000        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10001                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
10002                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10003            mLastIsOpaque = isOpaque();
10004            mPrivateFlags &= ~DRAWN;
10005            mPrivateFlags |= DIRTY;
10006            if (invalidateCache) {
10007                mPrivateFlags |= INVALIDATED;
10008                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10009            }
10010            final AttachInfo ai = mAttachInfo;
10011            final ViewParent p = mParent;
10012            //noinspection PointlessBooleanExpression,ConstantConditions
10013            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10014                if (p != null && ai != null && ai.mHardwareAccelerated) {
10015                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10016                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10017                    p.invalidateChild(this, null);
10018                    return;
10019                }
10020            }
10021
10022            if (p != null && ai != null) {
10023                final Rect r = ai.mTmpInvalRect;
10024                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10025                // Don't call invalidate -- we don't want to internally scroll
10026                // our own bounds
10027                p.invalidateChild(this, r);
10028            }
10029        }
10030    }
10031
10032    /**
10033     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10034     * set any flags or handle all of the cases handled by the default invalidation methods.
10035     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10036     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10037     * walk up the hierarchy, transforming the dirty rect as necessary.
10038     *
10039     * The method also handles normal invalidation logic if display list properties are not
10040     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10041     * backup approach, to handle these cases used in the various property-setting methods.
10042     *
10043     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10044     * are not being used in this view
10045     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10046     * list properties are not being used in this view
10047     */
10048    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10049        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10050            if (invalidateParent) {
10051                invalidateParentCaches();
10052            }
10053            if (forceRedraw) {
10054                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10055            }
10056            invalidate(false);
10057        } else {
10058            final AttachInfo ai = mAttachInfo;
10059            final ViewParent p = mParent;
10060            if (p != null && ai != null) {
10061                final Rect r = ai.mTmpInvalRect;
10062                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10063                if (mParent instanceof ViewGroup) {
10064                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10065                } else {
10066                    mParent.invalidateChild(this, r);
10067                }
10068            }
10069        }
10070    }
10071
10072    /**
10073     * Utility method to transform a given Rect by the current matrix of this view.
10074     */
10075    void transformRect(final Rect rect) {
10076        if (!getMatrix().isIdentity()) {
10077            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10078            boundingRect.set(rect);
10079            getMatrix().mapRect(boundingRect);
10080            rect.set((int) (boundingRect.left - 0.5f),
10081                    (int) (boundingRect.top - 0.5f),
10082                    (int) (boundingRect.right + 0.5f),
10083                    (int) (boundingRect.bottom + 0.5f));
10084        }
10085    }
10086
10087    /**
10088     * Used to indicate that the parent of this view should clear its caches. This functionality
10089     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10090     * which is necessary when various parent-managed properties of the view change, such as
10091     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10092     * clears the parent caches and does not causes an invalidate event.
10093     *
10094     * @hide
10095     */
10096    protected void invalidateParentCaches() {
10097        if (mParent instanceof View) {
10098            ((View) mParent).mPrivateFlags |= INVALIDATED;
10099        }
10100    }
10101
10102    /**
10103     * Used to indicate that the parent of this view should be invalidated. This functionality
10104     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10105     * which is necessary when various parent-managed properties of the view change, such as
10106     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10107     * an invalidation event to the parent.
10108     *
10109     * @hide
10110     */
10111    protected void invalidateParentIfNeeded() {
10112        if (isHardwareAccelerated() && mParent instanceof View) {
10113            ((View) mParent).invalidate(true);
10114        }
10115    }
10116
10117    /**
10118     * Indicates whether this View is opaque. An opaque View guarantees that it will
10119     * draw all the pixels overlapping its bounds using a fully opaque color.
10120     *
10121     * Subclasses of View should override this method whenever possible to indicate
10122     * whether an instance is opaque. Opaque Views are treated in a special way by
10123     * the View hierarchy, possibly allowing it to perform optimizations during
10124     * invalidate/draw passes.
10125     *
10126     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10127     */
10128    @ViewDebug.ExportedProperty(category = "drawing")
10129    public boolean isOpaque() {
10130        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10131                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10132                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10133    }
10134
10135    /**
10136     * @hide
10137     */
10138    protected void computeOpaqueFlags() {
10139        // Opaque if:
10140        //   - Has a background
10141        //   - Background is opaque
10142        //   - Doesn't have scrollbars or scrollbars are inside overlay
10143
10144        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10145            mPrivateFlags |= OPAQUE_BACKGROUND;
10146        } else {
10147            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10148        }
10149
10150        final int flags = mViewFlags;
10151        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10152                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10153            mPrivateFlags |= OPAQUE_SCROLLBARS;
10154        } else {
10155            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10156        }
10157    }
10158
10159    /**
10160     * @hide
10161     */
10162    protected boolean hasOpaqueScrollbars() {
10163        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10164    }
10165
10166    /**
10167     * @return A handler associated with the thread running the View. This
10168     * handler can be used to pump events in the UI events queue.
10169     */
10170    public Handler getHandler() {
10171        if (mAttachInfo != null) {
10172            return mAttachInfo.mHandler;
10173        }
10174        return null;
10175    }
10176
10177    /**
10178     * Gets the view root associated with the View.
10179     * @return The view root, or null if none.
10180     * @hide
10181     */
10182    public ViewRootImpl getViewRootImpl() {
10183        if (mAttachInfo != null) {
10184            return mAttachInfo.mViewRootImpl;
10185        }
10186        return null;
10187    }
10188
10189    /**
10190     * <p>Causes the Runnable to be added to the message queue.
10191     * The runnable will be run on the user interface thread.</p>
10192     *
10193     * <p>This method can be invoked from outside of the UI thread
10194     * only when this View is attached to a window.</p>
10195     *
10196     * @param action The Runnable that will be executed.
10197     *
10198     * @return Returns true if the Runnable was successfully placed in to the
10199     *         message queue.  Returns false on failure, usually because the
10200     *         looper processing the message queue is exiting.
10201     *
10202     * @see #postDelayed
10203     * @see #removeCallbacks
10204     */
10205    public boolean post(Runnable action) {
10206        final AttachInfo attachInfo = mAttachInfo;
10207        if (attachInfo != null) {
10208            return attachInfo.mHandler.post(action);
10209        }
10210        // Assume that post will succeed later
10211        ViewRootImpl.getRunQueue().post(action);
10212        return true;
10213    }
10214
10215    /**
10216     * <p>Causes the Runnable to be added to the message queue, to be run
10217     * after the specified amount of time elapses.
10218     * The runnable will be run on the user interface thread.</p>
10219     *
10220     * <p>This method can be invoked from outside of the UI thread
10221     * only when this View is attached to a window.</p>
10222     *
10223     * @param action The Runnable that will be executed.
10224     * @param delayMillis The delay (in milliseconds) until the Runnable
10225     *        will be executed.
10226     *
10227     * @return true if the Runnable was successfully placed in to the
10228     *         message queue.  Returns false on failure, usually because the
10229     *         looper processing the message queue is exiting.  Note that a
10230     *         result of true does not mean the Runnable will be processed --
10231     *         if the looper is quit before the delivery time of the message
10232     *         occurs then the message will be dropped.
10233     *
10234     * @see #post
10235     * @see #removeCallbacks
10236     */
10237    public boolean postDelayed(Runnable action, long delayMillis) {
10238        final AttachInfo attachInfo = mAttachInfo;
10239        if (attachInfo != null) {
10240            return attachInfo.mHandler.postDelayed(action, delayMillis);
10241        }
10242        // Assume that post will succeed later
10243        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10244        return true;
10245    }
10246
10247    /**
10248     * <p>Causes the Runnable to execute on the next animation time step.
10249     * The runnable will be run on the user interface thread.</p>
10250     *
10251     * <p>This method can be invoked from outside of the UI thread
10252     * only when this View is attached to a window.</p>
10253     *
10254     * @param action The Runnable that will be executed.
10255     *
10256     * @see #postOnAnimationDelayed
10257     * @see #removeCallbacks
10258     */
10259    public void postOnAnimation(Runnable action) {
10260        final AttachInfo attachInfo = mAttachInfo;
10261        if (attachInfo != null) {
10262            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10263                    Choreographer.CALLBACK_ANIMATION, action, null);
10264        } else {
10265            // Assume that post will succeed later
10266            ViewRootImpl.getRunQueue().post(action);
10267        }
10268    }
10269
10270    /**
10271     * <p>Causes the Runnable to execute on the next animation time step,
10272     * after the specified amount of time elapses.
10273     * The runnable will be run on the user interface thread.</p>
10274     *
10275     * <p>This method can be invoked from outside of the UI thread
10276     * only when this View is attached to a window.</p>
10277     *
10278     * @param action The Runnable that will be executed.
10279     * @param delayMillis The delay (in milliseconds) until the Runnable
10280     *        will be executed.
10281     *
10282     * @see #postOnAnimation
10283     * @see #removeCallbacks
10284     */
10285    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10286        final AttachInfo attachInfo = mAttachInfo;
10287        if (attachInfo != null) {
10288            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10289                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10290        } else {
10291            // Assume that post will succeed later
10292            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10293        }
10294    }
10295
10296    /**
10297     * <p>Removes the specified Runnable from the message queue.</p>
10298     *
10299     * <p>This method can be invoked from outside of the UI thread
10300     * only when this View is attached to a window.</p>
10301     *
10302     * @param action The Runnable to remove from the message handling queue
10303     *
10304     * @return true if this view could ask the Handler to remove the Runnable,
10305     *         false otherwise. When the returned value is true, the Runnable
10306     *         may or may not have been actually removed from the message queue
10307     *         (for instance, if the Runnable was not in the queue already.)
10308     *
10309     * @see #post
10310     * @see #postDelayed
10311     * @see #postOnAnimation
10312     * @see #postOnAnimationDelayed
10313     */
10314    public boolean removeCallbacks(Runnable action) {
10315        if (action != null) {
10316            final AttachInfo attachInfo = mAttachInfo;
10317            if (attachInfo != null) {
10318                attachInfo.mHandler.removeCallbacks(action);
10319                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10320                        Choreographer.CALLBACK_ANIMATION, action, null);
10321            } else {
10322                // Assume that post will succeed later
10323                ViewRootImpl.getRunQueue().removeCallbacks(action);
10324            }
10325        }
10326        return true;
10327    }
10328
10329    /**
10330     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10331     * Use this to invalidate the View from a non-UI thread.</p>
10332     *
10333     * <p>This method can be invoked from outside of the UI thread
10334     * only when this View is attached to a window.</p>
10335     *
10336     * @see #invalidate()
10337     * @see #postInvalidateDelayed(long)
10338     */
10339    public void postInvalidate() {
10340        postInvalidateDelayed(0);
10341    }
10342
10343    /**
10344     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10345     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10346     *
10347     * <p>This method can be invoked from outside of the UI thread
10348     * only when this View is attached to a window.</p>
10349     *
10350     * @param left The left coordinate of the rectangle to invalidate.
10351     * @param top The top coordinate of the rectangle to invalidate.
10352     * @param right The right coordinate of the rectangle to invalidate.
10353     * @param bottom The bottom coordinate of the rectangle to invalidate.
10354     *
10355     * @see #invalidate(int, int, int, int)
10356     * @see #invalidate(Rect)
10357     * @see #postInvalidateDelayed(long, int, int, int, int)
10358     */
10359    public void postInvalidate(int left, int top, int right, int bottom) {
10360        postInvalidateDelayed(0, left, top, right, bottom);
10361    }
10362
10363    /**
10364     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10365     * loop. Waits for the specified amount of time.</p>
10366     *
10367     * <p>This method can be invoked from outside of the UI thread
10368     * only when this View is attached to a window.</p>
10369     *
10370     * @param delayMilliseconds the duration in milliseconds to delay the
10371     *         invalidation by
10372     *
10373     * @see #invalidate()
10374     * @see #postInvalidate()
10375     */
10376    public void postInvalidateDelayed(long delayMilliseconds) {
10377        // We try only with the AttachInfo because there's no point in invalidating
10378        // if we are not attached to our window
10379        final AttachInfo attachInfo = mAttachInfo;
10380        if (attachInfo != null) {
10381            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10382        }
10383    }
10384
10385    /**
10386     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10387     * through the event loop. Waits for the specified amount of time.</p>
10388     *
10389     * <p>This method can be invoked from outside of the UI thread
10390     * only when this View is attached to a window.</p>
10391     *
10392     * @param delayMilliseconds the duration in milliseconds to delay the
10393     *         invalidation by
10394     * @param left The left coordinate of the rectangle to invalidate.
10395     * @param top The top coordinate of the rectangle to invalidate.
10396     * @param right The right coordinate of the rectangle to invalidate.
10397     * @param bottom The bottom coordinate of the rectangle to invalidate.
10398     *
10399     * @see #invalidate(int, int, int, int)
10400     * @see #invalidate(Rect)
10401     * @see #postInvalidate(int, int, int, int)
10402     */
10403    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10404            int right, int bottom) {
10405
10406        // We try only with the AttachInfo because there's no point in invalidating
10407        // if we are not attached to our window
10408        final AttachInfo attachInfo = mAttachInfo;
10409        if (attachInfo != null) {
10410            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10411            info.target = this;
10412            info.left = left;
10413            info.top = top;
10414            info.right = right;
10415            info.bottom = bottom;
10416
10417            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10418        }
10419    }
10420
10421    /**
10422     * <p>Cause an invalidate to happen on the next animation time step, typically the
10423     * next display frame.</p>
10424     *
10425     * <p>This method can be invoked from outside of the UI thread
10426     * only when this View is attached to a window.</p>
10427     *
10428     * @see #invalidate()
10429     */
10430    public void postInvalidateOnAnimation() {
10431        // We try only with the AttachInfo because there's no point in invalidating
10432        // if we are not attached to our window
10433        final AttachInfo attachInfo = mAttachInfo;
10434        if (attachInfo != null) {
10435            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10436        }
10437    }
10438
10439    /**
10440     * <p>Cause an invalidate of the specified area to happen on the next animation
10441     * time step, typically the next display frame.</p>
10442     *
10443     * <p>This method can be invoked from outside of the UI thread
10444     * only when this View is attached to a window.</p>
10445     *
10446     * @param left The left coordinate of the rectangle to invalidate.
10447     * @param top The top coordinate of the rectangle to invalidate.
10448     * @param right The right coordinate of the rectangle to invalidate.
10449     * @param bottom The bottom coordinate of the rectangle to invalidate.
10450     *
10451     * @see #invalidate(int, int, int, int)
10452     * @see #invalidate(Rect)
10453     */
10454    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10455        // We try only with the AttachInfo because there's no point in invalidating
10456        // if we are not attached to our window
10457        final AttachInfo attachInfo = mAttachInfo;
10458        if (attachInfo != null) {
10459            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10460            info.target = this;
10461            info.left = left;
10462            info.top = top;
10463            info.right = right;
10464            info.bottom = bottom;
10465
10466            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10467        }
10468    }
10469
10470    /**
10471     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10472     * This event is sent at most once every
10473     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10474     */
10475    private void postSendViewScrolledAccessibilityEventCallback() {
10476        if (mSendViewScrolledAccessibilityEvent == null) {
10477            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10478        }
10479        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10480            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10481            postDelayed(mSendViewScrolledAccessibilityEvent,
10482                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10483        }
10484    }
10485
10486    /**
10487     * Called by a parent to request that a child update its values for mScrollX
10488     * and mScrollY if necessary. This will typically be done if the child is
10489     * animating a scroll using a {@link android.widget.Scroller Scroller}
10490     * object.
10491     */
10492    public void computeScroll() {
10493    }
10494
10495    /**
10496     * <p>Indicate whether the horizontal edges are faded when the view is
10497     * scrolled horizontally.</p>
10498     *
10499     * @return true if the horizontal edges should are faded on scroll, false
10500     *         otherwise
10501     *
10502     * @see #setHorizontalFadingEdgeEnabled(boolean)
10503     *
10504     * @attr ref android.R.styleable#View_requiresFadingEdge
10505     */
10506    public boolean isHorizontalFadingEdgeEnabled() {
10507        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10508    }
10509
10510    /**
10511     * <p>Define whether the horizontal edges should be faded when this view
10512     * is scrolled horizontally.</p>
10513     *
10514     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10515     *                                    be faded when the view is scrolled
10516     *                                    horizontally
10517     *
10518     * @see #isHorizontalFadingEdgeEnabled()
10519     *
10520     * @attr ref android.R.styleable#View_requiresFadingEdge
10521     */
10522    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10523        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10524            if (horizontalFadingEdgeEnabled) {
10525                initScrollCache();
10526            }
10527
10528            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10529        }
10530    }
10531
10532    /**
10533     * <p>Indicate whether the vertical edges are faded when the view is
10534     * scrolled horizontally.</p>
10535     *
10536     * @return true if the vertical edges should are faded on scroll, false
10537     *         otherwise
10538     *
10539     * @see #setVerticalFadingEdgeEnabled(boolean)
10540     *
10541     * @attr ref android.R.styleable#View_requiresFadingEdge
10542     */
10543    public boolean isVerticalFadingEdgeEnabled() {
10544        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10545    }
10546
10547    /**
10548     * <p>Define whether the vertical edges should be faded when this view
10549     * is scrolled vertically.</p>
10550     *
10551     * @param verticalFadingEdgeEnabled true if the vertical edges should
10552     *                                  be faded when the view is scrolled
10553     *                                  vertically
10554     *
10555     * @see #isVerticalFadingEdgeEnabled()
10556     *
10557     * @attr ref android.R.styleable#View_requiresFadingEdge
10558     */
10559    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10560        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10561            if (verticalFadingEdgeEnabled) {
10562                initScrollCache();
10563            }
10564
10565            mViewFlags ^= FADING_EDGE_VERTICAL;
10566        }
10567    }
10568
10569    /**
10570     * Returns the strength, or intensity, of the top faded edge. The strength is
10571     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10572     * returns 0.0 or 1.0 but no value in between.
10573     *
10574     * Subclasses should override this method to provide a smoother fade transition
10575     * when scrolling occurs.
10576     *
10577     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10578     */
10579    protected float getTopFadingEdgeStrength() {
10580        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10581    }
10582
10583    /**
10584     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10585     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10586     * returns 0.0 or 1.0 but no value in between.
10587     *
10588     * Subclasses should override this method to provide a smoother fade transition
10589     * when scrolling occurs.
10590     *
10591     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10592     */
10593    protected float getBottomFadingEdgeStrength() {
10594        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10595                computeVerticalScrollRange() ? 1.0f : 0.0f;
10596    }
10597
10598    /**
10599     * Returns the strength, or intensity, of the left faded edge. The strength is
10600     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10601     * returns 0.0 or 1.0 but no value in between.
10602     *
10603     * Subclasses should override this method to provide a smoother fade transition
10604     * when scrolling occurs.
10605     *
10606     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10607     */
10608    protected float getLeftFadingEdgeStrength() {
10609        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10610    }
10611
10612    /**
10613     * Returns the strength, or intensity, of the right faded edge. The strength is
10614     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10615     * returns 0.0 or 1.0 but no value in between.
10616     *
10617     * Subclasses should override this method to provide a smoother fade transition
10618     * when scrolling occurs.
10619     *
10620     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10621     */
10622    protected float getRightFadingEdgeStrength() {
10623        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10624                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10625    }
10626
10627    /**
10628     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10629     * scrollbar is not drawn by default.</p>
10630     *
10631     * @return true if the horizontal scrollbar should be painted, false
10632     *         otherwise
10633     *
10634     * @see #setHorizontalScrollBarEnabled(boolean)
10635     */
10636    public boolean isHorizontalScrollBarEnabled() {
10637        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10638    }
10639
10640    /**
10641     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10642     * scrollbar is not drawn by default.</p>
10643     *
10644     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10645     *                                   be painted
10646     *
10647     * @see #isHorizontalScrollBarEnabled()
10648     */
10649    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10650        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10651            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10652            computeOpaqueFlags();
10653            resolvePadding();
10654        }
10655    }
10656
10657    /**
10658     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10659     * scrollbar is not drawn by default.</p>
10660     *
10661     * @return true if the vertical scrollbar should be painted, false
10662     *         otherwise
10663     *
10664     * @see #setVerticalScrollBarEnabled(boolean)
10665     */
10666    public boolean isVerticalScrollBarEnabled() {
10667        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10668    }
10669
10670    /**
10671     * <p>Define whether the vertical scrollbar should be drawn or not. The
10672     * scrollbar is not drawn by default.</p>
10673     *
10674     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10675     *                                 be painted
10676     *
10677     * @see #isVerticalScrollBarEnabled()
10678     */
10679    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10680        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10681            mViewFlags ^= SCROLLBARS_VERTICAL;
10682            computeOpaqueFlags();
10683            resolvePadding();
10684        }
10685    }
10686
10687    /**
10688     * @hide
10689     */
10690    protected void recomputePadding() {
10691        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10692    }
10693
10694    /**
10695     * Define whether scrollbars will fade when the view is not scrolling.
10696     *
10697     * @param fadeScrollbars wheter to enable fading
10698     *
10699     * @attr ref android.R.styleable#View_fadeScrollbars
10700     */
10701    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10702        initScrollCache();
10703        final ScrollabilityCache scrollabilityCache = mScrollCache;
10704        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10705        if (fadeScrollbars) {
10706            scrollabilityCache.state = ScrollabilityCache.OFF;
10707        } else {
10708            scrollabilityCache.state = ScrollabilityCache.ON;
10709        }
10710    }
10711
10712    /**
10713     *
10714     * Returns true if scrollbars will fade when this view is not scrolling
10715     *
10716     * @return true if scrollbar fading is enabled
10717     *
10718     * @attr ref android.R.styleable#View_fadeScrollbars
10719     */
10720    public boolean isScrollbarFadingEnabled() {
10721        return mScrollCache != null && mScrollCache.fadeScrollBars;
10722    }
10723
10724    /**
10725     *
10726     * Returns the delay before scrollbars fade.
10727     *
10728     * @return the delay before scrollbars fade
10729     *
10730     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10731     */
10732    public int getScrollBarDefaultDelayBeforeFade() {
10733        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10734                mScrollCache.scrollBarDefaultDelayBeforeFade;
10735    }
10736
10737    /**
10738     * Define the delay before scrollbars fade.
10739     *
10740     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10741     *
10742     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10743     */
10744    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10745        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10746    }
10747
10748    /**
10749     *
10750     * Returns the scrollbar fade duration.
10751     *
10752     * @return the scrollbar fade duration
10753     *
10754     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10755     */
10756    public int getScrollBarFadeDuration() {
10757        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10758                mScrollCache.scrollBarFadeDuration;
10759    }
10760
10761    /**
10762     * Define the scrollbar fade duration.
10763     *
10764     * @param scrollBarFadeDuration - the scrollbar fade duration
10765     *
10766     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10767     */
10768    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10769        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10770    }
10771
10772    /**
10773     *
10774     * Returns the scrollbar size.
10775     *
10776     * @return the scrollbar size
10777     *
10778     * @attr ref android.R.styleable#View_scrollbarSize
10779     */
10780    public int getScrollBarSize() {
10781        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10782                mScrollCache.scrollBarSize;
10783    }
10784
10785    /**
10786     * Define the scrollbar size.
10787     *
10788     * @param scrollBarSize - the scrollbar size
10789     *
10790     * @attr ref android.R.styleable#View_scrollbarSize
10791     */
10792    public void setScrollBarSize(int scrollBarSize) {
10793        getScrollCache().scrollBarSize = scrollBarSize;
10794    }
10795
10796    /**
10797     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10798     * inset. When inset, they add to the padding of the view. And the scrollbars
10799     * can be drawn inside the padding area or on the edge of the view. For example,
10800     * if a view has a background drawable and you want to draw the scrollbars
10801     * inside the padding specified by the drawable, you can use
10802     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10803     * appear at the edge of the view, ignoring the padding, then you can use
10804     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10805     * @param style the style of the scrollbars. Should be one of
10806     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10807     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10808     * @see #SCROLLBARS_INSIDE_OVERLAY
10809     * @see #SCROLLBARS_INSIDE_INSET
10810     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10811     * @see #SCROLLBARS_OUTSIDE_INSET
10812     *
10813     * @attr ref android.R.styleable#View_scrollbarStyle
10814     */
10815    public void setScrollBarStyle(int style) {
10816        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10817            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10818            computeOpaqueFlags();
10819            resolvePadding();
10820        }
10821    }
10822
10823    /**
10824     * <p>Returns the current scrollbar style.</p>
10825     * @return the current scrollbar style
10826     * @see #SCROLLBARS_INSIDE_OVERLAY
10827     * @see #SCROLLBARS_INSIDE_INSET
10828     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10829     * @see #SCROLLBARS_OUTSIDE_INSET
10830     *
10831     * @attr ref android.R.styleable#View_scrollbarStyle
10832     */
10833    @ViewDebug.ExportedProperty(mapping = {
10834            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10835            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10836            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10837            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10838    })
10839    public int getScrollBarStyle() {
10840        return mViewFlags & SCROLLBARS_STYLE_MASK;
10841    }
10842
10843    /**
10844     * <p>Compute the horizontal range that the horizontal scrollbar
10845     * represents.</p>
10846     *
10847     * <p>The range is expressed in arbitrary units that must be the same as the
10848     * units used by {@link #computeHorizontalScrollExtent()} and
10849     * {@link #computeHorizontalScrollOffset()}.</p>
10850     *
10851     * <p>The default range is the drawing width of this view.</p>
10852     *
10853     * @return the total horizontal range represented by the horizontal
10854     *         scrollbar
10855     *
10856     * @see #computeHorizontalScrollExtent()
10857     * @see #computeHorizontalScrollOffset()
10858     * @see android.widget.ScrollBarDrawable
10859     */
10860    protected int computeHorizontalScrollRange() {
10861        return getWidth();
10862    }
10863
10864    /**
10865     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10866     * within the horizontal range. This value is used to compute the position
10867     * of the thumb within the scrollbar's track.</p>
10868     *
10869     * <p>The range is expressed in arbitrary units that must be the same as the
10870     * units used by {@link #computeHorizontalScrollRange()} and
10871     * {@link #computeHorizontalScrollExtent()}.</p>
10872     *
10873     * <p>The default offset is the scroll offset of this view.</p>
10874     *
10875     * @return the horizontal offset of the scrollbar's thumb
10876     *
10877     * @see #computeHorizontalScrollRange()
10878     * @see #computeHorizontalScrollExtent()
10879     * @see android.widget.ScrollBarDrawable
10880     */
10881    protected int computeHorizontalScrollOffset() {
10882        return mScrollX;
10883    }
10884
10885    /**
10886     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10887     * within the horizontal range. This value is used to compute the length
10888     * of the thumb within the scrollbar's track.</p>
10889     *
10890     * <p>The range is expressed in arbitrary units that must be the same as the
10891     * units used by {@link #computeHorizontalScrollRange()} and
10892     * {@link #computeHorizontalScrollOffset()}.</p>
10893     *
10894     * <p>The default extent is the drawing width of this view.</p>
10895     *
10896     * @return the horizontal extent of the scrollbar's thumb
10897     *
10898     * @see #computeHorizontalScrollRange()
10899     * @see #computeHorizontalScrollOffset()
10900     * @see android.widget.ScrollBarDrawable
10901     */
10902    protected int computeHorizontalScrollExtent() {
10903        return getWidth();
10904    }
10905
10906    /**
10907     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10908     *
10909     * <p>The range is expressed in arbitrary units that must be the same as the
10910     * units used by {@link #computeVerticalScrollExtent()} and
10911     * {@link #computeVerticalScrollOffset()}.</p>
10912     *
10913     * @return the total vertical range represented by the vertical scrollbar
10914     *
10915     * <p>The default range is the drawing height of this view.</p>
10916     *
10917     * @see #computeVerticalScrollExtent()
10918     * @see #computeVerticalScrollOffset()
10919     * @see android.widget.ScrollBarDrawable
10920     */
10921    protected int computeVerticalScrollRange() {
10922        return getHeight();
10923    }
10924
10925    /**
10926     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10927     * within the horizontal range. This value is used to compute the position
10928     * of the thumb within the scrollbar's track.</p>
10929     *
10930     * <p>The range is expressed in arbitrary units that must be the same as the
10931     * units used by {@link #computeVerticalScrollRange()} and
10932     * {@link #computeVerticalScrollExtent()}.</p>
10933     *
10934     * <p>The default offset is the scroll offset of this view.</p>
10935     *
10936     * @return the vertical offset of the scrollbar's thumb
10937     *
10938     * @see #computeVerticalScrollRange()
10939     * @see #computeVerticalScrollExtent()
10940     * @see android.widget.ScrollBarDrawable
10941     */
10942    protected int computeVerticalScrollOffset() {
10943        return mScrollY;
10944    }
10945
10946    /**
10947     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10948     * within the vertical range. This value is used to compute the length
10949     * of the thumb within the scrollbar's track.</p>
10950     *
10951     * <p>The range is expressed in arbitrary units that must be the same as the
10952     * units used by {@link #computeVerticalScrollRange()} and
10953     * {@link #computeVerticalScrollOffset()}.</p>
10954     *
10955     * <p>The default extent is the drawing height of this view.</p>
10956     *
10957     * @return the vertical extent of the scrollbar's thumb
10958     *
10959     * @see #computeVerticalScrollRange()
10960     * @see #computeVerticalScrollOffset()
10961     * @see android.widget.ScrollBarDrawable
10962     */
10963    protected int computeVerticalScrollExtent() {
10964        return getHeight();
10965    }
10966
10967    /**
10968     * Check if this view can be scrolled horizontally in a certain direction.
10969     *
10970     * @param direction Negative to check scrolling left, positive to check scrolling right.
10971     * @return true if this view can be scrolled in the specified direction, false otherwise.
10972     */
10973    public boolean canScrollHorizontally(int direction) {
10974        final int offset = computeHorizontalScrollOffset();
10975        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10976        if (range == 0) return false;
10977        if (direction < 0) {
10978            return offset > 0;
10979        } else {
10980            return offset < range - 1;
10981        }
10982    }
10983
10984    /**
10985     * Check if this view can be scrolled vertically in a certain direction.
10986     *
10987     * @param direction Negative to check scrolling up, positive to check scrolling down.
10988     * @return true if this view can be scrolled in the specified direction, false otherwise.
10989     */
10990    public boolean canScrollVertically(int direction) {
10991        final int offset = computeVerticalScrollOffset();
10992        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10993        if (range == 0) return false;
10994        if (direction < 0) {
10995            return offset > 0;
10996        } else {
10997            return offset < range - 1;
10998        }
10999    }
11000
11001    /**
11002     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11003     * scrollbars are painted only if they have been awakened first.</p>
11004     *
11005     * @param canvas the canvas on which to draw the scrollbars
11006     *
11007     * @see #awakenScrollBars(int)
11008     */
11009    protected final void onDrawScrollBars(Canvas canvas) {
11010        // scrollbars are drawn only when the animation is running
11011        final ScrollabilityCache cache = mScrollCache;
11012        if (cache != null) {
11013
11014            int state = cache.state;
11015
11016            if (state == ScrollabilityCache.OFF) {
11017                return;
11018            }
11019
11020            boolean invalidate = false;
11021
11022            if (state == ScrollabilityCache.FADING) {
11023                // We're fading -- get our fade interpolation
11024                if (cache.interpolatorValues == null) {
11025                    cache.interpolatorValues = new float[1];
11026                }
11027
11028                float[] values = cache.interpolatorValues;
11029
11030                // Stops the animation if we're done
11031                if (cache.scrollBarInterpolator.timeToValues(values) ==
11032                        Interpolator.Result.FREEZE_END) {
11033                    cache.state = ScrollabilityCache.OFF;
11034                } else {
11035                    cache.scrollBar.setAlpha(Math.round(values[0]));
11036                }
11037
11038                // This will make the scroll bars inval themselves after
11039                // drawing. We only want this when we're fading so that
11040                // we prevent excessive redraws
11041                invalidate = true;
11042            } else {
11043                // We're just on -- but we may have been fading before so
11044                // reset alpha
11045                cache.scrollBar.setAlpha(255);
11046            }
11047
11048
11049            final int viewFlags = mViewFlags;
11050
11051            final boolean drawHorizontalScrollBar =
11052                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11053            final boolean drawVerticalScrollBar =
11054                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11055                && !isVerticalScrollBarHidden();
11056
11057            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11058                final int width = mRight - mLeft;
11059                final int height = mBottom - mTop;
11060
11061                final ScrollBarDrawable scrollBar = cache.scrollBar;
11062
11063                final int scrollX = mScrollX;
11064                final int scrollY = mScrollY;
11065                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11066
11067                int left, top, right, bottom;
11068
11069                if (drawHorizontalScrollBar) {
11070                    int size = scrollBar.getSize(false);
11071                    if (size <= 0) {
11072                        size = cache.scrollBarSize;
11073                    }
11074
11075                    scrollBar.setParameters(computeHorizontalScrollRange(),
11076                                            computeHorizontalScrollOffset(),
11077                                            computeHorizontalScrollExtent(), false);
11078                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11079                            getVerticalScrollbarWidth() : 0;
11080                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11081                    left = scrollX + (mPaddingLeft & inside);
11082                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11083                    bottom = top + size;
11084                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11085                    if (invalidate) {
11086                        invalidate(left, top, right, bottom);
11087                    }
11088                }
11089
11090                if (drawVerticalScrollBar) {
11091                    int size = scrollBar.getSize(true);
11092                    if (size <= 0) {
11093                        size = cache.scrollBarSize;
11094                    }
11095
11096                    scrollBar.setParameters(computeVerticalScrollRange(),
11097                                            computeVerticalScrollOffset(),
11098                                            computeVerticalScrollExtent(), true);
11099                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11100                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11101                        verticalScrollbarPosition = isLayoutRtl() ?
11102                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11103                    }
11104                    switch (verticalScrollbarPosition) {
11105                        default:
11106                        case SCROLLBAR_POSITION_RIGHT:
11107                            left = scrollX + width - size - (mUserPaddingRight & inside);
11108                            break;
11109                        case SCROLLBAR_POSITION_LEFT:
11110                            left = scrollX + (mUserPaddingLeft & inside);
11111                            break;
11112                    }
11113                    top = scrollY + (mPaddingTop & inside);
11114                    right = left + size;
11115                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11116                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11117                    if (invalidate) {
11118                        invalidate(left, top, right, bottom);
11119                    }
11120                }
11121            }
11122        }
11123    }
11124
11125    /**
11126     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11127     * FastScroller is visible.
11128     * @return whether to temporarily hide the vertical scrollbar
11129     * @hide
11130     */
11131    protected boolean isVerticalScrollBarHidden() {
11132        return false;
11133    }
11134
11135    /**
11136     * <p>Draw the horizontal scrollbar if
11137     * {@link #isHorizontalScrollBarEnabled()} 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 #isHorizontalScrollBarEnabled()
11143     * @see #computeHorizontalScrollRange()
11144     * @see #computeHorizontalScrollExtent()
11145     * @see #computeHorizontalScrollOffset()
11146     * @see android.widget.ScrollBarDrawable
11147     * @hide
11148     */
11149    protected void onDrawHorizontalScrollBar(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     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11157     * returns true.</p>
11158     *
11159     * @param canvas the canvas on which to draw the scrollbar
11160     * @param scrollBar the scrollbar's drawable
11161     *
11162     * @see #isVerticalScrollBarEnabled()
11163     * @see #computeVerticalScrollRange()
11164     * @see #computeVerticalScrollExtent()
11165     * @see #computeVerticalScrollOffset()
11166     * @see android.widget.ScrollBarDrawable
11167     * @hide
11168     */
11169    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11170            int l, int t, int r, int b) {
11171        scrollBar.setBounds(l, t, r, b);
11172        scrollBar.draw(canvas);
11173    }
11174
11175    /**
11176     * Implement this to do your drawing.
11177     *
11178     * @param canvas the canvas on which the background will be drawn
11179     */
11180    protected void onDraw(Canvas canvas) {
11181    }
11182
11183    /*
11184     * Caller is responsible for calling requestLayout if necessary.
11185     * (This allows addViewInLayout to not request a new layout.)
11186     */
11187    void assignParent(ViewParent parent) {
11188        if (mParent == null) {
11189            mParent = parent;
11190        } else if (parent == null) {
11191            mParent = null;
11192        } else {
11193            throw new RuntimeException("view " + this + " being added, but"
11194                    + " it already has a parent");
11195        }
11196    }
11197
11198    /**
11199     * This is called when the view is attached to a window.  At this point it
11200     * has a Surface and will start drawing.  Note that this function is
11201     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11202     * however it may be called any time before the first onDraw -- including
11203     * before or after {@link #onMeasure(int, int)}.
11204     *
11205     * @see #onDetachedFromWindow()
11206     */
11207    protected void onAttachedToWindow() {
11208        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11209            mParent.requestTransparentRegion(this);
11210        }
11211
11212        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11213            initialAwakenScrollBars();
11214            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11215        }
11216
11217        jumpDrawablesToCurrentState();
11218
11219        // Order is important here: LayoutDirection MUST be resolved before Padding
11220        // and TextDirection
11221        resolveLayoutDirection();
11222        resolvePadding();
11223        resolveTextDirection();
11224        resolveTextAlignment();
11225
11226        clearAccessibilityFocus();
11227        if (isFocused()) {
11228            InputMethodManager imm = InputMethodManager.peekInstance();
11229            imm.focusIn(this);
11230        }
11231
11232        if (mAttachInfo != null && mDisplayList != null) {
11233            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11234        }
11235    }
11236
11237    /**
11238     * @see #onScreenStateChanged(int)
11239     */
11240    void dispatchScreenStateChanged(int screenState) {
11241        onScreenStateChanged(screenState);
11242    }
11243
11244    /**
11245     * This method is called whenever the state of the screen this view is
11246     * attached to changes. A state change will usually occurs when the screen
11247     * turns on or off (whether it happens automatically or the user does it
11248     * manually.)
11249     *
11250     * @param screenState The new state of the screen. Can be either
11251     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11252     */
11253    public void onScreenStateChanged(int screenState) {
11254    }
11255
11256    /**
11257     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11258     */
11259    private boolean hasRtlSupport() {
11260        return mContext.getApplicationInfo().hasRtlSupport();
11261    }
11262
11263    /**
11264     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11265     * that the parent directionality can and will be resolved before its children.
11266     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11267     */
11268    public void resolveLayoutDirection() {
11269        // Clear any previous layout direction resolution
11270        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11271
11272        if (hasRtlSupport()) {
11273            // Set resolved depending on layout direction
11274            switch (getLayoutDirection()) {
11275                case LAYOUT_DIRECTION_INHERIT:
11276                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11277                    // later to get the correct resolved value
11278                    if (!canResolveLayoutDirection()) return;
11279
11280                    ViewGroup viewGroup = ((ViewGroup) mParent);
11281
11282                    // We cannot resolve yet on the parent too. LTR is by default and let the
11283                    // resolution happen again later
11284                    if (!viewGroup.canResolveLayoutDirection()) return;
11285
11286                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11287                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11288                    }
11289                    break;
11290                case LAYOUT_DIRECTION_RTL:
11291                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11292                    break;
11293                case LAYOUT_DIRECTION_LOCALE:
11294                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11295                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11296                    }
11297                    break;
11298                default:
11299                    // Nothing to do, LTR by default
11300            }
11301        }
11302
11303        // Set to resolved
11304        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11305        onResolvedLayoutDirectionChanged();
11306        // Resolve padding
11307        resolvePadding();
11308    }
11309
11310    /**
11311     * Called when layout direction has been resolved.
11312     *
11313     * The default implementation does nothing.
11314     */
11315    public void onResolvedLayoutDirectionChanged() {
11316    }
11317
11318    /**
11319     * Resolve padding depending on layout direction.
11320     */
11321    public void resolvePadding() {
11322        // If the user specified the absolute padding (either with android:padding or
11323        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11324        // use the default padding or the padding from the background drawable
11325        // (stored at this point in mPadding*)
11326        int resolvedLayoutDirection = getResolvedLayoutDirection();
11327        switch (resolvedLayoutDirection) {
11328            case LAYOUT_DIRECTION_RTL:
11329                // Start user padding override Right user padding. Otherwise, if Right user
11330                // padding is not defined, use the default Right padding. If Right user padding
11331                // is defined, just use it.
11332                if (mUserPaddingStart >= 0) {
11333                    mUserPaddingRight = mUserPaddingStart;
11334                } else if (mUserPaddingRight < 0) {
11335                    mUserPaddingRight = mPaddingRight;
11336                }
11337                if (mUserPaddingEnd >= 0) {
11338                    mUserPaddingLeft = mUserPaddingEnd;
11339                } else if (mUserPaddingLeft < 0) {
11340                    mUserPaddingLeft = mPaddingLeft;
11341                }
11342                break;
11343            case LAYOUT_DIRECTION_LTR:
11344            default:
11345                // Start user padding override Left user padding. Otherwise, if Left user
11346                // padding is not defined, use the default left padding. If Left user padding
11347                // is defined, just use it.
11348                if (mUserPaddingStart >= 0) {
11349                    mUserPaddingLeft = mUserPaddingStart;
11350                } else if (mUserPaddingLeft < 0) {
11351                    mUserPaddingLeft = mPaddingLeft;
11352                }
11353                if (mUserPaddingEnd >= 0) {
11354                    mUserPaddingRight = mUserPaddingEnd;
11355                } else if (mUserPaddingRight < 0) {
11356                    mUserPaddingRight = mPaddingRight;
11357                }
11358        }
11359
11360        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11361
11362        if(isPaddingRelative()) {
11363            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11364        } else {
11365            recomputePadding();
11366        }
11367        onPaddingChanged(resolvedLayoutDirection);
11368    }
11369
11370    /**
11371     * Resolve padding depending on the layout direction. Subclasses that care about
11372     * padding resolution should override this method. The default implementation does
11373     * nothing.
11374     *
11375     * @param layoutDirection the direction of the layout
11376     *
11377     * @see {@link #LAYOUT_DIRECTION_LTR}
11378     * @see {@link #LAYOUT_DIRECTION_RTL}
11379     */
11380    public void onPaddingChanged(int layoutDirection) {
11381    }
11382
11383    /**
11384     * Check if layout direction resolution can be done.
11385     *
11386     * @return true if layout direction resolution can be done otherwise return false.
11387     */
11388    public boolean canResolveLayoutDirection() {
11389        switch (getLayoutDirection()) {
11390            case LAYOUT_DIRECTION_INHERIT:
11391                return (mParent != null) && (mParent instanceof ViewGroup);
11392            default:
11393                return true;
11394        }
11395    }
11396
11397    /**
11398     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11399     * when reset is done.
11400     */
11401    public void resetResolvedLayoutDirection() {
11402        // Reset the current resolved bits
11403        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11404        onResolvedLayoutDirectionReset();
11405        // Reset also the text direction
11406        resetResolvedTextDirection();
11407    }
11408
11409    /**
11410     * Called during reset of resolved layout direction.
11411     *
11412     * Subclasses need to override this method to clear cached information that depends on the
11413     * resolved layout direction, or to inform child views that inherit their layout direction.
11414     *
11415     * The default implementation does nothing.
11416     */
11417    public void onResolvedLayoutDirectionReset() {
11418    }
11419
11420    /**
11421     * Check if a Locale uses an RTL script.
11422     *
11423     * @param locale Locale to check
11424     * @return true if the Locale uses an RTL script.
11425     */
11426    protected static boolean isLayoutDirectionRtl(Locale locale) {
11427        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11428    }
11429
11430    /**
11431     * This is called when the view is detached from a window.  At this point it
11432     * no longer has a surface for drawing.
11433     *
11434     * @see #onAttachedToWindow()
11435     */
11436    protected void onDetachedFromWindow() {
11437        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11438
11439        removeUnsetPressCallback();
11440        removeLongPressCallback();
11441        removePerformClickCallback();
11442        removeSendViewScrolledAccessibilityEventCallback();
11443
11444        destroyDrawingCache();
11445
11446        destroyLayer(false);
11447
11448        if (mAttachInfo != null) {
11449            if (mDisplayList != null) {
11450                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11451            }
11452            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11453        } else {
11454            // Should never happen
11455            clearDisplayList();
11456        }
11457
11458        mCurrentAnimation = null;
11459
11460        resetResolvedLayoutDirection();
11461        resetResolvedTextAlignment();
11462        resetAccessibilityStateChanged();
11463    }
11464
11465    /**
11466     * @return The number of times this view has been attached to a window
11467     */
11468    protected int getWindowAttachCount() {
11469        return mWindowAttachCount;
11470    }
11471
11472    /**
11473     * Retrieve a unique token identifying the window this view is attached to.
11474     * @return Return the window's token for use in
11475     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11476     */
11477    public IBinder getWindowToken() {
11478        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11479    }
11480
11481    /**
11482     * Retrieve a unique token identifying the top-level "real" window of
11483     * the window that this view is attached to.  That is, this is like
11484     * {@link #getWindowToken}, except if the window this view in is a panel
11485     * window (attached to another containing window), then the token of
11486     * the containing window is returned instead.
11487     *
11488     * @return Returns the associated window token, either
11489     * {@link #getWindowToken()} or the containing window's token.
11490     */
11491    public IBinder getApplicationWindowToken() {
11492        AttachInfo ai = mAttachInfo;
11493        if (ai != null) {
11494            IBinder appWindowToken = ai.mPanelParentWindowToken;
11495            if (appWindowToken == null) {
11496                appWindowToken = ai.mWindowToken;
11497            }
11498            return appWindowToken;
11499        }
11500        return null;
11501    }
11502
11503    /**
11504     * Retrieve private session object this view hierarchy is using to
11505     * communicate with the window manager.
11506     * @return the session object to communicate with the window manager
11507     */
11508    /*package*/ IWindowSession getWindowSession() {
11509        return mAttachInfo != null ? mAttachInfo.mSession : null;
11510    }
11511
11512    /**
11513     * @param info the {@link android.view.View.AttachInfo} to associated with
11514     *        this view
11515     */
11516    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11517        //System.out.println("Attached! " + this);
11518        mAttachInfo = info;
11519        mWindowAttachCount++;
11520        // We will need to evaluate the drawable state at least once.
11521        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11522        if (mFloatingTreeObserver != null) {
11523            info.mTreeObserver.merge(mFloatingTreeObserver);
11524            mFloatingTreeObserver = null;
11525        }
11526        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11527            mAttachInfo.mScrollContainers.add(this);
11528            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11529        }
11530        performCollectViewAttributes(mAttachInfo, visibility);
11531        onAttachedToWindow();
11532
11533        ListenerInfo li = mListenerInfo;
11534        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11535                li != null ? li.mOnAttachStateChangeListeners : null;
11536        if (listeners != null && listeners.size() > 0) {
11537            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11538            // perform the dispatching. The iterator is a safe guard against listeners that
11539            // could mutate the list by calling the various add/remove methods. This prevents
11540            // the array from being modified while we iterate it.
11541            for (OnAttachStateChangeListener listener : listeners) {
11542                listener.onViewAttachedToWindow(this);
11543            }
11544        }
11545
11546        int vis = info.mWindowVisibility;
11547        if (vis != GONE) {
11548            onWindowVisibilityChanged(vis);
11549        }
11550        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11551            // If nobody has evaluated the drawable state yet, then do it now.
11552            refreshDrawableState();
11553        }
11554    }
11555
11556    void dispatchDetachedFromWindow() {
11557        AttachInfo info = mAttachInfo;
11558        if (info != null) {
11559            int vis = info.mWindowVisibility;
11560            if (vis != GONE) {
11561                onWindowVisibilityChanged(GONE);
11562            }
11563        }
11564
11565        onDetachedFromWindow();
11566
11567        ListenerInfo li = mListenerInfo;
11568        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11569                li != null ? li.mOnAttachStateChangeListeners : null;
11570        if (listeners != null && listeners.size() > 0) {
11571            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11572            // perform the dispatching. The iterator is a safe guard against listeners that
11573            // could mutate the list by calling the various add/remove methods. This prevents
11574            // the array from being modified while we iterate it.
11575            for (OnAttachStateChangeListener listener : listeners) {
11576                listener.onViewDetachedFromWindow(this);
11577            }
11578        }
11579
11580        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11581            mAttachInfo.mScrollContainers.remove(this);
11582            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11583        }
11584
11585        mAttachInfo = null;
11586    }
11587
11588    /**
11589     * Store this view hierarchy's frozen state into the given container.
11590     *
11591     * @param container The SparseArray in which to save the view's state.
11592     *
11593     * @see #restoreHierarchyState(android.util.SparseArray)
11594     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11595     * @see #onSaveInstanceState()
11596     */
11597    public void saveHierarchyState(SparseArray<Parcelable> container) {
11598        dispatchSaveInstanceState(container);
11599    }
11600
11601    /**
11602     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11603     * this view and its children. May be overridden to modify how freezing happens to a
11604     * view's children; for example, some views may want to not store state for their children.
11605     *
11606     * @param container The SparseArray in which to save the view's state.
11607     *
11608     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11609     * @see #saveHierarchyState(android.util.SparseArray)
11610     * @see #onSaveInstanceState()
11611     */
11612    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11613        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11614            mPrivateFlags &= ~SAVE_STATE_CALLED;
11615            Parcelable state = onSaveInstanceState();
11616            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11617                throw new IllegalStateException(
11618                        "Derived class did not call super.onSaveInstanceState()");
11619            }
11620            if (state != null) {
11621                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11622                // + ": " + state);
11623                container.put(mID, state);
11624            }
11625        }
11626    }
11627
11628    /**
11629     * Hook allowing a view to generate a representation of its internal state
11630     * that can later be used to create a new instance with that same state.
11631     * This state should only contain information that is not persistent or can
11632     * not be reconstructed later. For example, you will never store your
11633     * current position on screen because that will be computed again when a
11634     * new instance of the view is placed in its view hierarchy.
11635     * <p>
11636     * Some examples of things you may store here: the current cursor position
11637     * in a text view (but usually not the text itself since that is stored in a
11638     * content provider or other persistent storage), the currently selected
11639     * item in a list view.
11640     *
11641     * @return Returns a Parcelable object containing the view's current dynamic
11642     *         state, or null if there is nothing interesting to save. The
11643     *         default implementation returns null.
11644     * @see #onRestoreInstanceState(android.os.Parcelable)
11645     * @see #saveHierarchyState(android.util.SparseArray)
11646     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11647     * @see #setSaveEnabled(boolean)
11648     */
11649    protected Parcelable onSaveInstanceState() {
11650        mPrivateFlags |= SAVE_STATE_CALLED;
11651        return BaseSavedState.EMPTY_STATE;
11652    }
11653
11654    /**
11655     * Restore this view hierarchy's frozen state from the given container.
11656     *
11657     * @param container The SparseArray which holds previously frozen states.
11658     *
11659     * @see #saveHierarchyState(android.util.SparseArray)
11660     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11661     * @see #onRestoreInstanceState(android.os.Parcelable)
11662     */
11663    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11664        dispatchRestoreInstanceState(container);
11665    }
11666
11667    /**
11668     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11669     * state for this view and its children. May be overridden to modify how restoring
11670     * happens to a view's children; for example, some views may want to not store state
11671     * for their children.
11672     *
11673     * @param container The SparseArray which holds previously saved state.
11674     *
11675     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11676     * @see #restoreHierarchyState(android.util.SparseArray)
11677     * @see #onRestoreInstanceState(android.os.Parcelable)
11678     */
11679    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11680        if (mID != NO_ID) {
11681            Parcelable state = container.get(mID);
11682            if (state != null) {
11683                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11684                // + ": " + state);
11685                mPrivateFlags &= ~SAVE_STATE_CALLED;
11686                onRestoreInstanceState(state);
11687                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11688                    throw new IllegalStateException(
11689                            "Derived class did not call super.onRestoreInstanceState()");
11690                }
11691            }
11692        }
11693    }
11694
11695    /**
11696     * Hook allowing a view to re-apply a representation of its internal state that had previously
11697     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11698     * null state.
11699     *
11700     * @param state The frozen state that had previously been returned by
11701     *        {@link #onSaveInstanceState}.
11702     *
11703     * @see #onSaveInstanceState()
11704     * @see #restoreHierarchyState(android.util.SparseArray)
11705     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11706     */
11707    protected void onRestoreInstanceState(Parcelable state) {
11708        mPrivateFlags |= SAVE_STATE_CALLED;
11709        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11710            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11711                    + "received " + state.getClass().toString() + " instead. This usually happens "
11712                    + "when two views of different type have the same id in the same hierarchy. "
11713                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11714                    + "other views do not use the same id.");
11715        }
11716    }
11717
11718    /**
11719     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11720     *
11721     * @return the drawing start time in milliseconds
11722     */
11723    public long getDrawingTime() {
11724        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11725    }
11726
11727    /**
11728     * <p>Enables or disables the duplication of the parent's state into this view. When
11729     * duplication is enabled, this view gets its drawable state from its parent rather
11730     * than from its own internal properties.</p>
11731     *
11732     * <p>Note: in the current implementation, setting this property to true after the
11733     * view was added to a ViewGroup might have no effect at all. This property should
11734     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11735     *
11736     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11737     * property is enabled, an exception will be thrown.</p>
11738     *
11739     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11740     * parent, these states should not be affected by this method.</p>
11741     *
11742     * @param enabled True to enable duplication of the parent's drawable state, false
11743     *                to disable it.
11744     *
11745     * @see #getDrawableState()
11746     * @see #isDuplicateParentStateEnabled()
11747     */
11748    public void setDuplicateParentStateEnabled(boolean enabled) {
11749        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11750    }
11751
11752    /**
11753     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11754     *
11755     * @return True if this view's drawable state is duplicated from the parent,
11756     *         false otherwise
11757     *
11758     * @see #getDrawableState()
11759     * @see #setDuplicateParentStateEnabled(boolean)
11760     */
11761    public boolean isDuplicateParentStateEnabled() {
11762        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11763    }
11764
11765    /**
11766     * <p>Specifies the type of layer backing this view. The layer can be
11767     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11768     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11769     *
11770     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11771     * instance that controls how the layer is composed on screen. The following
11772     * properties of the paint are taken into account when composing the layer:</p>
11773     * <ul>
11774     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11775     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11776     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11777     * </ul>
11778     *
11779     * <p>If this view has an alpha value set to < 1.0 by calling
11780     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11781     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11782     * equivalent to setting a hardware layer on this view and providing a paint with
11783     * the desired alpha value.<p>
11784     *
11785     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11786     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11787     * for more information on when and how to use layers.</p>
11788     *
11789     * @param layerType The ype of layer to use with this view, must be one of
11790     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11791     *        {@link #LAYER_TYPE_HARDWARE}
11792     * @param paint The paint used to compose the layer. This argument is optional
11793     *        and can be null. It is ignored when the layer type is
11794     *        {@link #LAYER_TYPE_NONE}
11795     *
11796     * @see #getLayerType()
11797     * @see #LAYER_TYPE_NONE
11798     * @see #LAYER_TYPE_SOFTWARE
11799     * @see #LAYER_TYPE_HARDWARE
11800     * @see #setAlpha(float)
11801     *
11802     * @attr ref android.R.styleable#View_layerType
11803     */
11804    public void setLayerType(int layerType, Paint paint) {
11805        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11806            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11807                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11808        }
11809
11810        if (layerType == mLayerType) {
11811            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11812                mLayerPaint = paint == null ? new Paint() : paint;
11813                invalidateParentCaches();
11814                invalidate(true);
11815            }
11816            return;
11817        }
11818
11819        // Destroy any previous software drawing cache if needed
11820        switch (mLayerType) {
11821            case LAYER_TYPE_HARDWARE:
11822                destroyLayer(false);
11823                // fall through - non-accelerated views may use software layer mechanism instead
11824            case LAYER_TYPE_SOFTWARE:
11825                destroyDrawingCache();
11826                break;
11827            default:
11828                break;
11829        }
11830
11831        mLayerType = layerType;
11832        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11833        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11834        mLocalDirtyRect = layerDisabled ? null : new Rect();
11835
11836        invalidateParentCaches();
11837        invalidate(true);
11838    }
11839
11840    /**
11841     * Indicates whether this view has a static layer. A view with layer type
11842     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11843     * dynamic.
11844     */
11845    boolean hasStaticLayer() {
11846        return true;
11847    }
11848
11849    /**
11850     * Indicates what type of layer is currently associated with this view. By default
11851     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11852     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11853     * for more information on the different types of layers.
11854     *
11855     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11856     *         {@link #LAYER_TYPE_HARDWARE}
11857     *
11858     * @see #setLayerType(int, android.graphics.Paint)
11859     * @see #buildLayer()
11860     * @see #LAYER_TYPE_NONE
11861     * @see #LAYER_TYPE_SOFTWARE
11862     * @see #LAYER_TYPE_HARDWARE
11863     */
11864    public int getLayerType() {
11865        return mLayerType;
11866    }
11867
11868    /**
11869     * Forces this view's layer to be created and this view to be rendered
11870     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11871     * invoking this method will have no effect.
11872     *
11873     * This method can for instance be used to render a view into its layer before
11874     * starting an animation. If this view is complex, rendering into the layer
11875     * before starting the animation will avoid skipping frames.
11876     *
11877     * @throws IllegalStateException If this view is not attached to a window
11878     *
11879     * @see #setLayerType(int, android.graphics.Paint)
11880     */
11881    public void buildLayer() {
11882        if (mLayerType == LAYER_TYPE_NONE) return;
11883
11884        if (mAttachInfo == null) {
11885            throw new IllegalStateException("This view must be attached to a window first");
11886        }
11887
11888        switch (mLayerType) {
11889            case LAYER_TYPE_HARDWARE:
11890                if (mAttachInfo.mHardwareRenderer != null &&
11891                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11892                        mAttachInfo.mHardwareRenderer.validate()) {
11893                    getHardwareLayer();
11894                }
11895                break;
11896            case LAYER_TYPE_SOFTWARE:
11897                buildDrawingCache(true);
11898                break;
11899        }
11900    }
11901
11902    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11903    void flushLayer() {
11904        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11905            mHardwareLayer.flush();
11906        }
11907    }
11908
11909    /**
11910     * <p>Returns a hardware layer that can be used to draw this view again
11911     * without executing its draw method.</p>
11912     *
11913     * @return A HardwareLayer ready to render, or null if an error occurred.
11914     */
11915    HardwareLayer getHardwareLayer() {
11916        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11917                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11918            return null;
11919        }
11920
11921        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11922
11923        final int width = mRight - mLeft;
11924        final int height = mBottom - mTop;
11925
11926        if (width == 0 || height == 0) {
11927            return null;
11928        }
11929
11930        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11931            if (mHardwareLayer == null) {
11932                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11933                        width, height, isOpaque());
11934                mLocalDirtyRect.set(0, 0, width, height);
11935            } else {
11936                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11937                    mHardwareLayer.resize(width, height);
11938                    mLocalDirtyRect.set(0, 0, width, height);
11939                }
11940
11941                // This should not be necessary but applications that change
11942                // the parameters of their background drawable without calling
11943                // this.setBackground(Drawable) can leave the view in a bad state
11944                // (for instance isOpaque() returns true, but the background is
11945                // not opaque.)
11946                computeOpaqueFlags();
11947
11948                final boolean opaque = isOpaque();
11949                if (mHardwareLayer.isOpaque() != opaque) {
11950                    mHardwareLayer.setOpaque(opaque);
11951                    mLocalDirtyRect.set(0, 0, width, height);
11952                }
11953            }
11954
11955            // The layer is not valid if the underlying GPU resources cannot be allocated
11956            if (!mHardwareLayer.isValid()) {
11957                return null;
11958            }
11959
11960            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11961            mLocalDirtyRect.setEmpty();
11962        }
11963
11964        return mHardwareLayer;
11965    }
11966
11967    /**
11968     * Destroys this View's hardware layer if possible.
11969     *
11970     * @return True if the layer was destroyed, false otherwise.
11971     *
11972     * @see #setLayerType(int, android.graphics.Paint)
11973     * @see #LAYER_TYPE_HARDWARE
11974     */
11975    boolean destroyLayer(boolean valid) {
11976        if (mHardwareLayer != null) {
11977            AttachInfo info = mAttachInfo;
11978            if (info != null && info.mHardwareRenderer != null &&
11979                    info.mHardwareRenderer.isEnabled() &&
11980                    (valid || info.mHardwareRenderer.validate())) {
11981                mHardwareLayer.destroy();
11982                mHardwareLayer = null;
11983
11984                invalidate(true);
11985                invalidateParentCaches();
11986            }
11987            return true;
11988        }
11989        return false;
11990    }
11991
11992    /**
11993     * Destroys all hardware rendering resources. This method is invoked
11994     * when the system needs to reclaim resources. Upon execution of this
11995     * method, you should free any OpenGL resources created by the view.
11996     *
11997     * Note: you <strong>must</strong> call
11998     * <code>super.destroyHardwareResources()</code> when overriding
11999     * this method.
12000     *
12001     * @hide
12002     */
12003    protected void destroyHardwareResources() {
12004        destroyLayer(true);
12005    }
12006
12007    /**
12008     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12009     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12010     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12011     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12012     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12013     * null.</p>
12014     *
12015     * <p>Enabling the drawing cache is similar to
12016     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12017     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12018     * drawing cache has no effect on rendering because the system uses a different mechanism
12019     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12020     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12021     * for information on how to enable software and hardware layers.</p>
12022     *
12023     * <p>This API can be used to manually generate
12024     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12025     * {@link #getDrawingCache()}.</p>
12026     *
12027     * @param enabled true to enable the drawing cache, false otherwise
12028     *
12029     * @see #isDrawingCacheEnabled()
12030     * @see #getDrawingCache()
12031     * @see #buildDrawingCache()
12032     * @see #setLayerType(int, android.graphics.Paint)
12033     */
12034    public void setDrawingCacheEnabled(boolean enabled) {
12035        mCachingFailed = false;
12036        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12037    }
12038
12039    /**
12040     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12041     *
12042     * @return true if the drawing cache is enabled
12043     *
12044     * @see #setDrawingCacheEnabled(boolean)
12045     * @see #getDrawingCache()
12046     */
12047    @ViewDebug.ExportedProperty(category = "drawing")
12048    public boolean isDrawingCacheEnabled() {
12049        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12050    }
12051
12052    /**
12053     * Debugging utility which recursively outputs the dirty state of a view and its
12054     * descendants.
12055     *
12056     * @hide
12057     */
12058    @SuppressWarnings({"UnusedDeclaration"})
12059    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12060        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12061                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12062                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12063                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12064        if (clear) {
12065            mPrivateFlags &= clearMask;
12066        }
12067        if (this instanceof ViewGroup) {
12068            ViewGroup parent = (ViewGroup) this;
12069            final int count = parent.getChildCount();
12070            for (int i = 0; i < count; i++) {
12071                final View child = parent.getChildAt(i);
12072                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12073            }
12074        }
12075    }
12076
12077    /**
12078     * This method is used by ViewGroup to cause its children to restore or recreate their
12079     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12080     * to recreate its own display list, which would happen if it went through the normal
12081     * draw/dispatchDraw mechanisms.
12082     *
12083     * @hide
12084     */
12085    protected void dispatchGetDisplayList() {}
12086
12087    /**
12088     * A view that is not attached or hardware accelerated cannot create a display list.
12089     * This method checks these conditions and returns the appropriate result.
12090     *
12091     * @return true if view has the ability to create a display list, false otherwise.
12092     *
12093     * @hide
12094     */
12095    public boolean canHaveDisplayList() {
12096        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12097    }
12098
12099    /**
12100     * @return The HardwareRenderer associated with that view or null if hardware rendering
12101     * is not supported or this this has not been attached to a window.
12102     *
12103     * @hide
12104     */
12105    public HardwareRenderer getHardwareRenderer() {
12106        if (mAttachInfo != null) {
12107            return mAttachInfo.mHardwareRenderer;
12108        }
12109        return null;
12110    }
12111
12112    /**
12113     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12114     * Otherwise, the same display list will be returned (after having been rendered into
12115     * along the way, depending on the invalidation state of the view).
12116     *
12117     * @param displayList The previous version of this displayList, could be null.
12118     * @param isLayer Whether the requester of the display list is a layer. If so,
12119     * the view will avoid creating a layer inside the resulting display list.
12120     * @return A new or reused DisplayList object.
12121     */
12122    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12123        if (!canHaveDisplayList()) {
12124            return null;
12125        }
12126
12127        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12128                displayList == null || !displayList.isValid() ||
12129                (!isLayer && mRecreateDisplayList))) {
12130            // Don't need to recreate the display list, just need to tell our
12131            // children to restore/recreate theirs
12132            if (displayList != null && displayList.isValid() &&
12133                    !isLayer && !mRecreateDisplayList) {
12134                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12135                mPrivateFlags &= ~DIRTY_MASK;
12136                dispatchGetDisplayList();
12137
12138                return displayList;
12139            }
12140
12141            if (!isLayer) {
12142                // If we got here, we're recreating it. Mark it as such to ensure that
12143                // we copy in child display lists into ours in drawChild()
12144                mRecreateDisplayList = true;
12145            }
12146            if (displayList == null) {
12147                final String name = getClass().getSimpleName();
12148                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12149                // If we're creating a new display list, make sure our parent gets invalidated
12150                // since they will need to recreate their display list to account for this
12151                // new child display list.
12152                invalidateParentCaches();
12153            }
12154
12155            boolean caching = false;
12156            final HardwareCanvas canvas = displayList.start();
12157            int width = mRight - mLeft;
12158            int height = mBottom - mTop;
12159
12160            try {
12161                canvas.setViewport(width, height);
12162                // The dirty rect should always be null for a display list
12163                canvas.onPreDraw(null);
12164                int layerType = getLayerType();
12165                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12166                    if (layerType == LAYER_TYPE_HARDWARE) {
12167                        final HardwareLayer layer = getHardwareLayer();
12168                        if (layer != null && layer.isValid()) {
12169                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12170                        } else {
12171                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12172                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12173                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12174                        }
12175                        caching = true;
12176                    } else {
12177                        buildDrawingCache(true);
12178                        Bitmap cache = getDrawingCache(true);
12179                        if (cache != null) {
12180                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12181                            caching = true;
12182                        }
12183                    }
12184                } else {
12185
12186                    computeScroll();
12187
12188                    canvas.translate(-mScrollX, -mScrollY);
12189                    if (!isLayer) {
12190                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12191                        mPrivateFlags &= ~DIRTY_MASK;
12192                    }
12193
12194                    // Fast path for layouts with no backgrounds
12195                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12196                        dispatchDraw(canvas);
12197                    } else {
12198                        draw(canvas);
12199                    }
12200                }
12201            } finally {
12202                canvas.onPostDraw();
12203
12204                displayList.end();
12205                displayList.setCaching(caching);
12206                if (isLayer) {
12207                    displayList.setLeftTopRightBottom(0, 0, width, height);
12208                } else {
12209                    setDisplayListProperties(displayList);
12210                }
12211            }
12212        } else if (!isLayer) {
12213            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12214            mPrivateFlags &= ~DIRTY_MASK;
12215        }
12216
12217        return displayList;
12218    }
12219
12220    /**
12221     * Get the DisplayList for the HardwareLayer
12222     *
12223     * @param layer The HardwareLayer whose DisplayList we want
12224     * @return A DisplayList fopr the specified HardwareLayer
12225     */
12226    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12227        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12228        layer.setDisplayList(displayList);
12229        return displayList;
12230    }
12231
12232
12233    /**
12234     * <p>Returns a display list that can be used to draw this view again
12235     * without executing its draw method.</p>
12236     *
12237     * @return A DisplayList ready to replay, or null if caching is not enabled.
12238     *
12239     * @hide
12240     */
12241    public DisplayList getDisplayList() {
12242        mDisplayList = getDisplayList(mDisplayList, false);
12243        return mDisplayList;
12244    }
12245
12246    private void clearDisplayList() {
12247        if (mDisplayList != null) {
12248            mDisplayList.invalidate();
12249            mDisplayList.clear();
12250        }
12251    }
12252
12253    /**
12254     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12255     *
12256     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12257     *
12258     * @see #getDrawingCache(boolean)
12259     */
12260    public Bitmap getDrawingCache() {
12261        return getDrawingCache(false);
12262    }
12263
12264    /**
12265     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12266     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12267     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12268     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12269     * request the drawing cache by calling this method and draw it on screen if the
12270     * returned bitmap is not null.</p>
12271     *
12272     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12273     * this method will create a bitmap of the same size as this view. Because this bitmap
12274     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12275     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12276     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12277     * size than the view. This implies that your application must be able to handle this
12278     * size.</p>
12279     *
12280     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12281     *        the current density of the screen when the application is in compatibility
12282     *        mode.
12283     *
12284     * @return A bitmap representing this view or null if cache is disabled.
12285     *
12286     * @see #setDrawingCacheEnabled(boolean)
12287     * @see #isDrawingCacheEnabled()
12288     * @see #buildDrawingCache(boolean)
12289     * @see #destroyDrawingCache()
12290     */
12291    public Bitmap getDrawingCache(boolean autoScale) {
12292        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12293            return null;
12294        }
12295        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12296            buildDrawingCache(autoScale);
12297        }
12298        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12299    }
12300
12301    /**
12302     * <p>Frees the resources used by the drawing cache. If you call
12303     * {@link #buildDrawingCache()} manually without calling
12304     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12305     * should cleanup the cache with this method afterwards.</p>
12306     *
12307     * @see #setDrawingCacheEnabled(boolean)
12308     * @see #buildDrawingCache()
12309     * @see #getDrawingCache()
12310     */
12311    public void destroyDrawingCache() {
12312        if (mDrawingCache != null) {
12313            mDrawingCache.recycle();
12314            mDrawingCache = null;
12315        }
12316        if (mUnscaledDrawingCache != null) {
12317            mUnscaledDrawingCache.recycle();
12318            mUnscaledDrawingCache = null;
12319        }
12320    }
12321
12322    /**
12323     * Setting a solid background color for the drawing cache's bitmaps will improve
12324     * performance and memory usage. Note, though that this should only be used if this
12325     * view will always be drawn on top of a solid color.
12326     *
12327     * @param color The background color to use for the drawing cache's bitmap
12328     *
12329     * @see #setDrawingCacheEnabled(boolean)
12330     * @see #buildDrawingCache()
12331     * @see #getDrawingCache()
12332     */
12333    public void setDrawingCacheBackgroundColor(int color) {
12334        if (color != mDrawingCacheBackgroundColor) {
12335            mDrawingCacheBackgroundColor = color;
12336            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12337        }
12338    }
12339
12340    /**
12341     * @see #setDrawingCacheBackgroundColor(int)
12342     *
12343     * @return The background color to used for the drawing cache's bitmap
12344     */
12345    public int getDrawingCacheBackgroundColor() {
12346        return mDrawingCacheBackgroundColor;
12347    }
12348
12349    /**
12350     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12351     *
12352     * @see #buildDrawingCache(boolean)
12353     */
12354    public void buildDrawingCache() {
12355        buildDrawingCache(false);
12356    }
12357
12358    /**
12359     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12360     *
12361     * <p>If you call {@link #buildDrawingCache()} manually without calling
12362     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12363     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12364     *
12365     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12366     * this method will create a bitmap of the same size as this view. Because this bitmap
12367     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12368     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12369     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12370     * size than the view. This implies that your application must be able to handle this
12371     * size.</p>
12372     *
12373     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12374     * you do not need the drawing cache bitmap, calling this method will increase memory
12375     * usage and cause the view to be rendered in software once, thus negatively impacting
12376     * performance.</p>
12377     *
12378     * @see #getDrawingCache()
12379     * @see #destroyDrawingCache()
12380     */
12381    public void buildDrawingCache(boolean autoScale) {
12382        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12383                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12384            mCachingFailed = false;
12385
12386            int width = mRight - mLeft;
12387            int height = mBottom - mTop;
12388
12389            final AttachInfo attachInfo = mAttachInfo;
12390            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12391
12392            if (autoScale && scalingRequired) {
12393                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12394                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12395            }
12396
12397            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12398            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12399            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12400
12401            if (width <= 0 || height <= 0 ||
12402                     // Projected bitmap size in bytes
12403                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12404                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12405                destroyDrawingCache();
12406                mCachingFailed = true;
12407                return;
12408            }
12409
12410            boolean clear = true;
12411            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12412
12413            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12414                Bitmap.Config quality;
12415                if (!opaque) {
12416                    // Never pick ARGB_4444 because it looks awful
12417                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12418                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12419                        case DRAWING_CACHE_QUALITY_AUTO:
12420                            quality = Bitmap.Config.ARGB_8888;
12421                            break;
12422                        case DRAWING_CACHE_QUALITY_LOW:
12423                            quality = Bitmap.Config.ARGB_8888;
12424                            break;
12425                        case DRAWING_CACHE_QUALITY_HIGH:
12426                            quality = Bitmap.Config.ARGB_8888;
12427                            break;
12428                        default:
12429                            quality = Bitmap.Config.ARGB_8888;
12430                            break;
12431                    }
12432                } else {
12433                    // Optimization for translucent windows
12434                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12435                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12436                }
12437
12438                // Try to cleanup memory
12439                if (bitmap != null) bitmap.recycle();
12440
12441                try {
12442                    bitmap = Bitmap.createBitmap(width, height, quality);
12443                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12444                    if (autoScale) {
12445                        mDrawingCache = bitmap;
12446                    } else {
12447                        mUnscaledDrawingCache = bitmap;
12448                    }
12449                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12450                } catch (OutOfMemoryError e) {
12451                    // If there is not enough memory to create the bitmap cache, just
12452                    // ignore the issue as bitmap caches are not required to draw the
12453                    // view hierarchy
12454                    if (autoScale) {
12455                        mDrawingCache = null;
12456                    } else {
12457                        mUnscaledDrawingCache = null;
12458                    }
12459                    mCachingFailed = true;
12460                    return;
12461                }
12462
12463                clear = drawingCacheBackgroundColor != 0;
12464            }
12465
12466            Canvas canvas;
12467            if (attachInfo != null) {
12468                canvas = attachInfo.mCanvas;
12469                if (canvas == null) {
12470                    canvas = new Canvas();
12471                }
12472                canvas.setBitmap(bitmap);
12473                // Temporarily clobber the cached Canvas in case one of our children
12474                // is also using a drawing cache. Without this, the children would
12475                // steal the canvas by attaching their own bitmap to it and bad, bad
12476                // thing would happen (invisible views, corrupted drawings, etc.)
12477                attachInfo.mCanvas = null;
12478            } else {
12479                // This case should hopefully never or seldom happen
12480                canvas = new Canvas(bitmap);
12481            }
12482
12483            if (clear) {
12484                bitmap.eraseColor(drawingCacheBackgroundColor);
12485            }
12486
12487            computeScroll();
12488            final int restoreCount = canvas.save();
12489
12490            if (autoScale && scalingRequired) {
12491                final float scale = attachInfo.mApplicationScale;
12492                canvas.scale(scale, scale);
12493            }
12494
12495            canvas.translate(-mScrollX, -mScrollY);
12496
12497            mPrivateFlags |= DRAWN;
12498            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12499                    mLayerType != LAYER_TYPE_NONE) {
12500                mPrivateFlags |= DRAWING_CACHE_VALID;
12501            }
12502
12503            // Fast path for layouts with no backgrounds
12504            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12505                mPrivateFlags &= ~DIRTY_MASK;
12506                dispatchDraw(canvas);
12507            } else {
12508                draw(canvas);
12509            }
12510
12511            canvas.restoreToCount(restoreCount);
12512            canvas.setBitmap(null);
12513
12514            if (attachInfo != null) {
12515                // Restore the cached Canvas for our siblings
12516                attachInfo.mCanvas = canvas;
12517            }
12518        }
12519    }
12520
12521    /**
12522     * Create a snapshot of the view into a bitmap.  We should probably make
12523     * some form of this public, but should think about the API.
12524     */
12525    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12526        int width = mRight - mLeft;
12527        int height = mBottom - mTop;
12528
12529        final AttachInfo attachInfo = mAttachInfo;
12530        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12531        width = (int) ((width * scale) + 0.5f);
12532        height = (int) ((height * scale) + 0.5f);
12533
12534        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12535        if (bitmap == null) {
12536            throw new OutOfMemoryError();
12537        }
12538
12539        Resources resources = getResources();
12540        if (resources != null) {
12541            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12542        }
12543
12544        Canvas canvas;
12545        if (attachInfo != null) {
12546            canvas = attachInfo.mCanvas;
12547            if (canvas == null) {
12548                canvas = new Canvas();
12549            }
12550            canvas.setBitmap(bitmap);
12551            // Temporarily clobber the cached Canvas in case one of our children
12552            // is also using a drawing cache. Without this, the children would
12553            // steal the canvas by attaching their own bitmap to it and bad, bad
12554            // things would happen (invisible views, corrupted drawings, etc.)
12555            attachInfo.mCanvas = null;
12556        } else {
12557            // This case should hopefully never or seldom happen
12558            canvas = new Canvas(bitmap);
12559        }
12560
12561        if ((backgroundColor & 0xff000000) != 0) {
12562            bitmap.eraseColor(backgroundColor);
12563        }
12564
12565        computeScroll();
12566        final int restoreCount = canvas.save();
12567        canvas.scale(scale, scale);
12568        canvas.translate(-mScrollX, -mScrollY);
12569
12570        // Temporarily remove the dirty mask
12571        int flags = mPrivateFlags;
12572        mPrivateFlags &= ~DIRTY_MASK;
12573
12574        // Fast path for layouts with no backgrounds
12575        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12576            dispatchDraw(canvas);
12577        } else {
12578            draw(canvas);
12579        }
12580
12581        mPrivateFlags = flags;
12582
12583        canvas.restoreToCount(restoreCount);
12584        canvas.setBitmap(null);
12585
12586        if (attachInfo != null) {
12587            // Restore the cached Canvas for our siblings
12588            attachInfo.mCanvas = canvas;
12589        }
12590
12591        return bitmap;
12592    }
12593
12594    /**
12595     * Indicates whether this View is currently in edit mode. A View is usually
12596     * in edit mode when displayed within a developer tool. For instance, if
12597     * this View is being drawn by a visual user interface builder, this method
12598     * should return true.
12599     *
12600     * Subclasses should check the return value of this method to provide
12601     * different behaviors if their normal behavior might interfere with the
12602     * host environment. For instance: the class spawns a thread in its
12603     * constructor, the drawing code relies on device-specific features, etc.
12604     *
12605     * This method is usually checked in the drawing code of custom widgets.
12606     *
12607     * @return True if this View is in edit mode, false otherwise.
12608     */
12609    public boolean isInEditMode() {
12610        return false;
12611    }
12612
12613    /**
12614     * If the View draws content inside its padding and enables fading edges,
12615     * it needs to support padding offsets. Padding offsets are added to the
12616     * fading edges to extend the length of the fade so that it covers pixels
12617     * drawn inside the padding.
12618     *
12619     * Subclasses of this class should override this method if they need
12620     * to draw content inside the padding.
12621     *
12622     * @return True if padding offset must be applied, false otherwise.
12623     *
12624     * @see #getLeftPaddingOffset()
12625     * @see #getRightPaddingOffset()
12626     * @see #getTopPaddingOffset()
12627     * @see #getBottomPaddingOffset()
12628     *
12629     * @since CURRENT
12630     */
12631    protected boolean isPaddingOffsetRequired() {
12632        return false;
12633    }
12634
12635    /**
12636     * Amount by which to extend the left fading region. Called only when
12637     * {@link #isPaddingOffsetRequired()} returns true.
12638     *
12639     * @return The left padding offset in pixels.
12640     *
12641     * @see #isPaddingOffsetRequired()
12642     *
12643     * @since CURRENT
12644     */
12645    protected int getLeftPaddingOffset() {
12646        return 0;
12647    }
12648
12649    /**
12650     * Amount by which to extend the right fading region. Called only when
12651     * {@link #isPaddingOffsetRequired()} returns true.
12652     *
12653     * @return The right padding offset in pixels.
12654     *
12655     * @see #isPaddingOffsetRequired()
12656     *
12657     * @since CURRENT
12658     */
12659    protected int getRightPaddingOffset() {
12660        return 0;
12661    }
12662
12663    /**
12664     * Amount by which to extend the top fading region. Called only when
12665     * {@link #isPaddingOffsetRequired()} returns true.
12666     *
12667     * @return The top padding offset in pixels.
12668     *
12669     * @see #isPaddingOffsetRequired()
12670     *
12671     * @since CURRENT
12672     */
12673    protected int getTopPaddingOffset() {
12674        return 0;
12675    }
12676
12677    /**
12678     * Amount by which to extend the bottom fading region. Called only when
12679     * {@link #isPaddingOffsetRequired()} returns true.
12680     *
12681     * @return The bottom padding offset in pixels.
12682     *
12683     * @see #isPaddingOffsetRequired()
12684     *
12685     * @since CURRENT
12686     */
12687    protected int getBottomPaddingOffset() {
12688        return 0;
12689    }
12690
12691    /**
12692     * @hide
12693     * @param offsetRequired
12694     */
12695    protected int getFadeTop(boolean offsetRequired) {
12696        int top = mPaddingTop;
12697        if (offsetRequired) top += getTopPaddingOffset();
12698        return top;
12699    }
12700
12701    /**
12702     * @hide
12703     * @param offsetRequired
12704     */
12705    protected int getFadeHeight(boolean offsetRequired) {
12706        int padding = mPaddingTop;
12707        if (offsetRequired) padding += getTopPaddingOffset();
12708        return mBottom - mTop - mPaddingBottom - padding;
12709    }
12710
12711    /**
12712     * <p>Indicates whether this view is attached to a hardware accelerated
12713     * window or not.</p>
12714     *
12715     * <p>Even if this method returns true, it does not mean that every call
12716     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12717     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12718     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12719     * window is hardware accelerated,
12720     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12721     * return false, and this method will return true.</p>
12722     *
12723     * @return True if the view is attached to a window and the window is
12724     *         hardware accelerated; false in any other case.
12725     */
12726    public boolean isHardwareAccelerated() {
12727        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12728    }
12729
12730    /**
12731     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12732     * case of an active Animation being run on the view.
12733     */
12734    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12735            Animation a, boolean scalingRequired) {
12736        Transformation invalidationTransform;
12737        final int flags = parent.mGroupFlags;
12738        final boolean initialized = a.isInitialized();
12739        if (!initialized) {
12740            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12741            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12742            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12743            onAnimationStart();
12744        }
12745
12746        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12747        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12748            if (parent.mInvalidationTransformation == null) {
12749                parent.mInvalidationTransformation = new Transformation();
12750            }
12751            invalidationTransform = parent.mInvalidationTransformation;
12752            a.getTransformation(drawingTime, invalidationTransform, 1f);
12753        } else {
12754            invalidationTransform = parent.mChildTransformation;
12755        }
12756
12757        if (more) {
12758            if (!a.willChangeBounds()) {
12759                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12760                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12761                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12762                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12763                    // The child need to draw an animation, potentially offscreen, so
12764                    // make sure we do not cancel invalidate requests
12765                    parent.mPrivateFlags |= DRAW_ANIMATION;
12766                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12767                }
12768            } else {
12769                if (parent.mInvalidateRegion == null) {
12770                    parent.mInvalidateRegion = new RectF();
12771                }
12772                final RectF region = parent.mInvalidateRegion;
12773                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12774                        invalidationTransform);
12775
12776                // The child need to draw an animation, potentially offscreen, so
12777                // make sure we do not cancel invalidate requests
12778                parent.mPrivateFlags |= DRAW_ANIMATION;
12779
12780                final int left = mLeft + (int) region.left;
12781                final int top = mTop + (int) region.top;
12782                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12783                        top + (int) (region.height() + .5f));
12784            }
12785        }
12786        return more;
12787    }
12788
12789    /**
12790     * This method is called by getDisplayList() when a display list is created or re-rendered.
12791     * It sets or resets the current value of all properties on that display list (resetting is
12792     * necessary when a display list is being re-created, because we need to make sure that
12793     * previously-set transform values
12794     */
12795    void setDisplayListProperties(DisplayList displayList) {
12796        if (displayList != null) {
12797            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12798            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12799            if (mParent instanceof ViewGroup) {
12800                displayList.setClipChildren(
12801                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12802            }
12803            float alpha = 1;
12804            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12805                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12806                ViewGroup parentVG = (ViewGroup) mParent;
12807                final boolean hasTransform =
12808                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12809                if (hasTransform) {
12810                    Transformation transform = parentVG.mChildTransformation;
12811                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12812                    if (transformType != Transformation.TYPE_IDENTITY) {
12813                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12814                            alpha = transform.getAlpha();
12815                        }
12816                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12817                            displayList.setStaticMatrix(transform.getMatrix());
12818                        }
12819                    }
12820                }
12821            }
12822            if (mTransformationInfo != null) {
12823                alpha *= mTransformationInfo.mAlpha;
12824                if (alpha < 1) {
12825                    final int multipliedAlpha = (int) (255 * alpha);
12826                    if (onSetAlpha(multipliedAlpha)) {
12827                        alpha = 1;
12828                    }
12829                }
12830                displayList.setTransformationInfo(alpha,
12831                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12832                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12833                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12834                        mTransformationInfo.mScaleY);
12835                if (mTransformationInfo.mCamera == null) {
12836                    mTransformationInfo.mCamera = new Camera();
12837                    mTransformationInfo.matrix3D = new Matrix();
12838                }
12839                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12840                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12841                    displayList.setPivotX(getPivotX());
12842                    displayList.setPivotY(getPivotY());
12843                }
12844            } else if (alpha < 1) {
12845                displayList.setAlpha(alpha);
12846            }
12847        }
12848    }
12849
12850    /**
12851     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12852     * This draw() method is an implementation detail and is not intended to be overridden or
12853     * to be called from anywhere else other than ViewGroup.drawChild().
12854     */
12855    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12856        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12857        boolean more = false;
12858        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12859        final int flags = parent.mGroupFlags;
12860
12861        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12862            parent.mChildTransformation.clear();
12863            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12864        }
12865
12866        Transformation transformToApply = null;
12867        boolean concatMatrix = false;
12868
12869        boolean scalingRequired = false;
12870        boolean caching;
12871        int layerType = getLayerType();
12872
12873        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12874        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12875                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12876            caching = true;
12877            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12878            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12879        } else {
12880            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12881        }
12882
12883        final Animation a = getAnimation();
12884        if (a != null) {
12885            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12886            concatMatrix = a.willChangeTransformationMatrix();
12887            if (concatMatrix) {
12888                mPrivateFlags3 |= VIEW_IS_ANIMATING_TRANSFORM;
12889            }
12890            transformToApply = parent.mChildTransformation;
12891        } else {
12892            if ((mPrivateFlags3 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12893                    mDisplayList != null) {
12894                // No longer animating: clear out old animation matrix
12895                mDisplayList.setAnimationMatrix(null);
12896                mPrivateFlags3 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12897            }
12898            if (!useDisplayListProperties &&
12899                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12900                final boolean hasTransform =
12901                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12902                if (hasTransform) {
12903                    final int transformType = parent.mChildTransformation.getTransformationType();
12904                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12905                            parent.mChildTransformation : null;
12906                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12907                }
12908            }
12909        }
12910
12911        concatMatrix |= !childHasIdentityMatrix;
12912
12913        // Sets the flag as early as possible to allow draw() implementations
12914        // to call invalidate() successfully when doing animations
12915        mPrivateFlags |= DRAWN;
12916
12917        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12918                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12919            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12920            return more;
12921        }
12922        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12923
12924        if (hardwareAccelerated) {
12925            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12926            // retain the flag's value temporarily in the mRecreateDisplayList flag
12927            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12928            mPrivateFlags &= ~INVALIDATED;
12929        }
12930
12931        computeScroll();
12932
12933        final int sx = mScrollX;
12934        final int sy = mScrollY;
12935
12936        DisplayList displayList = null;
12937        Bitmap cache = null;
12938        boolean hasDisplayList = false;
12939        if (caching) {
12940            if (!hardwareAccelerated) {
12941                if (layerType != LAYER_TYPE_NONE) {
12942                    layerType = LAYER_TYPE_SOFTWARE;
12943                    buildDrawingCache(true);
12944                }
12945                cache = getDrawingCache(true);
12946            } else {
12947                switch (layerType) {
12948                    case LAYER_TYPE_SOFTWARE:
12949                        if (useDisplayListProperties) {
12950                            hasDisplayList = canHaveDisplayList();
12951                        } else {
12952                            buildDrawingCache(true);
12953                            cache = getDrawingCache(true);
12954                        }
12955                        break;
12956                    case LAYER_TYPE_HARDWARE:
12957                        if (useDisplayListProperties) {
12958                            hasDisplayList = canHaveDisplayList();
12959                        }
12960                        break;
12961                    case LAYER_TYPE_NONE:
12962                        // Delay getting the display list until animation-driven alpha values are
12963                        // set up and possibly passed on to the view
12964                        hasDisplayList = canHaveDisplayList();
12965                        break;
12966                }
12967            }
12968        }
12969        useDisplayListProperties &= hasDisplayList;
12970        if (useDisplayListProperties) {
12971            displayList = getDisplayList();
12972            if (!displayList.isValid()) {
12973                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12974                // to getDisplayList(), the display list will be marked invalid and we should not
12975                // try to use it again.
12976                displayList = null;
12977                hasDisplayList = false;
12978                useDisplayListProperties = false;
12979            }
12980        }
12981
12982        final boolean hasNoCache = cache == null || hasDisplayList;
12983        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12984                layerType != LAYER_TYPE_HARDWARE;
12985
12986        int restoreTo = -1;
12987        if (!useDisplayListProperties || transformToApply != null) {
12988            restoreTo = canvas.save();
12989        }
12990        if (offsetForScroll) {
12991            canvas.translate(mLeft - sx, mTop - sy);
12992        } else {
12993            if (!useDisplayListProperties) {
12994                canvas.translate(mLeft, mTop);
12995            }
12996            if (scalingRequired) {
12997                if (useDisplayListProperties) {
12998                    // TODO: Might not need this if we put everything inside the DL
12999                    restoreTo = canvas.save();
13000                }
13001                // mAttachInfo cannot be null, otherwise scalingRequired == false
13002                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13003                canvas.scale(scale, scale);
13004            }
13005        }
13006
13007        float alpha = useDisplayListProperties ? 1 : getAlpha();
13008        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13009                (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
13010            if (transformToApply != null || !childHasIdentityMatrix) {
13011                int transX = 0;
13012                int transY = 0;
13013
13014                if (offsetForScroll) {
13015                    transX = -sx;
13016                    transY = -sy;
13017                }
13018
13019                if (transformToApply != null) {
13020                    if (concatMatrix) {
13021                        if (useDisplayListProperties) {
13022                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13023                        } else {
13024                            // Undo the scroll translation, apply the transformation matrix,
13025                            // then redo the scroll translate to get the correct result.
13026                            canvas.translate(-transX, -transY);
13027                            canvas.concat(transformToApply.getMatrix());
13028                            canvas.translate(transX, transY);
13029                        }
13030                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13031                    }
13032
13033                    float transformAlpha = transformToApply.getAlpha();
13034                    if (transformAlpha < 1) {
13035                        alpha *= transformAlpha;
13036                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13037                    }
13038                }
13039
13040                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13041                    canvas.translate(-transX, -transY);
13042                    canvas.concat(getMatrix());
13043                    canvas.translate(transX, transY);
13044                }
13045            }
13046
13047            // Deal with alpha if it is or used to be <1
13048            if (alpha < 1 ||
13049                    (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
13050                if (alpha < 1) {
13051                    mPrivateFlags3 |= VIEW_IS_ANIMATING_ALPHA;
13052                } else {
13053                    mPrivateFlags3 &= ~VIEW_IS_ANIMATING_ALPHA;
13054                }
13055                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13056                if (hasNoCache) {
13057                    final int multipliedAlpha = (int) (255 * alpha);
13058                    if (!onSetAlpha(multipliedAlpha)) {
13059                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13060                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13061                                layerType != LAYER_TYPE_NONE) {
13062                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13063                        }
13064                        if (useDisplayListProperties) {
13065                            displayList.setAlpha(alpha * getAlpha());
13066                        } else  if (layerType == LAYER_TYPE_NONE) {
13067                            final int scrollX = hasDisplayList ? 0 : sx;
13068                            final int scrollY = hasDisplayList ? 0 : sy;
13069                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13070                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13071                        }
13072                    } else {
13073                        // Alpha is handled by the child directly, clobber the layer's alpha
13074                        mPrivateFlags |= ALPHA_SET;
13075                    }
13076                }
13077            }
13078        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13079            onSetAlpha(255);
13080            mPrivateFlags &= ~ALPHA_SET;
13081        }
13082
13083        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13084                !useDisplayListProperties) {
13085            if (offsetForScroll) {
13086                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13087            } else {
13088                if (!scalingRequired || cache == null) {
13089                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13090                } else {
13091                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13092                }
13093            }
13094        }
13095
13096        if (!useDisplayListProperties && hasDisplayList) {
13097            displayList = getDisplayList();
13098            if (!displayList.isValid()) {
13099                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13100                // to getDisplayList(), the display list will be marked invalid and we should not
13101                // try to use it again.
13102                displayList = null;
13103                hasDisplayList = false;
13104            }
13105        }
13106
13107        if (hasNoCache) {
13108            boolean layerRendered = false;
13109            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13110                final HardwareLayer layer = getHardwareLayer();
13111                if (layer != null && layer.isValid()) {
13112                    mLayerPaint.setAlpha((int) (alpha * 255));
13113                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13114                    layerRendered = true;
13115                } else {
13116                    final int scrollX = hasDisplayList ? 0 : sx;
13117                    final int scrollY = hasDisplayList ? 0 : sy;
13118                    canvas.saveLayer(scrollX, scrollY,
13119                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13120                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13121                }
13122            }
13123
13124            if (!layerRendered) {
13125                if (!hasDisplayList) {
13126                    // Fast path for layouts with no backgrounds
13127                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13128                        mPrivateFlags &= ~DIRTY_MASK;
13129                        dispatchDraw(canvas);
13130                    } else {
13131                        draw(canvas);
13132                    }
13133                } else {
13134                    mPrivateFlags &= ~DIRTY_MASK;
13135                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13136                }
13137            }
13138        } else if (cache != null) {
13139            mPrivateFlags &= ~DIRTY_MASK;
13140            Paint cachePaint;
13141
13142            if (layerType == LAYER_TYPE_NONE) {
13143                cachePaint = parent.mCachePaint;
13144                if (cachePaint == null) {
13145                    cachePaint = new Paint();
13146                    cachePaint.setDither(false);
13147                    parent.mCachePaint = cachePaint;
13148                }
13149                if (alpha < 1) {
13150                    cachePaint.setAlpha((int) (alpha * 255));
13151                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13152                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13153                    cachePaint.setAlpha(255);
13154                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13155                }
13156            } else {
13157                cachePaint = mLayerPaint;
13158                cachePaint.setAlpha((int) (alpha * 255));
13159            }
13160            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13161        }
13162
13163        if (restoreTo >= 0) {
13164            canvas.restoreToCount(restoreTo);
13165        }
13166
13167        if (a != null && !more) {
13168            if (!hardwareAccelerated && !a.getFillAfter()) {
13169                onSetAlpha(255);
13170            }
13171            parent.finishAnimatingView(this, a);
13172        }
13173
13174        if (more && hardwareAccelerated) {
13175            // invalidation is the trigger to recreate display lists, so if we're using
13176            // display lists to render, force an invalidate to allow the animation to
13177            // continue drawing another frame
13178            parent.invalidate(true);
13179            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13180                // alpha animations should cause the child to recreate its display list
13181                invalidate(true);
13182            }
13183        }
13184
13185        mRecreateDisplayList = false;
13186
13187        return more;
13188    }
13189
13190    /**
13191     * Manually render this view (and all of its children) to the given Canvas.
13192     * The view must have already done a full layout before this function is
13193     * called.  When implementing a view, implement
13194     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13195     * If you do need to override this method, call the superclass version.
13196     *
13197     * @param canvas The Canvas to which the View is rendered.
13198     */
13199    public void draw(Canvas canvas) {
13200        final int privateFlags = mPrivateFlags;
13201        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13202                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13203        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13204
13205        /*
13206         * Draw traversal performs several drawing steps which must be executed
13207         * in the appropriate order:
13208         *
13209         *      1. Draw the background
13210         *      2. If necessary, save the canvas' layers to prepare for fading
13211         *      3. Draw view's content
13212         *      4. Draw children
13213         *      5. If necessary, draw the fading edges and restore layers
13214         *      6. Draw decorations (scrollbars for instance)
13215         */
13216
13217        // Step 1, draw the background, if needed
13218        int saveCount;
13219
13220        if (!dirtyOpaque) {
13221            final Drawable background = mBackground;
13222            if (background != null) {
13223                final int scrollX = mScrollX;
13224                final int scrollY = mScrollY;
13225
13226                if (mBackgroundSizeChanged) {
13227                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13228                    mBackgroundSizeChanged = false;
13229                }
13230
13231                if ((scrollX | scrollY) == 0) {
13232                    background.draw(canvas);
13233                } else {
13234                    canvas.translate(scrollX, scrollY);
13235                    background.draw(canvas);
13236                    canvas.translate(-scrollX, -scrollY);
13237                }
13238            }
13239        }
13240
13241        // skip step 2 & 5 if possible (common case)
13242        final int viewFlags = mViewFlags;
13243        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13244        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13245        if (!verticalEdges && !horizontalEdges) {
13246            // Step 3, draw the content
13247            if (!dirtyOpaque) onDraw(canvas);
13248
13249            // Step 4, draw the children
13250            dispatchDraw(canvas);
13251
13252            // Step 6, draw decorations (scrollbars)
13253            onDrawScrollBars(canvas);
13254
13255            // we're done...
13256            return;
13257        }
13258
13259        /*
13260         * Here we do the full fledged routine...
13261         * (this is an uncommon case where speed matters less,
13262         * this is why we repeat some of the tests that have been
13263         * done above)
13264         */
13265
13266        boolean drawTop = false;
13267        boolean drawBottom = false;
13268        boolean drawLeft = false;
13269        boolean drawRight = false;
13270
13271        float topFadeStrength = 0.0f;
13272        float bottomFadeStrength = 0.0f;
13273        float leftFadeStrength = 0.0f;
13274        float rightFadeStrength = 0.0f;
13275
13276        // Step 2, save the canvas' layers
13277        int paddingLeft = mPaddingLeft;
13278
13279        final boolean offsetRequired = isPaddingOffsetRequired();
13280        if (offsetRequired) {
13281            paddingLeft += getLeftPaddingOffset();
13282        }
13283
13284        int left = mScrollX + paddingLeft;
13285        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13286        int top = mScrollY + getFadeTop(offsetRequired);
13287        int bottom = top + getFadeHeight(offsetRequired);
13288
13289        if (offsetRequired) {
13290            right += getRightPaddingOffset();
13291            bottom += getBottomPaddingOffset();
13292        }
13293
13294        final ScrollabilityCache scrollabilityCache = mScrollCache;
13295        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13296        int length = (int) fadeHeight;
13297
13298        // clip the fade length if top and bottom fades overlap
13299        // overlapping fades produce odd-looking artifacts
13300        if (verticalEdges && (top + length > bottom - length)) {
13301            length = (bottom - top) / 2;
13302        }
13303
13304        // also clip horizontal fades if necessary
13305        if (horizontalEdges && (left + length > right - length)) {
13306            length = (right - left) / 2;
13307        }
13308
13309        if (verticalEdges) {
13310            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13311            drawTop = topFadeStrength * fadeHeight > 1.0f;
13312            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13313            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13314        }
13315
13316        if (horizontalEdges) {
13317            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13318            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13319            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13320            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13321        }
13322
13323        saveCount = canvas.getSaveCount();
13324
13325        int solidColor = getSolidColor();
13326        if (solidColor == 0) {
13327            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13328
13329            if (drawTop) {
13330                canvas.saveLayer(left, top, right, top + length, null, flags);
13331            }
13332
13333            if (drawBottom) {
13334                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13335            }
13336
13337            if (drawLeft) {
13338                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13339            }
13340
13341            if (drawRight) {
13342                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13343            }
13344        } else {
13345            scrollabilityCache.setFadeColor(solidColor);
13346        }
13347
13348        // Step 3, draw the content
13349        if (!dirtyOpaque) onDraw(canvas);
13350
13351        // Step 4, draw the children
13352        dispatchDraw(canvas);
13353
13354        // Step 5, draw the fade effect and restore layers
13355        final Paint p = scrollabilityCache.paint;
13356        final Matrix matrix = scrollabilityCache.matrix;
13357        final Shader fade = scrollabilityCache.shader;
13358
13359        if (drawTop) {
13360            matrix.setScale(1, fadeHeight * topFadeStrength);
13361            matrix.postTranslate(left, top);
13362            fade.setLocalMatrix(matrix);
13363            canvas.drawRect(left, top, right, top + length, p);
13364        }
13365
13366        if (drawBottom) {
13367            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13368            matrix.postRotate(180);
13369            matrix.postTranslate(left, bottom);
13370            fade.setLocalMatrix(matrix);
13371            canvas.drawRect(left, bottom - length, right, bottom, p);
13372        }
13373
13374        if (drawLeft) {
13375            matrix.setScale(1, fadeHeight * leftFadeStrength);
13376            matrix.postRotate(-90);
13377            matrix.postTranslate(left, top);
13378            fade.setLocalMatrix(matrix);
13379            canvas.drawRect(left, top, left + length, bottom, p);
13380        }
13381
13382        if (drawRight) {
13383            matrix.setScale(1, fadeHeight * rightFadeStrength);
13384            matrix.postRotate(90);
13385            matrix.postTranslate(right, top);
13386            fade.setLocalMatrix(matrix);
13387            canvas.drawRect(right - length, top, right, bottom, p);
13388        }
13389
13390        canvas.restoreToCount(saveCount);
13391
13392        // Step 6, draw decorations (scrollbars)
13393        onDrawScrollBars(canvas);
13394    }
13395
13396    /**
13397     * Override this if your view is known to always be drawn on top of a solid color background,
13398     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13399     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13400     * should be set to 0xFF.
13401     *
13402     * @see #setVerticalFadingEdgeEnabled(boolean)
13403     * @see #setHorizontalFadingEdgeEnabled(boolean)
13404     *
13405     * @return The known solid color background for this view, or 0 if the color may vary
13406     */
13407    @ViewDebug.ExportedProperty(category = "drawing")
13408    public int getSolidColor() {
13409        return 0;
13410    }
13411
13412    /**
13413     * Build a human readable string representation of the specified view flags.
13414     *
13415     * @param flags the view flags to convert to a string
13416     * @return a String representing the supplied flags
13417     */
13418    private static String printFlags(int flags) {
13419        String output = "";
13420        int numFlags = 0;
13421        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13422            output += "TAKES_FOCUS";
13423            numFlags++;
13424        }
13425
13426        switch (flags & VISIBILITY_MASK) {
13427        case INVISIBLE:
13428            if (numFlags > 0) {
13429                output += " ";
13430            }
13431            output += "INVISIBLE";
13432            // USELESS HERE numFlags++;
13433            break;
13434        case GONE:
13435            if (numFlags > 0) {
13436                output += " ";
13437            }
13438            output += "GONE";
13439            // USELESS HERE numFlags++;
13440            break;
13441        default:
13442            break;
13443        }
13444        return output;
13445    }
13446
13447    /**
13448     * Build a human readable string representation of the specified private
13449     * view flags.
13450     *
13451     * @param privateFlags the private view flags to convert to a string
13452     * @return a String representing the supplied flags
13453     */
13454    private static String printPrivateFlags(int privateFlags) {
13455        String output = "";
13456        int numFlags = 0;
13457
13458        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13459            output += "WANTS_FOCUS";
13460            numFlags++;
13461        }
13462
13463        if ((privateFlags & FOCUSED) == FOCUSED) {
13464            if (numFlags > 0) {
13465                output += " ";
13466            }
13467            output += "FOCUSED";
13468            numFlags++;
13469        }
13470
13471        if ((privateFlags & SELECTED) == SELECTED) {
13472            if (numFlags > 0) {
13473                output += " ";
13474            }
13475            output += "SELECTED";
13476            numFlags++;
13477        }
13478
13479        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13480            if (numFlags > 0) {
13481                output += " ";
13482            }
13483            output += "IS_ROOT_NAMESPACE";
13484            numFlags++;
13485        }
13486
13487        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13488            if (numFlags > 0) {
13489                output += " ";
13490            }
13491            output += "HAS_BOUNDS";
13492            numFlags++;
13493        }
13494
13495        if ((privateFlags & DRAWN) == DRAWN) {
13496            if (numFlags > 0) {
13497                output += " ";
13498            }
13499            output += "DRAWN";
13500            // USELESS HERE numFlags++;
13501        }
13502        return output;
13503    }
13504
13505    /**
13506     * <p>Indicates whether or not this view's layout will be requested during
13507     * the next hierarchy layout pass.</p>
13508     *
13509     * @return true if the layout will be forced during next layout pass
13510     */
13511    public boolean isLayoutRequested() {
13512        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13513    }
13514
13515    /**
13516     * Assign a size and position to a view and all of its
13517     * descendants
13518     *
13519     * <p>This is the second phase of the layout mechanism.
13520     * (The first is measuring). In this phase, each parent calls
13521     * layout on all of its children to position them.
13522     * This is typically done using the child measurements
13523     * that were stored in the measure pass().</p>
13524     *
13525     * <p>Derived classes should not override this method.
13526     * Derived classes with children should override
13527     * onLayout. In that method, they should
13528     * call layout on each of their children.</p>
13529     *
13530     * @param l Left position, relative to parent
13531     * @param t Top position, relative to parent
13532     * @param r Right position, relative to parent
13533     * @param b Bottom position, relative to parent
13534     */
13535    @SuppressWarnings({"unchecked"})
13536    public void layout(int l, int t, int r, int b) {
13537        int oldL = mLeft;
13538        int oldT = mTop;
13539        int oldB = mBottom;
13540        int oldR = mRight;
13541        boolean changed = setFrame(l, t, r, b);
13542        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13543            onLayout(changed, l, t, r, b);
13544            mPrivateFlags &= ~LAYOUT_REQUIRED;
13545
13546            ListenerInfo li = mListenerInfo;
13547            if (li != null && li.mOnLayoutChangeListeners != null) {
13548                ArrayList<OnLayoutChangeListener> listenersCopy =
13549                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13550                int numListeners = listenersCopy.size();
13551                for (int i = 0; i < numListeners; ++i) {
13552                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13553                }
13554            }
13555        }
13556        mPrivateFlags &= ~FORCE_LAYOUT;
13557    }
13558
13559    /**
13560     * Called from layout when this view should
13561     * assign a size and position to each of its children.
13562     *
13563     * Derived classes with children should override
13564     * this method and call layout on each of
13565     * their children.
13566     * @param changed This is a new size or position for this view
13567     * @param left Left position, relative to parent
13568     * @param top Top position, relative to parent
13569     * @param right Right position, relative to parent
13570     * @param bottom Bottom position, relative to parent
13571     */
13572    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13573    }
13574
13575    /**
13576     * Assign a size and position to this view.
13577     *
13578     * This is called from layout.
13579     *
13580     * @param left Left position, relative to parent
13581     * @param top Top position, relative to parent
13582     * @param right Right position, relative to parent
13583     * @param bottom Bottom position, relative to parent
13584     * @return true if the new size and position are different than the
13585     *         previous ones
13586     * {@hide}
13587     */
13588    protected boolean setFrame(int left, int top, int right, int bottom) {
13589        boolean changed = false;
13590
13591        if (DBG) {
13592            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13593                    + right + "," + bottom + ")");
13594        }
13595
13596        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13597            changed = true;
13598
13599            // Remember our drawn bit
13600            int drawn = mPrivateFlags & DRAWN;
13601
13602            int oldWidth = mRight - mLeft;
13603            int oldHeight = mBottom - mTop;
13604            int newWidth = right - left;
13605            int newHeight = bottom - top;
13606            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13607
13608            // Invalidate our old position
13609            invalidate(sizeChanged);
13610
13611            mLeft = left;
13612            mTop = top;
13613            mRight = right;
13614            mBottom = bottom;
13615            if (mDisplayList != null) {
13616                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13617            }
13618
13619            mPrivateFlags |= HAS_BOUNDS;
13620
13621
13622            if (sizeChanged) {
13623                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13624                    // A change in dimension means an auto-centered pivot point changes, too
13625                    if (mTransformationInfo != null) {
13626                        mTransformationInfo.mMatrixDirty = true;
13627                    }
13628                }
13629                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13630            }
13631
13632            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13633                // If we are visible, force the DRAWN bit to on so that
13634                // this invalidate will go through (at least to our parent).
13635                // This is because someone may have invalidated this view
13636                // before this call to setFrame came in, thereby clearing
13637                // the DRAWN bit.
13638                mPrivateFlags |= DRAWN;
13639                invalidate(sizeChanged);
13640                // parent display list may need to be recreated based on a change in the bounds
13641                // of any child
13642                invalidateParentCaches();
13643            }
13644
13645            // Reset drawn bit to original value (invalidate turns it off)
13646            mPrivateFlags |= drawn;
13647
13648            mBackgroundSizeChanged = true;
13649        }
13650        return changed;
13651    }
13652
13653    /**
13654     * Finalize inflating a view from XML.  This is called as the last phase
13655     * of inflation, after all child views have been added.
13656     *
13657     * <p>Even if the subclass overrides onFinishInflate, they should always be
13658     * sure to call the super method, so that we get called.
13659     */
13660    protected void onFinishInflate() {
13661    }
13662
13663    /**
13664     * Returns the resources associated with this view.
13665     *
13666     * @return Resources object.
13667     */
13668    public Resources getResources() {
13669        return mResources;
13670    }
13671
13672    /**
13673     * Invalidates the specified Drawable.
13674     *
13675     * @param drawable the drawable to invalidate
13676     */
13677    public void invalidateDrawable(Drawable drawable) {
13678        if (verifyDrawable(drawable)) {
13679            final Rect dirty = drawable.getBounds();
13680            final int scrollX = mScrollX;
13681            final int scrollY = mScrollY;
13682
13683            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13684                    dirty.right + scrollX, dirty.bottom + scrollY);
13685        }
13686    }
13687
13688    /**
13689     * Schedules an action on a drawable to occur at a specified time.
13690     *
13691     * @param who the recipient of the action
13692     * @param what the action to run on the drawable
13693     * @param when the time at which the action must occur. Uses the
13694     *        {@link SystemClock#uptimeMillis} timebase.
13695     */
13696    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13697        if (verifyDrawable(who) && what != null) {
13698            final long delay = when - SystemClock.uptimeMillis();
13699            if (mAttachInfo != null) {
13700                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13701                        Choreographer.CALLBACK_ANIMATION, what, who,
13702                        Choreographer.subtractFrameDelay(delay));
13703            } else {
13704                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13705            }
13706        }
13707    }
13708
13709    /**
13710     * Cancels a scheduled action on a drawable.
13711     *
13712     * @param who the recipient of the action
13713     * @param what the action to cancel
13714     */
13715    public void unscheduleDrawable(Drawable who, Runnable what) {
13716        if (verifyDrawable(who) && what != null) {
13717            if (mAttachInfo != null) {
13718                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13719                        Choreographer.CALLBACK_ANIMATION, what, who);
13720            } else {
13721                ViewRootImpl.getRunQueue().removeCallbacks(what);
13722            }
13723        }
13724    }
13725
13726    /**
13727     * Unschedule any events associated with the given Drawable.  This can be
13728     * used when selecting a new Drawable into a view, so that the previous
13729     * one is completely unscheduled.
13730     *
13731     * @param who The Drawable to unschedule.
13732     *
13733     * @see #drawableStateChanged
13734     */
13735    public void unscheduleDrawable(Drawable who) {
13736        if (mAttachInfo != null && who != null) {
13737            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13738                    Choreographer.CALLBACK_ANIMATION, null, who);
13739        }
13740    }
13741
13742    /**
13743     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
13744     * that the View directionality can and will be resolved before its Drawables.
13745     *
13746     * Will call {@link View#onResolveDrawables} when resolution is done.
13747     */
13748    public void resolveDrawables() {
13749        if (mBackground != null) {
13750            mBackground.setLayoutDirection(getResolvedLayoutDirection());
13751        }
13752        onResolveDrawables(getResolvedLayoutDirection());
13753    }
13754
13755    /**
13756     * Called when layout direction has been resolved.
13757     *
13758     * The default implementation does nothing.
13759     *
13760     * @param layoutDirection The resolved layout direction.
13761     *
13762     * @see {@link #LAYOUT_DIRECTION_LTR}
13763     * @see {@link #LAYOUT_DIRECTION_RTL}
13764     */
13765    public void onResolveDrawables(int layoutDirection) {
13766    }
13767
13768    /**
13769     * If your view subclass is displaying its own Drawable objects, it should
13770     * override this function and return true for any Drawable it is
13771     * displaying.  This allows animations for those drawables to be
13772     * scheduled.
13773     *
13774     * <p>Be sure to call through to the super class when overriding this
13775     * function.
13776     *
13777     * @param who The Drawable to verify.  Return true if it is one you are
13778     *            displaying, else return the result of calling through to the
13779     *            super class.
13780     *
13781     * @return boolean If true than the Drawable is being displayed in the
13782     *         view; else false and it is not allowed to animate.
13783     *
13784     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13785     * @see #drawableStateChanged()
13786     */
13787    protected boolean verifyDrawable(Drawable who) {
13788        return who == mBackground;
13789    }
13790
13791    /**
13792     * This function is called whenever the state of the view changes in such
13793     * a way that it impacts the state of drawables being shown.
13794     *
13795     * <p>Be sure to call through to the superclass when overriding this
13796     * function.
13797     *
13798     * @see Drawable#setState(int[])
13799     */
13800    protected void drawableStateChanged() {
13801        Drawable d = mBackground;
13802        if (d != null && d.isStateful()) {
13803            d.setState(getDrawableState());
13804        }
13805    }
13806
13807    /**
13808     * Call this to force a view to update its drawable state. This will cause
13809     * drawableStateChanged to be called on this view. Views that are interested
13810     * in the new state should call getDrawableState.
13811     *
13812     * @see #drawableStateChanged
13813     * @see #getDrawableState
13814     */
13815    public void refreshDrawableState() {
13816        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13817        drawableStateChanged();
13818
13819        ViewParent parent = mParent;
13820        if (parent != null) {
13821            parent.childDrawableStateChanged(this);
13822        }
13823    }
13824
13825    /**
13826     * Return an array of resource IDs of the drawable states representing the
13827     * current state of the view.
13828     *
13829     * @return The current drawable state
13830     *
13831     * @see Drawable#setState(int[])
13832     * @see #drawableStateChanged()
13833     * @see #onCreateDrawableState(int)
13834     */
13835    public final int[] getDrawableState() {
13836        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13837            return mDrawableState;
13838        } else {
13839            mDrawableState = onCreateDrawableState(0);
13840            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13841            return mDrawableState;
13842        }
13843    }
13844
13845    /**
13846     * Generate the new {@link android.graphics.drawable.Drawable} state for
13847     * this view. This is called by the view
13848     * system when the cached Drawable state is determined to be invalid.  To
13849     * retrieve the current state, you should use {@link #getDrawableState}.
13850     *
13851     * @param extraSpace if non-zero, this is the number of extra entries you
13852     * would like in the returned array in which you can place your own
13853     * states.
13854     *
13855     * @return Returns an array holding the current {@link Drawable} state of
13856     * the view.
13857     *
13858     * @see #mergeDrawableStates(int[], int[])
13859     */
13860    protected int[] onCreateDrawableState(int extraSpace) {
13861        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13862                mParent instanceof View) {
13863            return ((View) mParent).onCreateDrawableState(extraSpace);
13864        }
13865
13866        int[] drawableState;
13867
13868        int privateFlags = mPrivateFlags;
13869
13870        int viewStateIndex = 0;
13871        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13872        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13873        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13874        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13875        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13876        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13877        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13878                HardwareRenderer.isAvailable()) {
13879            // This is set if HW acceleration is requested, even if the current
13880            // process doesn't allow it.  This is just to allow app preview
13881            // windows to better match their app.
13882            viewStateIndex |= VIEW_STATE_ACCELERATED;
13883        }
13884        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13885
13886        final int privateFlags2 = mPrivateFlags2;
13887        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13888        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13889
13890        drawableState = VIEW_STATE_SETS[viewStateIndex];
13891
13892        //noinspection ConstantIfStatement
13893        if (false) {
13894            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13895            Log.i("View", toString()
13896                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13897                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13898                    + " fo=" + hasFocus()
13899                    + " sl=" + ((privateFlags & SELECTED) != 0)
13900                    + " wf=" + hasWindowFocus()
13901                    + ": " + Arrays.toString(drawableState));
13902        }
13903
13904        if (extraSpace == 0) {
13905            return drawableState;
13906        }
13907
13908        final int[] fullState;
13909        if (drawableState != null) {
13910            fullState = new int[drawableState.length + extraSpace];
13911            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13912        } else {
13913            fullState = new int[extraSpace];
13914        }
13915
13916        return fullState;
13917    }
13918
13919    /**
13920     * Merge your own state values in <var>additionalState</var> into the base
13921     * state values <var>baseState</var> that were returned by
13922     * {@link #onCreateDrawableState(int)}.
13923     *
13924     * @param baseState The base state values returned by
13925     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13926     * own additional state values.
13927     *
13928     * @param additionalState The additional state values you would like
13929     * added to <var>baseState</var>; this array is not modified.
13930     *
13931     * @return As a convenience, the <var>baseState</var> array you originally
13932     * passed into the function is returned.
13933     *
13934     * @see #onCreateDrawableState(int)
13935     */
13936    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13937        final int N = baseState.length;
13938        int i = N - 1;
13939        while (i >= 0 && baseState[i] == 0) {
13940            i--;
13941        }
13942        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13943        return baseState;
13944    }
13945
13946    /**
13947     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13948     * on all Drawable objects associated with this view.
13949     */
13950    public void jumpDrawablesToCurrentState() {
13951        if (mBackground != null) {
13952            mBackground.jumpToCurrentState();
13953        }
13954    }
13955
13956    /**
13957     * Sets the background color for this view.
13958     * @param color the color of the background
13959     */
13960    @RemotableViewMethod
13961    public void setBackgroundColor(int color) {
13962        if (mBackground instanceof ColorDrawable) {
13963            ((ColorDrawable) mBackground).setColor(color);
13964            computeOpaqueFlags();
13965        } else {
13966            setBackground(new ColorDrawable(color));
13967        }
13968    }
13969
13970    /**
13971     * Set the background to a given resource. The resource should refer to
13972     * a Drawable object or 0 to remove the background.
13973     * @param resid The identifier of the resource.
13974     *
13975     * @attr ref android.R.styleable#View_background
13976     */
13977    @RemotableViewMethod
13978    public void setBackgroundResource(int resid) {
13979        if (resid != 0 && resid == mBackgroundResource) {
13980            return;
13981        }
13982
13983        Drawable d= null;
13984        if (resid != 0) {
13985            d = mResources.getDrawable(resid);
13986        }
13987        setBackground(d);
13988
13989        mBackgroundResource = resid;
13990    }
13991
13992    /**
13993     * Set the background to a given Drawable, or remove the background. If the
13994     * background has padding, this View's padding is set to the background's
13995     * padding. However, when a background is removed, this View's padding isn't
13996     * touched. If setting the padding is desired, please use
13997     * {@link #setPadding(int, int, int, int)}.
13998     *
13999     * @param background The Drawable to use as the background, or null to remove the
14000     *        background
14001     */
14002    public void setBackground(Drawable background) {
14003        //noinspection deprecation
14004        setBackgroundDrawable(background);
14005    }
14006
14007    /**
14008     * @deprecated use {@link #setBackground(Drawable)} instead
14009     */
14010    @Deprecated
14011    public void setBackgroundDrawable(Drawable background) {
14012        computeOpaqueFlags();
14013
14014        if (background == mBackground) {
14015            return;
14016        }
14017
14018        boolean requestLayout = false;
14019
14020        mBackgroundResource = 0;
14021
14022        /*
14023         * Regardless of whether we're setting a new background or not, we want
14024         * to clear the previous drawable.
14025         */
14026        if (mBackground != null) {
14027            mBackground.setCallback(null);
14028            unscheduleDrawable(mBackground);
14029        }
14030
14031        if (background != null) {
14032            Rect padding = sThreadLocal.get();
14033            if (padding == null) {
14034                padding = new Rect();
14035                sThreadLocal.set(padding);
14036            }
14037            background.setLayoutDirection(getResolvedLayoutDirection());
14038            if (background.getPadding(padding)) {
14039                switch (background.getLayoutDirection()) {
14040                    case LAYOUT_DIRECTION_RTL:
14041                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14042                        break;
14043                    case LAYOUT_DIRECTION_LTR:
14044                    default:
14045                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14046                }
14047            }
14048
14049            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14050            // if it has a different minimum size, we should layout again
14051            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14052                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14053                requestLayout = true;
14054            }
14055
14056            background.setCallback(this);
14057            if (background.isStateful()) {
14058                background.setState(getDrawableState());
14059            }
14060            background.setVisible(getVisibility() == VISIBLE, false);
14061            mBackground = background;
14062
14063            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14064                mPrivateFlags &= ~SKIP_DRAW;
14065                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14066                requestLayout = true;
14067            }
14068        } else {
14069            /* Remove the background */
14070            mBackground = null;
14071
14072            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14073                /*
14074                 * This view ONLY drew the background before and we're removing
14075                 * the background, so now it won't draw anything
14076                 * (hence we SKIP_DRAW)
14077                 */
14078                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14079                mPrivateFlags |= SKIP_DRAW;
14080            }
14081
14082            /*
14083             * When the background is set, we try to apply its padding to this
14084             * View. When the background is removed, we don't touch this View's
14085             * padding. This is noted in the Javadocs. Hence, we don't need to
14086             * requestLayout(), the invalidate() below is sufficient.
14087             */
14088
14089            // The old background's minimum size could have affected this
14090            // View's layout, so let's requestLayout
14091            requestLayout = true;
14092        }
14093
14094        computeOpaqueFlags();
14095
14096        if (requestLayout) {
14097            requestLayout();
14098        }
14099
14100        mBackgroundSizeChanged = true;
14101        invalidate(true);
14102    }
14103
14104    /**
14105     * Gets the background drawable
14106     *
14107     * @return The drawable used as the background for this view, if any.
14108     *
14109     * @see #setBackground(Drawable)
14110     *
14111     * @attr ref android.R.styleable#View_background
14112     */
14113    public Drawable getBackground() {
14114        return mBackground;
14115    }
14116
14117    /**
14118     * Sets the padding. The view may add on the space required to display
14119     * the scrollbars, depending on the style and visibility of the scrollbars.
14120     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14121     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14122     * from the values set in this call.
14123     *
14124     * @attr ref android.R.styleable#View_padding
14125     * @attr ref android.R.styleable#View_paddingBottom
14126     * @attr ref android.R.styleable#View_paddingLeft
14127     * @attr ref android.R.styleable#View_paddingRight
14128     * @attr ref android.R.styleable#View_paddingTop
14129     * @param left the left padding in pixels
14130     * @param top the top padding in pixels
14131     * @param right the right padding in pixels
14132     * @param bottom the bottom padding in pixels
14133     */
14134    public void setPadding(int left, int top, int right, int bottom) {
14135        mUserPaddingStart = -1;
14136        mUserPaddingEnd = -1;
14137        mUserPaddingRelative = false;
14138
14139        internalSetPadding(left, top, right, bottom);
14140    }
14141
14142    private void internalSetPadding(int left, int top, int right, int bottom) {
14143        mUserPaddingLeft = left;
14144        mUserPaddingRight = right;
14145        mUserPaddingBottom = bottom;
14146
14147        final int viewFlags = mViewFlags;
14148        boolean changed = false;
14149
14150        // Common case is there are no scroll bars.
14151        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14152            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14153                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14154                        ? 0 : getVerticalScrollbarWidth();
14155                switch (mVerticalScrollbarPosition) {
14156                    case SCROLLBAR_POSITION_DEFAULT:
14157                        if (isLayoutRtl()) {
14158                            left += offset;
14159                        } else {
14160                            right += offset;
14161                        }
14162                        break;
14163                    case SCROLLBAR_POSITION_RIGHT:
14164                        right += offset;
14165                        break;
14166                    case SCROLLBAR_POSITION_LEFT:
14167                        left += offset;
14168                        break;
14169                }
14170            }
14171            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14172                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14173                        ? 0 : getHorizontalScrollbarHeight();
14174            }
14175        }
14176
14177        if (mPaddingLeft != left) {
14178            changed = true;
14179            mPaddingLeft = left;
14180        }
14181        if (mPaddingTop != top) {
14182            changed = true;
14183            mPaddingTop = top;
14184        }
14185        if (mPaddingRight != right) {
14186            changed = true;
14187            mPaddingRight = right;
14188        }
14189        if (mPaddingBottom != bottom) {
14190            changed = true;
14191            mPaddingBottom = bottom;
14192        }
14193
14194        if (changed) {
14195            requestLayout();
14196        }
14197    }
14198
14199    /**
14200     * Sets the relative padding. The view may add on the space required to display
14201     * the scrollbars, depending on the style and visibility of the scrollbars.
14202     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14203     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14204     * from the values set in this call.
14205     *
14206     * @attr ref android.R.styleable#View_padding
14207     * @attr ref android.R.styleable#View_paddingBottom
14208     * @attr ref android.R.styleable#View_paddingStart
14209     * @attr ref android.R.styleable#View_paddingEnd
14210     * @attr ref android.R.styleable#View_paddingTop
14211     * @param start the start padding in pixels
14212     * @param top the top padding in pixels
14213     * @param end the end padding in pixels
14214     * @param bottom the bottom padding in pixels
14215     */
14216    public void setPaddingRelative(int start, int top, int end, int bottom) {
14217        mUserPaddingStart = start;
14218        mUserPaddingEnd = end;
14219        mUserPaddingRelative = true;
14220
14221        switch(getResolvedLayoutDirection()) {
14222            case LAYOUT_DIRECTION_RTL:
14223                internalSetPadding(end, top, start, bottom);
14224                break;
14225            case LAYOUT_DIRECTION_LTR:
14226            default:
14227                internalSetPadding(start, top, end, bottom);
14228        }
14229    }
14230
14231    /**
14232     * Returns the top padding of this view.
14233     *
14234     * @return the top padding in pixels
14235     */
14236    public int getPaddingTop() {
14237        return mPaddingTop;
14238    }
14239
14240    /**
14241     * Returns the bottom padding of this view. If there are inset and enabled
14242     * scrollbars, this value may include the space required to display the
14243     * scrollbars as well.
14244     *
14245     * @return the bottom padding in pixels
14246     */
14247    public int getPaddingBottom() {
14248        return mPaddingBottom;
14249    }
14250
14251    /**
14252     * Returns the left padding of this view. If there are inset and enabled
14253     * scrollbars, this value may include the space required to display the
14254     * scrollbars as well.
14255     *
14256     * @return the left padding in pixels
14257     */
14258    public int getPaddingLeft() {
14259        return mPaddingLeft;
14260    }
14261
14262    /**
14263     * Returns the start padding of this view depending on its resolved layout direction.
14264     * If there are inset and enabled scrollbars, this value may include the space
14265     * required to display the scrollbars as well.
14266     *
14267     * @return the start padding in pixels
14268     */
14269    public int getPaddingStart() {
14270        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14271                mPaddingRight : mPaddingLeft;
14272    }
14273
14274    /**
14275     * Returns the right padding of this view. If there are inset and enabled
14276     * scrollbars, this value may include the space required to display the
14277     * scrollbars as well.
14278     *
14279     * @return the right padding in pixels
14280     */
14281    public int getPaddingRight() {
14282        return mPaddingRight;
14283    }
14284
14285    /**
14286     * Returns the end padding of this view depending on its resolved layout direction.
14287     * If there are inset and enabled scrollbars, this value may include the space
14288     * required to display the scrollbars as well.
14289     *
14290     * @return the end padding in pixels
14291     */
14292    public int getPaddingEnd() {
14293        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14294                mPaddingLeft : mPaddingRight;
14295    }
14296
14297    /**
14298     * Return if the padding as been set thru relative values
14299     * {@link #setPaddingRelative(int, int, int, int)} or thru
14300     * @attr ref android.R.styleable#View_paddingStart or
14301     * @attr ref android.R.styleable#View_paddingEnd
14302     *
14303     * @return true if the padding is relative or false if it is not.
14304     */
14305    public boolean isPaddingRelative() {
14306        return mUserPaddingRelative;
14307    }
14308
14309    /**
14310     * @hide
14311     */
14312    public Insets getOpticalInsets() {
14313        if (mLayoutInsets == null) {
14314            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14315        }
14316        return mLayoutInsets;
14317    }
14318
14319    /**
14320     * @hide
14321     */
14322    public void setLayoutInsets(Insets layoutInsets) {
14323        mLayoutInsets = layoutInsets;
14324    }
14325
14326    /**
14327     * Changes the selection state of this view. A view can be selected or not.
14328     * Note that selection is not the same as focus. Views are typically
14329     * selected in the context of an AdapterView like ListView or GridView;
14330     * the selected view is the view that is highlighted.
14331     *
14332     * @param selected true if the view must be selected, false otherwise
14333     */
14334    public void setSelected(boolean selected) {
14335        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14336            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14337            if (!selected) resetPressedState();
14338            invalidate(true);
14339            refreshDrawableState();
14340            dispatchSetSelected(selected);
14341            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14342                notifyAccessibilityStateChanged();
14343            }
14344        }
14345    }
14346
14347    /**
14348     * Dispatch setSelected to all of this View's children.
14349     *
14350     * @see #setSelected(boolean)
14351     *
14352     * @param selected The new selected state
14353     */
14354    protected void dispatchSetSelected(boolean selected) {
14355    }
14356
14357    /**
14358     * Indicates the selection state of this view.
14359     *
14360     * @return true if the view is selected, false otherwise
14361     */
14362    @ViewDebug.ExportedProperty
14363    public boolean isSelected() {
14364        return (mPrivateFlags & SELECTED) != 0;
14365    }
14366
14367    /**
14368     * Changes the activated state of this view. A view can be activated or not.
14369     * Note that activation is not the same as selection.  Selection is
14370     * a transient property, representing the view (hierarchy) the user is
14371     * currently interacting with.  Activation is a longer-term state that the
14372     * user can move views in and out of.  For example, in a list view with
14373     * single or multiple selection enabled, the views in the current selection
14374     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14375     * here.)  The activated state is propagated down to children of the view it
14376     * is set on.
14377     *
14378     * @param activated true if the view must be activated, false otherwise
14379     */
14380    public void setActivated(boolean activated) {
14381        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14382            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14383            invalidate(true);
14384            refreshDrawableState();
14385            dispatchSetActivated(activated);
14386        }
14387    }
14388
14389    /**
14390     * Dispatch setActivated to all of this View's children.
14391     *
14392     * @see #setActivated(boolean)
14393     *
14394     * @param activated The new activated state
14395     */
14396    protected void dispatchSetActivated(boolean activated) {
14397    }
14398
14399    /**
14400     * Indicates the activation state of this view.
14401     *
14402     * @return true if the view is activated, false otherwise
14403     */
14404    @ViewDebug.ExportedProperty
14405    public boolean isActivated() {
14406        return (mPrivateFlags & ACTIVATED) != 0;
14407    }
14408
14409    /**
14410     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14411     * observer can be used to get notifications when global events, like
14412     * layout, happen.
14413     *
14414     * The returned ViewTreeObserver observer is not guaranteed to remain
14415     * valid for the lifetime of this View. If the caller of this method keeps
14416     * a long-lived reference to ViewTreeObserver, it should always check for
14417     * the return value of {@link ViewTreeObserver#isAlive()}.
14418     *
14419     * @return The ViewTreeObserver for this view's hierarchy.
14420     */
14421    public ViewTreeObserver getViewTreeObserver() {
14422        if (mAttachInfo != null) {
14423            return mAttachInfo.mTreeObserver;
14424        }
14425        if (mFloatingTreeObserver == null) {
14426            mFloatingTreeObserver = new ViewTreeObserver();
14427        }
14428        return mFloatingTreeObserver;
14429    }
14430
14431    /**
14432     * <p>Finds the topmost view in the current view hierarchy.</p>
14433     *
14434     * @return the topmost view containing this view
14435     */
14436    public View getRootView() {
14437        if (mAttachInfo != null) {
14438            final View v = mAttachInfo.mRootView;
14439            if (v != null) {
14440                return v;
14441            }
14442        }
14443
14444        View parent = this;
14445
14446        while (parent.mParent != null && parent.mParent instanceof View) {
14447            parent = (View) parent.mParent;
14448        }
14449
14450        return parent;
14451    }
14452
14453    /**
14454     * <p>Computes the coordinates of this view on the screen. The argument
14455     * must be an array of two integers. After the method returns, the array
14456     * contains the x and y location in that order.</p>
14457     *
14458     * @param location an array of two integers in which to hold the coordinates
14459     */
14460    public void getLocationOnScreen(int[] location) {
14461        getLocationInWindow(location);
14462
14463        final AttachInfo info = mAttachInfo;
14464        if (info != null) {
14465            location[0] += info.mWindowLeft;
14466            location[1] += info.mWindowTop;
14467        }
14468    }
14469
14470    /**
14471     * <p>Computes the coordinates of this view in its window. The argument
14472     * must be an array of two integers. After the method returns, the array
14473     * contains the x and y location in that order.</p>
14474     *
14475     * @param location an array of two integers in which to hold the coordinates
14476     */
14477    public void getLocationInWindow(int[] location) {
14478        if (location == null || location.length < 2) {
14479            throw new IllegalArgumentException("location must be an array of two integers");
14480        }
14481
14482        if (mAttachInfo == null) {
14483            // When the view is not attached to a window, this method does not make sense
14484            location[0] = location[1] = 0;
14485            return;
14486        }
14487
14488        float[] position = mAttachInfo.mTmpTransformLocation;
14489        position[0] = position[1] = 0.0f;
14490
14491        if (!hasIdentityMatrix()) {
14492            getMatrix().mapPoints(position);
14493        }
14494
14495        position[0] += mLeft;
14496        position[1] += mTop;
14497
14498        ViewParent viewParent = mParent;
14499        while (viewParent instanceof View) {
14500            final View view = (View) viewParent;
14501
14502            position[0] -= view.mScrollX;
14503            position[1] -= view.mScrollY;
14504
14505            if (!view.hasIdentityMatrix()) {
14506                view.getMatrix().mapPoints(position);
14507            }
14508
14509            position[0] += view.mLeft;
14510            position[1] += view.mTop;
14511
14512            viewParent = view.mParent;
14513         }
14514
14515        if (viewParent instanceof ViewRootImpl) {
14516            // *cough*
14517            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14518            position[1] -= vr.mCurScrollY;
14519        }
14520
14521        location[0] = (int) (position[0] + 0.5f);
14522        location[1] = (int) (position[1] + 0.5f);
14523    }
14524
14525    /**
14526     * {@hide}
14527     * @param id the id of the view to be found
14528     * @return the view of the specified id, null if cannot be found
14529     */
14530    protected View findViewTraversal(int id) {
14531        if (id == mID) {
14532            return this;
14533        }
14534        return null;
14535    }
14536
14537    /**
14538     * {@hide}
14539     * @param tag the tag of the view to be found
14540     * @return the view of specified tag, null if cannot be found
14541     */
14542    protected View findViewWithTagTraversal(Object tag) {
14543        if (tag != null && tag.equals(mTag)) {
14544            return this;
14545        }
14546        return null;
14547    }
14548
14549    /**
14550     * {@hide}
14551     * @param predicate The predicate to evaluate.
14552     * @param childToSkip If not null, ignores this child during the recursive traversal.
14553     * @return The first view that matches the predicate or null.
14554     */
14555    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14556        if (predicate.apply(this)) {
14557            return this;
14558        }
14559        return null;
14560    }
14561
14562    /**
14563     * Look for a child view with the given id.  If this view has the given
14564     * id, return this view.
14565     *
14566     * @param id The id to search for.
14567     * @return The view that has the given id in the hierarchy or null
14568     */
14569    public final View findViewById(int id) {
14570        if (id < 0) {
14571            return null;
14572        }
14573        return findViewTraversal(id);
14574    }
14575
14576    /**
14577     * Finds a view by its unuque and stable accessibility id.
14578     *
14579     * @param accessibilityId The searched accessibility id.
14580     * @return The found view.
14581     */
14582    final View findViewByAccessibilityId(int accessibilityId) {
14583        if (accessibilityId < 0) {
14584            return null;
14585        }
14586        return findViewByAccessibilityIdTraversal(accessibilityId);
14587    }
14588
14589    /**
14590     * Performs the traversal to find a view by its unuque and stable accessibility id.
14591     *
14592     * <strong>Note:</strong>This method does not stop at the root namespace
14593     * boundary since the user can touch the screen at an arbitrary location
14594     * potentially crossing the root namespace bounday which will send an
14595     * accessibility event to accessibility services and they should be able
14596     * to obtain the event source. Also accessibility ids are guaranteed to be
14597     * unique in the window.
14598     *
14599     * @param accessibilityId The accessibility id.
14600     * @return The found view.
14601     */
14602    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14603        if (getAccessibilityViewId() == accessibilityId) {
14604            return this;
14605        }
14606        return null;
14607    }
14608
14609    /**
14610     * Look for a child view with the given tag.  If this view has the given
14611     * tag, return this view.
14612     *
14613     * @param tag The tag to search for, using "tag.equals(getTag())".
14614     * @return The View that has the given tag in the hierarchy or null
14615     */
14616    public final View findViewWithTag(Object tag) {
14617        if (tag == null) {
14618            return null;
14619        }
14620        return findViewWithTagTraversal(tag);
14621    }
14622
14623    /**
14624     * {@hide}
14625     * Look for a child view that matches the specified predicate.
14626     * If this view matches the predicate, return this view.
14627     *
14628     * @param predicate The predicate to evaluate.
14629     * @return The first view that matches the predicate or null.
14630     */
14631    public final View findViewByPredicate(Predicate<View> predicate) {
14632        return findViewByPredicateTraversal(predicate, null);
14633    }
14634
14635    /**
14636     * {@hide}
14637     * Look for a child view that matches the specified predicate,
14638     * starting with the specified view and its descendents and then
14639     * recusively searching the ancestors and siblings of that view
14640     * until this view is reached.
14641     *
14642     * This method is useful in cases where the predicate does not match
14643     * a single unique view (perhaps multiple views use the same id)
14644     * and we are trying to find the view that is "closest" in scope to the
14645     * starting view.
14646     *
14647     * @param start The view to start from.
14648     * @param predicate The predicate to evaluate.
14649     * @return The first view that matches the predicate or null.
14650     */
14651    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14652        View childToSkip = null;
14653        for (;;) {
14654            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14655            if (view != null || start == this) {
14656                return view;
14657            }
14658
14659            ViewParent parent = start.getParent();
14660            if (parent == null || !(parent instanceof View)) {
14661                return null;
14662            }
14663
14664            childToSkip = start;
14665            start = (View) parent;
14666        }
14667    }
14668
14669    /**
14670     * Sets the identifier for this view. The identifier does not have to be
14671     * unique in this view's hierarchy. The identifier should be a positive
14672     * number.
14673     *
14674     * @see #NO_ID
14675     * @see #getId()
14676     * @see #findViewById(int)
14677     *
14678     * @param id a number used to identify the view
14679     *
14680     * @attr ref android.R.styleable#View_id
14681     */
14682    public void setId(int id) {
14683        mID = id;
14684    }
14685
14686    /**
14687     * {@hide}
14688     *
14689     * @param isRoot true if the view belongs to the root namespace, false
14690     *        otherwise
14691     */
14692    public void setIsRootNamespace(boolean isRoot) {
14693        if (isRoot) {
14694            mPrivateFlags |= IS_ROOT_NAMESPACE;
14695        } else {
14696            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14697        }
14698    }
14699
14700    /**
14701     * {@hide}
14702     *
14703     * @return true if the view belongs to the root namespace, false otherwise
14704     */
14705    public boolean isRootNamespace() {
14706        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14707    }
14708
14709    /**
14710     * Returns this view's identifier.
14711     *
14712     * @return a positive integer used to identify the view or {@link #NO_ID}
14713     *         if the view has no ID
14714     *
14715     * @see #setId(int)
14716     * @see #findViewById(int)
14717     * @attr ref android.R.styleable#View_id
14718     */
14719    @ViewDebug.CapturedViewProperty
14720    public int getId() {
14721        return mID;
14722    }
14723
14724    /**
14725     * Returns this view's tag.
14726     *
14727     * @return the Object stored in this view as a tag
14728     *
14729     * @see #setTag(Object)
14730     * @see #getTag(int)
14731     */
14732    @ViewDebug.ExportedProperty
14733    public Object getTag() {
14734        return mTag;
14735    }
14736
14737    /**
14738     * Sets the tag associated with this view. A tag can be used to mark
14739     * a view in its hierarchy and does not have to be unique within the
14740     * hierarchy. Tags can also be used to store data within a view without
14741     * resorting to another data structure.
14742     *
14743     * @param tag an Object to tag the view with
14744     *
14745     * @see #getTag()
14746     * @see #setTag(int, Object)
14747     */
14748    public void setTag(final Object tag) {
14749        mTag = tag;
14750    }
14751
14752    /**
14753     * Returns the tag associated with this view and the specified key.
14754     *
14755     * @param key The key identifying the tag
14756     *
14757     * @return the Object stored in this view as a tag
14758     *
14759     * @see #setTag(int, Object)
14760     * @see #getTag()
14761     */
14762    public Object getTag(int key) {
14763        if (mKeyedTags != null) return mKeyedTags.get(key);
14764        return null;
14765    }
14766
14767    /**
14768     * Sets a tag associated with this view and a key. A tag can be used
14769     * to mark a view in its hierarchy and does not have to be unique within
14770     * the hierarchy. Tags can also be used to store data within a view
14771     * without resorting to another data structure.
14772     *
14773     * The specified key should be an id declared in the resources of the
14774     * application to ensure it is unique (see the <a
14775     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14776     * Keys identified as belonging to
14777     * the Android framework or not associated with any package will cause
14778     * an {@link IllegalArgumentException} to be thrown.
14779     *
14780     * @param key The key identifying the tag
14781     * @param tag An Object to tag the view with
14782     *
14783     * @throws IllegalArgumentException If they specified key is not valid
14784     *
14785     * @see #setTag(Object)
14786     * @see #getTag(int)
14787     */
14788    public void setTag(int key, final Object tag) {
14789        // If the package id is 0x00 or 0x01, it's either an undefined package
14790        // or a framework id
14791        if ((key >>> 24) < 2) {
14792            throw new IllegalArgumentException("The key must be an application-specific "
14793                    + "resource id.");
14794        }
14795
14796        setKeyedTag(key, tag);
14797    }
14798
14799    /**
14800     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14801     * framework id.
14802     *
14803     * @hide
14804     */
14805    public void setTagInternal(int key, Object tag) {
14806        if ((key >>> 24) != 0x1) {
14807            throw new IllegalArgumentException("The key must be a framework-specific "
14808                    + "resource id.");
14809        }
14810
14811        setKeyedTag(key, tag);
14812    }
14813
14814    private void setKeyedTag(int key, Object tag) {
14815        if (mKeyedTags == null) {
14816            mKeyedTags = new SparseArray<Object>();
14817        }
14818
14819        mKeyedTags.put(key, tag);
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        mPrivateFlags |= FORCE_LAYOUT;
14936        mPrivateFlags |= INVALIDATED;
14937
14938        if (mLayoutParams != null) {
14939            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14940        }
14941
14942        if (mParent != null && !mParent.isLayoutRequested()) {
14943            mParent.requestLayout();
14944        }
14945    }
14946
14947    /**
14948     * Forces this view to be laid out during the next layout pass.
14949     * This method does not call requestLayout() or forceLayout()
14950     * on the parent.
14951     */
14952    public void forceLayout() {
14953        mPrivateFlags |= FORCE_LAYOUT;
14954        mPrivateFlags |= INVALIDATED;
14955    }
14956
14957    /**
14958     * <p>
14959     * This is called to find out how big a view should be. The parent
14960     * supplies constraint information in the width and height parameters.
14961     * </p>
14962     *
14963     * <p>
14964     * The actual measurement work of a view is performed in
14965     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14966     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14967     * </p>
14968     *
14969     *
14970     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14971     *        parent
14972     * @param heightMeasureSpec Vertical space requirements as imposed by the
14973     *        parent
14974     *
14975     * @see #onMeasure(int, int)
14976     */
14977    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14978        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14979                widthMeasureSpec != mOldWidthMeasureSpec ||
14980                heightMeasureSpec != mOldHeightMeasureSpec) {
14981
14982            // first clears the measured dimension flag
14983            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14984
14985            // measure ourselves, this should set the measured dimension flag back
14986            onMeasure(widthMeasureSpec, heightMeasureSpec);
14987
14988            // flag not set, setMeasuredDimension() was not invoked, we raise
14989            // an exception to warn the developer
14990            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14991                throw new IllegalStateException("onMeasure() did not set the"
14992                        + " measured dimension by calling"
14993                        + " setMeasuredDimension()");
14994            }
14995
14996            mPrivateFlags |= LAYOUT_REQUIRED;
14997        }
14998
14999        mOldWidthMeasureSpec = widthMeasureSpec;
15000        mOldHeightMeasureSpec = heightMeasureSpec;
15001    }
15002
15003    /**
15004     * <p>
15005     * Measure the view and its content to determine the measured width and the
15006     * measured height. This method is invoked by {@link #measure(int, int)} and
15007     * should be overriden by subclasses to provide accurate and efficient
15008     * measurement of their contents.
15009     * </p>
15010     *
15011     * <p>
15012     * <strong>CONTRACT:</strong> When overriding this method, you
15013     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15014     * measured width and height of this view. Failure to do so will trigger an
15015     * <code>IllegalStateException</code>, thrown by
15016     * {@link #measure(int, int)}. Calling the superclass'
15017     * {@link #onMeasure(int, int)} is a valid use.
15018     * </p>
15019     *
15020     * <p>
15021     * The base class implementation of measure defaults to the background size,
15022     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15023     * override {@link #onMeasure(int, int)} to provide better measurements of
15024     * their content.
15025     * </p>
15026     *
15027     * <p>
15028     * If this method is overridden, it is the subclass's responsibility to make
15029     * sure the measured height and width are at least the view's minimum height
15030     * and width ({@link #getSuggestedMinimumHeight()} and
15031     * {@link #getSuggestedMinimumWidth()}).
15032     * </p>
15033     *
15034     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15035     *                         The requirements are encoded with
15036     *                         {@link android.view.View.MeasureSpec}.
15037     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15038     *                         The requirements are encoded with
15039     *                         {@link android.view.View.MeasureSpec}.
15040     *
15041     * @see #getMeasuredWidth()
15042     * @see #getMeasuredHeight()
15043     * @see #setMeasuredDimension(int, int)
15044     * @see #getSuggestedMinimumHeight()
15045     * @see #getSuggestedMinimumWidth()
15046     * @see android.view.View.MeasureSpec#getMode(int)
15047     * @see android.view.View.MeasureSpec#getSize(int)
15048     */
15049    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15050        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15051                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15052    }
15053
15054    /**
15055     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15056     * measured width and measured height. Failing to do so will trigger an
15057     * exception at measurement time.</p>
15058     *
15059     * @param measuredWidth The measured width of this view.  May be a complex
15060     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15061     * {@link #MEASURED_STATE_TOO_SMALL}.
15062     * @param measuredHeight The measured height of this view.  May be a complex
15063     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15064     * {@link #MEASURED_STATE_TOO_SMALL}.
15065     */
15066    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15067        mMeasuredWidth = measuredWidth;
15068        mMeasuredHeight = measuredHeight;
15069
15070        mPrivateFlags |= MEASURED_DIMENSION_SET;
15071    }
15072
15073    /**
15074     * Merge two states as returned by {@link #getMeasuredState()}.
15075     * @param curState The current state as returned from a view or the result
15076     * of combining multiple views.
15077     * @param newState The new view state to combine.
15078     * @return Returns a new integer reflecting the combination of the two
15079     * states.
15080     */
15081    public static int combineMeasuredStates(int curState, int newState) {
15082        return curState | newState;
15083    }
15084
15085    /**
15086     * Version of {@link #resolveSizeAndState(int, int, int)}
15087     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15088     */
15089    public static int resolveSize(int size, int measureSpec) {
15090        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15091    }
15092
15093    /**
15094     * Utility to reconcile a desired size and state, with constraints imposed
15095     * by a MeasureSpec.  Will take the desired size, unless a different size
15096     * is imposed by the constraints.  The returned value is a compound integer,
15097     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15098     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15099     * size is smaller than the size the view wants to be.
15100     *
15101     * @param size How big the view wants to be
15102     * @param measureSpec Constraints imposed by the parent
15103     * @return Size information bit mask as defined by
15104     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15105     */
15106    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15107        int result = size;
15108        int specMode = MeasureSpec.getMode(measureSpec);
15109        int specSize =  MeasureSpec.getSize(measureSpec);
15110        switch (specMode) {
15111        case MeasureSpec.UNSPECIFIED:
15112            result = size;
15113            break;
15114        case MeasureSpec.AT_MOST:
15115            if (specSize < size) {
15116                result = specSize | MEASURED_STATE_TOO_SMALL;
15117            } else {
15118                result = size;
15119            }
15120            break;
15121        case MeasureSpec.EXACTLY:
15122            result = specSize;
15123            break;
15124        }
15125        return result | (childMeasuredState&MEASURED_STATE_MASK);
15126    }
15127
15128    /**
15129     * Utility to return a default size. Uses the supplied size if the
15130     * MeasureSpec imposed no constraints. Will get larger if allowed
15131     * by the MeasureSpec.
15132     *
15133     * @param size Default size for this view
15134     * @param measureSpec Constraints imposed by the parent
15135     * @return The size this view should be.
15136     */
15137    public static int getDefaultSize(int size, int measureSpec) {
15138        int result = size;
15139        int specMode = MeasureSpec.getMode(measureSpec);
15140        int specSize = MeasureSpec.getSize(measureSpec);
15141
15142        switch (specMode) {
15143        case MeasureSpec.UNSPECIFIED:
15144            result = size;
15145            break;
15146        case MeasureSpec.AT_MOST:
15147        case MeasureSpec.EXACTLY:
15148            result = specSize;
15149            break;
15150        }
15151        return result;
15152    }
15153
15154    /**
15155     * Returns the suggested minimum height that the view should use. This
15156     * returns the maximum of the view's minimum height
15157     * and the background's minimum height
15158     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15159     * <p>
15160     * When being used in {@link #onMeasure(int, int)}, the caller should still
15161     * ensure the returned height is within the requirements of the parent.
15162     *
15163     * @return The suggested minimum height of the view.
15164     */
15165    protected int getSuggestedMinimumHeight() {
15166        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15167
15168    }
15169
15170    /**
15171     * Returns the suggested minimum width that the view should use. This
15172     * returns the maximum of the view's minimum width)
15173     * and the background's minimum width
15174     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15175     * <p>
15176     * When being used in {@link #onMeasure(int, int)}, the caller should still
15177     * ensure the returned width is within the requirements of the parent.
15178     *
15179     * @return The suggested minimum width of the view.
15180     */
15181    protected int getSuggestedMinimumWidth() {
15182        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15183    }
15184
15185    /**
15186     * Returns the minimum height of the view.
15187     *
15188     * @return the minimum height the view will try to be.
15189     *
15190     * @see #setMinimumHeight(int)
15191     *
15192     * @attr ref android.R.styleable#View_minHeight
15193     */
15194    public int getMinimumHeight() {
15195        return mMinHeight;
15196    }
15197
15198    /**
15199     * Sets the minimum height of the view. It is not guaranteed the view will
15200     * be able to achieve this minimum height (for example, if its parent layout
15201     * constrains it with less available height).
15202     *
15203     * @param minHeight The minimum height the view will try to be.
15204     *
15205     * @see #getMinimumHeight()
15206     *
15207     * @attr ref android.R.styleable#View_minHeight
15208     */
15209    public void setMinimumHeight(int minHeight) {
15210        mMinHeight = minHeight;
15211        requestLayout();
15212    }
15213
15214    /**
15215     * Returns the minimum width of the view.
15216     *
15217     * @return the minimum width the view will try to be.
15218     *
15219     * @see #setMinimumWidth(int)
15220     *
15221     * @attr ref android.R.styleable#View_minWidth
15222     */
15223    public int getMinimumWidth() {
15224        return mMinWidth;
15225    }
15226
15227    /**
15228     * Sets the minimum width of the view. It is not guaranteed the view will
15229     * be able to achieve this minimum width (for example, if its parent layout
15230     * constrains it with less available width).
15231     *
15232     * @param minWidth The minimum width the view will try to be.
15233     *
15234     * @see #getMinimumWidth()
15235     *
15236     * @attr ref android.R.styleable#View_minWidth
15237     */
15238    public void setMinimumWidth(int minWidth) {
15239        mMinWidth = minWidth;
15240        requestLayout();
15241
15242    }
15243
15244    /**
15245     * Get the animation currently associated with this view.
15246     *
15247     * @return The animation that is currently playing or
15248     *         scheduled to play for this view.
15249     */
15250    public Animation getAnimation() {
15251        return mCurrentAnimation;
15252    }
15253
15254    /**
15255     * Start the specified animation now.
15256     *
15257     * @param animation the animation to start now
15258     */
15259    public void startAnimation(Animation animation) {
15260        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15261        setAnimation(animation);
15262        invalidateParentCaches();
15263        invalidate(true);
15264    }
15265
15266    /**
15267     * Cancels any animations for this view.
15268     */
15269    public void clearAnimation() {
15270        if (mCurrentAnimation != null) {
15271            mCurrentAnimation.detach();
15272        }
15273        mCurrentAnimation = null;
15274        invalidateParentIfNeeded();
15275    }
15276
15277    /**
15278     * Sets the next animation to play for this view.
15279     * If you want the animation to play immediately, use
15280     * {@link #startAnimation(android.view.animation.Animation)} instead.
15281     * This method provides allows fine-grained
15282     * control over the start time and invalidation, but you
15283     * must make sure that 1) the animation has a start time set, and
15284     * 2) the view's parent (which controls animations on its children)
15285     * will be invalidated when the animation is supposed to
15286     * start.
15287     *
15288     * @param animation The next animation, or null.
15289     */
15290    public void setAnimation(Animation animation) {
15291        mCurrentAnimation = animation;
15292
15293        if (animation != null) {
15294            // If the screen is off assume the animation start time is now instead of
15295            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15296            // would cause the animation to start when the screen turns back on
15297            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15298                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15299                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15300            }
15301            animation.reset();
15302        }
15303    }
15304
15305    /**
15306     * Invoked by a parent ViewGroup to notify the start of the animation
15307     * currently associated with this view. If you override this method,
15308     * always call super.onAnimationStart();
15309     *
15310     * @see #setAnimation(android.view.animation.Animation)
15311     * @see #getAnimation()
15312     */
15313    protected void onAnimationStart() {
15314        mPrivateFlags |= ANIMATION_STARTED;
15315    }
15316
15317    /**
15318     * Invoked by a parent ViewGroup to notify the end of the animation
15319     * currently associated with this view. If you override this method,
15320     * always call super.onAnimationEnd();
15321     *
15322     * @see #setAnimation(android.view.animation.Animation)
15323     * @see #getAnimation()
15324     */
15325    protected void onAnimationEnd() {
15326        mPrivateFlags &= ~ANIMATION_STARTED;
15327    }
15328
15329    /**
15330     * Invoked if there is a Transform that involves alpha. Subclass that can
15331     * draw themselves with the specified alpha should return true, and then
15332     * respect that alpha when their onDraw() is called. If this returns false
15333     * then the view may be redirected to draw into an offscreen buffer to
15334     * fulfill the request, which will look fine, but may be slower than if the
15335     * subclass handles it internally. The default implementation returns false.
15336     *
15337     * @param alpha The alpha (0..255) to apply to the view's drawing
15338     * @return true if the view can draw with the specified alpha.
15339     */
15340    protected boolean onSetAlpha(int alpha) {
15341        return false;
15342    }
15343
15344    /**
15345     * This is used by the RootView to perform an optimization when
15346     * the view hierarchy contains one or several SurfaceView.
15347     * SurfaceView is always considered transparent, but its children are not,
15348     * therefore all View objects remove themselves from the global transparent
15349     * region (passed as a parameter to this function).
15350     *
15351     * @param region The transparent region for this ViewAncestor (window).
15352     *
15353     * @return Returns true if the effective visibility of the view at this
15354     * point is opaque, regardless of the transparent region; returns false
15355     * if it is possible for underlying windows to be seen behind the view.
15356     *
15357     * {@hide}
15358     */
15359    public boolean gatherTransparentRegion(Region region) {
15360        final AttachInfo attachInfo = mAttachInfo;
15361        if (region != null && attachInfo != null) {
15362            final int pflags = mPrivateFlags;
15363            if ((pflags & SKIP_DRAW) == 0) {
15364                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15365                // remove it from the transparent region.
15366                final int[] location = attachInfo.mTransparentLocation;
15367                getLocationInWindow(location);
15368                region.op(location[0], location[1], location[0] + mRight - mLeft,
15369                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15370            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15371                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15372                // exists, so we remove the background drawable's non-transparent
15373                // parts from this transparent region.
15374                applyDrawableToTransparentRegion(mBackground, region);
15375            }
15376        }
15377        return true;
15378    }
15379
15380    /**
15381     * Play a sound effect for this view.
15382     *
15383     * <p>The framework will play sound effects for some built in actions, such as
15384     * clicking, but you may wish to play these effects in your widget,
15385     * for instance, for internal navigation.
15386     *
15387     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15388     * {@link #isSoundEffectsEnabled()} is true.
15389     *
15390     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15391     */
15392    public void playSoundEffect(int soundConstant) {
15393        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15394            return;
15395        }
15396        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15397    }
15398
15399    /**
15400     * BZZZTT!!1!
15401     *
15402     * <p>Provide haptic feedback to the user for this view.
15403     *
15404     * <p>The framework will provide haptic feedback for some built in actions,
15405     * such as long presses, but you may wish to provide feedback for your
15406     * own widget.
15407     *
15408     * <p>The feedback will only be performed if
15409     * {@link #isHapticFeedbackEnabled()} is true.
15410     *
15411     * @param feedbackConstant One of the constants defined in
15412     * {@link HapticFeedbackConstants}
15413     */
15414    public boolean performHapticFeedback(int feedbackConstant) {
15415        return performHapticFeedback(feedbackConstant, 0);
15416    }
15417
15418    /**
15419     * BZZZTT!!1!
15420     *
15421     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15422     *
15423     * @param feedbackConstant One of the constants defined in
15424     * {@link HapticFeedbackConstants}
15425     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15426     */
15427    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15428        if (mAttachInfo == null) {
15429            return false;
15430        }
15431        //noinspection SimplifiableIfStatement
15432        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15433                && !isHapticFeedbackEnabled()) {
15434            return false;
15435        }
15436        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15437                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15438    }
15439
15440    /**
15441     * Request that the visibility of the status bar or other screen/window
15442     * decorations be changed.
15443     *
15444     * <p>This method is used to put the over device UI into temporary modes
15445     * where the user's attention is focused more on the application content,
15446     * by dimming or hiding surrounding system affordances.  This is typically
15447     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15448     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15449     * to be placed behind the action bar (and with these flags other system
15450     * affordances) so that smooth transitions between hiding and showing them
15451     * can be done.
15452     *
15453     * <p>Two representative examples of the use of system UI visibility is
15454     * implementing a content browsing application (like a magazine reader)
15455     * and a video playing application.
15456     *
15457     * <p>The first code shows a typical implementation of a View in a content
15458     * browsing application.  In this implementation, the application goes
15459     * into a content-oriented mode by hiding the status bar and action bar,
15460     * and putting the navigation elements into lights out mode.  The user can
15461     * then interact with content while in this mode.  Such an application should
15462     * provide an easy way for the user to toggle out of the mode (such as to
15463     * check information in the status bar or access notifications).  In the
15464     * implementation here, this is done simply by tapping on the content.
15465     *
15466     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15467     *      content}
15468     *
15469     * <p>This second code sample shows a typical implementation of a View
15470     * in a video playing application.  In this situation, while the video is
15471     * playing the application would like to go into a complete full-screen mode,
15472     * to use as much of the display as possible for the video.  When in this state
15473     * the user can not interact with the application; the system intercepts
15474     * touching on the screen to pop the UI out of full screen mode.  See
15475     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15476     *
15477     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15478     *      content}
15479     *
15480     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15481     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15482     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15483     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15484     */
15485    public void setSystemUiVisibility(int visibility) {
15486        if (visibility != mSystemUiVisibility) {
15487            mSystemUiVisibility = visibility;
15488            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15489                mParent.recomputeViewAttributes(this);
15490            }
15491        }
15492    }
15493
15494    /**
15495     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15496     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15497     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15498     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15499     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15500     */
15501    public int getSystemUiVisibility() {
15502        return mSystemUiVisibility;
15503    }
15504
15505    /**
15506     * Returns the current system UI visibility that is currently set for
15507     * the entire window.  This is the combination of the
15508     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15509     * views in the window.
15510     */
15511    public int getWindowSystemUiVisibility() {
15512        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15513    }
15514
15515    /**
15516     * Override to find out when the window's requested system UI visibility
15517     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15518     * This is different from the callbacks recieved through
15519     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15520     * in that this is only telling you about the local request of the window,
15521     * not the actual values applied by the system.
15522     */
15523    public void onWindowSystemUiVisibilityChanged(int visible) {
15524    }
15525
15526    /**
15527     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15528     * the view hierarchy.
15529     */
15530    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15531        onWindowSystemUiVisibilityChanged(visible);
15532    }
15533
15534    /**
15535     * Set a listener to receive callbacks when the visibility of the system bar changes.
15536     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15537     */
15538    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15539        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15540        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15541            mParent.recomputeViewAttributes(this);
15542        }
15543    }
15544
15545    /**
15546     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15547     * the view hierarchy.
15548     */
15549    public void dispatchSystemUiVisibilityChanged(int visibility) {
15550        ListenerInfo li = mListenerInfo;
15551        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15552            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15553                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15554        }
15555    }
15556
15557    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15558        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15559        if (val != mSystemUiVisibility) {
15560            setSystemUiVisibility(val);
15561            return true;
15562        }
15563        return false;
15564    }
15565
15566    /** @hide */
15567    public void setDisabledSystemUiVisibility(int flags) {
15568        if (mAttachInfo != null) {
15569            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15570                mAttachInfo.mDisabledSystemUiVisibility = flags;
15571                if (mParent != null) {
15572                    mParent.recomputeViewAttributes(this);
15573                }
15574            }
15575        }
15576    }
15577
15578    /**
15579     * Creates an image that the system displays during the drag and drop
15580     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15581     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15582     * appearance as the given View. The default also positions the center of the drag shadow
15583     * directly under the touch point. If no View is provided (the constructor with no parameters
15584     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15585     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15586     * default is an invisible drag shadow.
15587     * <p>
15588     * You are not required to use the View you provide to the constructor as the basis of the
15589     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15590     * anything you want as the drag shadow.
15591     * </p>
15592     * <p>
15593     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15594     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15595     *  size and position of the drag shadow. It uses this data to construct a
15596     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15597     *  so that your application can draw the shadow image in the Canvas.
15598     * </p>
15599     *
15600     * <div class="special reference">
15601     * <h3>Developer Guides</h3>
15602     * <p>For a guide to implementing drag and drop features, read the
15603     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15604     * </div>
15605     */
15606    public static class DragShadowBuilder {
15607        private final WeakReference<View> mView;
15608
15609        /**
15610         * Constructs a shadow image builder based on a View. By default, the resulting drag
15611         * shadow will have the same appearance and dimensions as the View, with the touch point
15612         * over the center of the View.
15613         * @param view A View. Any View in scope can be used.
15614         */
15615        public DragShadowBuilder(View view) {
15616            mView = new WeakReference<View>(view);
15617        }
15618
15619        /**
15620         * Construct a shadow builder object with no associated View.  This
15621         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15622         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15623         * to supply the drag shadow's dimensions and appearance without
15624         * reference to any View object. If they are not overridden, then the result is an
15625         * invisible drag shadow.
15626         */
15627        public DragShadowBuilder() {
15628            mView = new WeakReference<View>(null);
15629        }
15630
15631        /**
15632         * Returns the View object that had been passed to the
15633         * {@link #View.DragShadowBuilder(View)}
15634         * constructor.  If that View parameter was {@code null} or if the
15635         * {@link #View.DragShadowBuilder()}
15636         * constructor was used to instantiate the builder object, this method will return
15637         * null.
15638         *
15639         * @return The View object associate with this builder object.
15640         */
15641        @SuppressWarnings({"JavadocReference"})
15642        final public View getView() {
15643            return mView.get();
15644        }
15645
15646        /**
15647         * Provides the metrics for the shadow image. These include the dimensions of
15648         * the shadow image, and the point within that shadow that should
15649         * be centered under the touch location while dragging.
15650         * <p>
15651         * The default implementation sets the dimensions of the shadow to be the
15652         * same as the dimensions of the View itself and centers the shadow under
15653         * the touch point.
15654         * </p>
15655         *
15656         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15657         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15658         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15659         * image.
15660         *
15661         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15662         * shadow image that should be underneath the touch point during the drag and drop
15663         * operation. Your application must set {@link android.graphics.Point#x} to the
15664         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15665         */
15666        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15667            final View view = mView.get();
15668            if (view != null) {
15669                shadowSize.set(view.getWidth(), view.getHeight());
15670                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15671            } else {
15672                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15673            }
15674        }
15675
15676        /**
15677         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15678         * based on the dimensions it received from the
15679         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15680         *
15681         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15682         */
15683        public void onDrawShadow(Canvas canvas) {
15684            final View view = mView.get();
15685            if (view != null) {
15686                view.draw(canvas);
15687            } else {
15688                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15689            }
15690        }
15691    }
15692
15693    /**
15694     * Starts a drag and drop operation. When your application calls this method, it passes a
15695     * {@link android.view.View.DragShadowBuilder} object to the system. The
15696     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15697     * to get metrics for the drag shadow, and then calls the object's
15698     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15699     * <p>
15700     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15701     *  drag events to all the View objects in your application that are currently visible. It does
15702     *  this either by calling the View object's drag listener (an implementation of
15703     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15704     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15705     *  Both are passed a {@link android.view.DragEvent} object that has a
15706     *  {@link android.view.DragEvent#getAction()} value of
15707     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15708     * </p>
15709     * <p>
15710     * Your application can invoke startDrag() on any attached View object. The View object does not
15711     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15712     * be related to the View the user selected for dragging.
15713     * </p>
15714     * @param data A {@link android.content.ClipData} object pointing to the data to be
15715     * transferred by the drag and drop operation.
15716     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15717     * drag shadow.
15718     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15719     * drop operation. This Object is put into every DragEvent object sent by the system during the
15720     * current drag.
15721     * <p>
15722     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15723     * to the target Views. For example, it can contain flags that differentiate between a
15724     * a copy operation and a move operation.
15725     * </p>
15726     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15727     * so the parameter should be set to 0.
15728     * @return {@code true} if the method completes successfully, or
15729     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15730     * do a drag, and so no drag operation is in progress.
15731     */
15732    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15733            Object myLocalState, int flags) {
15734        if (ViewDebug.DEBUG_DRAG) {
15735            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15736        }
15737        boolean okay = false;
15738
15739        Point shadowSize = new Point();
15740        Point shadowTouchPoint = new Point();
15741        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15742
15743        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15744                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15745            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15746        }
15747
15748        if (ViewDebug.DEBUG_DRAG) {
15749            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15750                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15751        }
15752        Surface surface = new Surface();
15753        try {
15754            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15755                    flags, shadowSize.x, shadowSize.y, surface);
15756            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15757                    + " surface=" + surface);
15758            if (token != null) {
15759                Canvas canvas = surface.lockCanvas(null);
15760                try {
15761                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15762                    shadowBuilder.onDrawShadow(canvas);
15763                } finally {
15764                    surface.unlockCanvasAndPost(canvas);
15765                }
15766
15767                final ViewRootImpl root = getViewRootImpl();
15768
15769                // Cache the local state object for delivery with DragEvents
15770                root.setLocalDragState(myLocalState);
15771
15772                // repurpose 'shadowSize' for the last touch point
15773                root.getLastTouchPoint(shadowSize);
15774
15775                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15776                        shadowSize.x, shadowSize.y,
15777                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15778                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15779
15780                // Off and running!  Release our local surface instance; the drag
15781                // shadow surface is now managed by the system process.
15782                surface.release();
15783            }
15784        } catch (Exception e) {
15785            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15786            surface.destroy();
15787        }
15788
15789        return okay;
15790    }
15791
15792    /**
15793     * Handles drag events sent by the system following a call to
15794     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15795     *<p>
15796     * When the system calls this method, it passes a
15797     * {@link android.view.DragEvent} object. A call to
15798     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15799     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15800     * operation.
15801     * @param event The {@link android.view.DragEvent} sent by the system.
15802     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15803     * in DragEvent, indicating the type of drag event represented by this object.
15804     * @return {@code true} if the method was successful, otherwise {@code false}.
15805     * <p>
15806     *  The method should return {@code true} in response to an action type of
15807     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15808     *  operation.
15809     * </p>
15810     * <p>
15811     *  The method should also return {@code true} in response to an action type of
15812     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15813     *  {@code false} if it didn't.
15814     * </p>
15815     */
15816    public boolean onDragEvent(DragEvent event) {
15817        return false;
15818    }
15819
15820    /**
15821     * Detects if this View is enabled and has a drag event listener.
15822     * If both are true, then it calls the drag event listener with the
15823     * {@link android.view.DragEvent} it received. If the drag event listener returns
15824     * {@code true}, then dispatchDragEvent() returns {@code true}.
15825     * <p>
15826     * For all other cases, the method calls the
15827     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15828     * method and returns its result.
15829     * </p>
15830     * <p>
15831     * This ensures that a drag event is always consumed, even if the View does not have a drag
15832     * event listener. However, if the View has a listener and the listener returns true, then
15833     * onDragEvent() is not called.
15834     * </p>
15835     */
15836    public boolean dispatchDragEvent(DragEvent event) {
15837        //noinspection SimplifiableIfStatement
15838        ListenerInfo li = mListenerInfo;
15839        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15840                && li.mOnDragListener.onDrag(this, event)) {
15841            return true;
15842        }
15843        return onDragEvent(event);
15844    }
15845
15846    boolean canAcceptDrag() {
15847        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15848    }
15849
15850    /**
15851     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15852     * it is ever exposed at all.
15853     * @hide
15854     */
15855    public void onCloseSystemDialogs(String reason) {
15856    }
15857
15858    /**
15859     * Given a Drawable whose bounds have been set to draw into this view,
15860     * update a Region being computed for
15861     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15862     * that any non-transparent parts of the Drawable are removed from the
15863     * given transparent region.
15864     *
15865     * @param dr The Drawable whose transparency is to be applied to the region.
15866     * @param region A Region holding the current transparency information,
15867     * where any parts of the region that are set are considered to be
15868     * transparent.  On return, this region will be modified to have the
15869     * transparency information reduced by the corresponding parts of the
15870     * Drawable that are not transparent.
15871     * {@hide}
15872     */
15873    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15874        if (DBG) {
15875            Log.i("View", "Getting transparent region for: " + this);
15876        }
15877        final Region r = dr.getTransparentRegion();
15878        final Rect db = dr.getBounds();
15879        final AttachInfo attachInfo = mAttachInfo;
15880        if (r != null && attachInfo != null) {
15881            final int w = getRight()-getLeft();
15882            final int h = getBottom()-getTop();
15883            if (db.left > 0) {
15884                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15885                r.op(0, 0, db.left, h, Region.Op.UNION);
15886            }
15887            if (db.right < w) {
15888                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15889                r.op(db.right, 0, w, h, Region.Op.UNION);
15890            }
15891            if (db.top > 0) {
15892                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15893                r.op(0, 0, w, db.top, Region.Op.UNION);
15894            }
15895            if (db.bottom < h) {
15896                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15897                r.op(0, db.bottom, w, h, Region.Op.UNION);
15898            }
15899            final int[] location = attachInfo.mTransparentLocation;
15900            getLocationInWindow(location);
15901            r.translate(location[0], location[1]);
15902            region.op(r, Region.Op.INTERSECT);
15903        } else {
15904            region.op(db, Region.Op.DIFFERENCE);
15905        }
15906    }
15907
15908    private void checkForLongClick(int delayOffset) {
15909        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15910            mHasPerformedLongPress = false;
15911
15912            if (mPendingCheckForLongPress == null) {
15913                mPendingCheckForLongPress = new CheckForLongPress();
15914            }
15915            mPendingCheckForLongPress.rememberWindowAttachCount();
15916            postDelayed(mPendingCheckForLongPress,
15917                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15918        }
15919    }
15920
15921    /**
15922     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15923     * LayoutInflater} class, which provides a full range of options for view inflation.
15924     *
15925     * @param context The Context object for your activity or application.
15926     * @param resource The resource ID to inflate
15927     * @param root A view group that will be the parent.  Used to properly inflate the
15928     * layout_* parameters.
15929     * @see LayoutInflater
15930     */
15931    public static View inflate(Context context, int resource, ViewGroup root) {
15932        LayoutInflater factory = LayoutInflater.from(context);
15933        return factory.inflate(resource, root);
15934    }
15935
15936    /**
15937     * Scroll the view with standard behavior for scrolling beyond the normal
15938     * content boundaries. Views that call this method should override
15939     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15940     * results of an over-scroll operation.
15941     *
15942     * Views can use this method to handle any touch or fling-based scrolling.
15943     *
15944     * @param deltaX Change in X in pixels
15945     * @param deltaY Change in Y in pixels
15946     * @param scrollX Current X scroll value in pixels before applying deltaX
15947     * @param scrollY Current Y scroll value in pixels before applying deltaY
15948     * @param scrollRangeX Maximum content scroll range along the X axis
15949     * @param scrollRangeY Maximum content scroll range along the Y axis
15950     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15951     *          along the X axis.
15952     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15953     *          along the Y axis.
15954     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15955     * @return true if scrolling was clamped to an over-scroll boundary along either
15956     *          axis, false otherwise.
15957     */
15958    @SuppressWarnings({"UnusedParameters"})
15959    protected boolean overScrollBy(int deltaX, int deltaY,
15960            int scrollX, int scrollY,
15961            int scrollRangeX, int scrollRangeY,
15962            int maxOverScrollX, int maxOverScrollY,
15963            boolean isTouchEvent) {
15964        final int overScrollMode = mOverScrollMode;
15965        final boolean canScrollHorizontal =
15966                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15967        final boolean canScrollVertical =
15968                computeVerticalScrollRange() > computeVerticalScrollExtent();
15969        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15970                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15971        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15972                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15973
15974        int newScrollX = scrollX + deltaX;
15975        if (!overScrollHorizontal) {
15976            maxOverScrollX = 0;
15977        }
15978
15979        int newScrollY = scrollY + deltaY;
15980        if (!overScrollVertical) {
15981            maxOverScrollY = 0;
15982        }
15983
15984        // Clamp values if at the limits and record
15985        final int left = -maxOverScrollX;
15986        final int right = maxOverScrollX + scrollRangeX;
15987        final int top = -maxOverScrollY;
15988        final int bottom = maxOverScrollY + scrollRangeY;
15989
15990        boolean clampedX = false;
15991        if (newScrollX > right) {
15992            newScrollX = right;
15993            clampedX = true;
15994        } else if (newScrollX < left) {
15995            newScrollX = left;
15996            clampedX = true;
15997        }
15998
15999        boolean clampedY = false;
16000        if (newScrollY > bottom) {
16001            newScrollY = bottom;
16002            clampedY = true;
16003        } else if (newScrollY < top) {
16004            newScrollY = top;
16005            clampedY = true;
16006        }
16007
16008        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16009
16010        return clampedX || clampedY;
16011    }
16012
16013    /**
16014     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16015     * respond to the results of an over-scroll operation.
16016     *
16017     * @param scrollX New X scroll value in pixels
16018     * @param scrollY New Y scroll value in pixels
16019     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16020     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16021     */
16022    protected void onOverScrolled(int scrollX, int scrollY,
16023            boolean clampedX, boolean clampedY) {
16024        // Intentionally empty.
16025    }
16026
16027    /**
16028     * Returns the over-scroll mode for this view. The result will be
16029     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16030     * (allow over-scrolling only if the view content is larger than the container),
16031     * or {@link #OVER_SCROLL_NEVER}.
16032     *
16033     * @return This view's over-scroll mode.
16034     */
16035    public int getOverScrollMode() {
16036        return mOverScrollMode;
16037    }
16038
16039    /**
16040     * Set the over-scroll mode for this view. Valid over-scroll modes are
16041     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16042     * (allow over-scrolling only if the view content is larger than the container),
16043     * or {@link #OVER_SCROLL_NEVER}.
16044     *
16045     * Setting the over-scroll mode of a view will have an effect only if the
16046     * view is capable of scrolling.
16047     *
16048     * @param overScrollMode The new over-scroll mode for this view.
16049     */
16050    public void setOverScrollMode(int overScrollMode) {
16051        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16052                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16053                overScrollMode != OVER_SCROLL_NEVER) {
16054            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16055        }
16056        mOverScrollMode = overScrollMode;
16057    }
16058
16059    /**
16060     * Gets a scale factor that determines the distance the view should scroll
16061     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16062     * @return The vertical scroll scale factor.
16063     * @hide
16064     */
16065    protected float getVerticalScrollFactor() {
16066        if (mVerticalScrollFactor == 0) {
16067            TypedValue outValue = new TypedValue();
16068            if (!mContext.getTheme().resolveAttribute(
16069                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16070                throw new IllegalStateException(
16071                        "Expected theme to define listPreferredItemHeight.");
16072            }
16073            mVerticalScrollFactor = outValue.getDimension(
16074                    mContext.getResources().getDisplayMetrics());
16075        }
16076        return mVerticalScrollFactor;
16077    }
16078
16079    /**
16080     * Gets a scale factor that determines the distance the view should scroll
16081     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16082     * @return The horizontal scroll scale factor.
16083     * @hide
16084     */
16085    protected float getHorizontalScrollFactor() {
16086        // TODO: Should use something else.
16087        return getVerticalScrollFactor();
16088    }
16089
16090    /**
16091     * Return the value specifying the text direction or policy that was set with
16092     * {@link #setTextDirection(int)}.
16093     *
16094     * @return the defined text direction. It can be one of:
16095     *
16096     * {@link #TEXT_DIRECTION_INHERIT},
16097     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16098     * {@link #TEXT_DIRECTION_ANY_RTL},
16099     * {@link #TEXT_DIRECTION_LTR},
16100     * {@link #TEXT_DIRECTION_RTL},
16101     * {@link #TEXT_DIRECTION_LOCALE}
16102     */
16103    @ViewDebug.ExportedProperty(category = "text", mapping = {
16104            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16105            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16106            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16107            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16108            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16109            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16110    })
16111    public int getTextDirection() {
16112        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16113    }
16114
16115    /**
16116     * Set the text direction.
16117     *
16118     * @param textDirection the direction to set. Should be one of:
16119     *
16120     * {@link #TEXT_DIRECTION_INHERIT},
16121     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16122     * {@link #TEXT_DIRECTION_ANY_RTL},
16123     * {@link #TEXT_DIRECTION_LTR},
16124     * {@link #TEXT_DIRECTION_RTL},
16125     * {@link #TEXT_DIRECTION_LOCALE}
16126     */
16127    public void setTextDirection(int textDirection) {
16128        if (getTextDirection() != textDirection) {
16129            // Reset the current text direction and the resolved one
16130            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16131            resetResolvedTextDirection();
16132            // Set the new text direction
16133            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16134            // Refresh
16135            requestLayout();
16136            invalidate(true);
16137        }
16138    }
16139
16140    /**
16141     * Return the resolved text direction.
16142     *
16143     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16144     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16145     * up the parent chain of the view. if there is no parent, then it will return the default
16146     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16147     *
16148     * @return the resolved text direction. Returns one of:
16149     *
16150     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16151     * {@link #TEXT_DIRECTION_ANY_RTL},
16152     * {@link #TEXT_DIRECTION_LTR},
16153     * {@link #TEXT_DIRECTION_RTL},
16154     * {@link #TEXT_DIRECTION_LOCALE}
16155     */
16156    public int getResolvedTextDirection() {
16157        // The text direction will be resolved only if needed
16158        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16159            resolveTextDirection();
16160        }
16161        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16162    }
16163
16164    /**
16165     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16166     * resolution is done.
16167     */
16168    public void resolveTextDirection() {
16169        // Reset any previous text direction resolution
16170        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16171
16172        if (hasRtlSupport()) {
16173            // Set resolved text direction flag depending on text direction flag
16174            final int textDirection = getTextDirection();
16175            switch(textDirection) {
16176                case TEXT_DIRECTION_INHERIT:
16177                    if (canResolveTextDirection()) {
16178                        ViewGroup viewGroup = ((ViewGroup) mParent);
16179
16180                        // Set current resolved direction to the same value as the parent's one
16181                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16182                        switch (parentResolvedDirection) {
16183                            case TEXT_DIRECTION_FIRST_STRONG:
16184                            case TEXT_DIRECTION_ANY_RTL:
16185                            case TEXT_DIRECTION_LTR:
16186                            case TEXT_DIRECTION_RTL:
16187                            case TEXT_DIRECTION_LOCALE:
16188                                mPrivateFlags2 |=
16189                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16190                                break;
16191                            default:
16192                                // Default resolved direction is "first strong" heuristic
16193                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16194                        }
16195                    } else {
16196                        // We cannot do the resolution if there is no parent, so use the default one
16197                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16198                    }
16199                    break;
16200                case TEXT_DIRECTION_FIRST_STRONG:
16201                case TEXT_DIRECTION_ANY_RTL:
16202                case TEXT_DIRECTION_LTR:
16203                case TEXT_DIRECTION_RTL:
16204                case TEXT_DIRECTION_LOCALE:
16205                    // Resolved direction is the same as text direction
16206                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16207                    break;
16208                default:
16209                    // Default resolved direction is "first strong" heuristic
16210                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16211            }
16212        } else {
16213            // Default resolved direction is "first strong" heuristic
16214            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16215        }
16216
16217        // Set to resolved
16218        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16219        onResolvedTextDirectionChanged();
16220    }
16221
16222    /**
16223     * Called when text direction has been resolved. Subclasses that care about text direction
16224     * resolution should override this method.
16225     *
16226     * The default implementation does nothing.
16227     */
16228    public void onResolvedTextDirectionChanged() {
16229    }
16230
16231    /**
16232     * Check if text direction resolution can be done.
16233     *
16234     * @return true if text direction resolution can be done otherwise return false.
16235     */
16236    public boolean canResolveTextDirection() {
16237        switch (getTextDirection()) {
16238            case TEXT_DIRECTION_INHERIT:
16239                return (mParent != null) && (mParent instanceof ViewGroup);
16240            default:
16241                return true;
16242        }
16243    }
16244
16245    /**
16246     * Reset resolved text direction. Text direction can be resolved with a call to
16247     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16248     * reset is done.
16249     */
16250    public void resetResolvedTextDirection() {
16251        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16252        onResolvedTextDirectionReset();
16253    }
16254
16255    /**
16256     * Called when text direction is reset. Subclasses that care about text direction reset should
16257     * override this method and do a reset of the text direction of their children. The default
16258     * implementation does nothing.
16259     */
16260    public void onResolvedTextDirectionReset() {
16261    }
16262
16263    /**
16264     * Return the value specifying the text alignment or policy that was set with
16265     * {@link #setTextAlignment(int)}.
16266     *
16267     * @return the defined text alignment. It can be one of:
16268     *
16269     * {@link #TEXT_ALIGNMENT_INHERIT},
16270     * {@link #TEXT_ALIGNMENT_GRAVITY},
16271     * {@link #TEXT_ALIGNMENT_CENTER},
16272     * {@link #TEXT_ALIGNMENT_TEXT_START},
16273     * {@link #TEXT_ALIGNMENT_TEXT_END},
16274     * {@link #TEXT_ALIGNMENT_VIEW_START},
16275     * {@link #TEXT_ALIGNMENT_VIEW_END}
16276     */
16277    @ViewDebug.ExportedProperty(category = "text", mapping = {
16278            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16279            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16280            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16281            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16282            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16283            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16284            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16285    })
16286    public int getTextAlignment() {
16287        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16288    }
16289
16290    /**
16291     * Set the text alignment.
16292     *
16293     * @param textAlignment The text alignment to set. Should be one of
16294     *
16295     * {@link #TEXT_ALIGNMENT_INHERIT},
16296     * {@link #TEXT_ALIGNMENT_GRAVITY},
16297     * {@link #TEXT_ALIGNMENT_CENTER},
16298     * {@link #TEXT_ALIGNMENT_TEXT_START},
16299     * {@link #TEXT_ALIGNMENT_TEXT_END},
16300     * {@link #TEXT_ALIGNMENT_VIEW_START},
16301     * {@link #TEXT_ALIGNMENT_VIEW_END}
16302     *
16303     * @attr ref android.R.styleable#View_textAlignment
16304     */
16305    public void setTextAlignment(int textAlignment) {
16306        if (textAlignment != getTextAlignment()) {
16307            // Reset the current and resolved text alignment
16308            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16309            resetResolvedTextAlignment();
16310            // Set the new text alignment
16311            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16312            // Refresh
16313            requestLayout();
16314            invalidate(true);
16315        }
16316    }
16317
16318    /**
16319     * Return the resolved text alignment.
16320     *
16321     * The resolved text alignment. This needs resolution if the value is
16322     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16323     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16324     *
16325     * @return the resolved text alignment. Returns one of:
16326     *
16327     * {@link #TEXT_ALIGNMENT_GRAVITY},
16328     * {@link #TEXT_ALIGNMENT_CENTER},
16329     * {@link #TEXT_ALIGNMENT_TEXT_START},
16330     * {@link #TEXT_ALIGNMENT_TEXT_END},
16331     * {@link #TEXT_ALIGNMENT_VIEW_START},
16332     * {@link #TEXT_ALIGNMENT_VIEW_END}
16333     */
16334    @ViewDebug.ExportedProperty(category = "text", mapping = {
16335            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16336            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16337            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16338            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16339            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16340            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16341            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16342    })
16343    public int getResolvedTextAlignment() {
16344        // If text alignment is not resolved, then resolve it
16345        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16346            resolveTextAlignment();
16347        }
16348        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16349    }
16350
16351    /**
16352     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16353     * resolution is done.
16354     */
16355    public void resolveTextAlignment() {
16356        // Reset any previous text alignment resolution
16357        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16358
16359        if (hasRtlSupport()) {
16360            // Set resolved text alignment flag depending on text alignment flag
16361            final int textAlignment = getTextAlignment();
16362            switch (textAlignment) {
16363                case TEXT_ALIGNMENT_INHERIT:
16364                    // Check if we can resolve the text alignment
16365                    if (canResolveLayoutDirection() && mParent instanceof View) {
16366                        View view = (View) mParent;
16367
16368                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16369                        switch (parentResolvedTextAlignment) {
16370                            case TEXT_ALIGNMENT_GRAVITY:
16371                            case TEXT_ALIGNMENT_TEXT_START:
16372                            case TEXT_ALIGNMENT_TEXT_END:
16373                            case TEXT_ALIGNMENT_CENTER:
16374                            case TEXT_ALIGNMENT_VIEW_START:
16375                            case TEXT_ALIGNMENT_VIEW_END:
16376                                // Resolved text alignment is the same as the parent resolved
16377                                // text alignment
16378                                mPrivateFlags2 |=
16379                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16380                                break;
16381                            default:
16382                                // Use default resolved text alignment
16383                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16384                        }
16385                    }
16386                    else {
16387                        // We cannot do the resolution if there is no parent so use the default
16388                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16389                    }
16390                    break;
16391                case TEXT_ALIGNMENT_GRAVITY:
16392                case TEXT_ALIGNMENT_TEXT_START:
16393                case TEXT_ALIGNMENT_TEXT_END:
16394                case TEXT_ALIGNMENT_CENTER:
16395                case TEXT_ALIGNMENT_VIEW_START:
16396                case TEXT_ALIGNMENT_VIEW_END:
16397                    // Resolved text alignment is the same as text alignment
16398                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16399                    break;
16400                default:
16401                    // Use default resolved text alignment
16402                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16403            }
16404        } else {
16405            // Use default resolved text alignment
16406            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16407        }
16408
16409        // Set the resolved
16410        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16411        onResolvedTextAlignmentChanged();
16412    }
16413
16414    /**
16415     * Check if text alignment resolution can be done.
16416     *
16417     * @return true if text alignment resolution can be done otherwise return false.
16418     */
16419    public boolean canResolveTextAlignment() {
16420        switch (getTextAlignment()) {
16421            case TEXT_DIRECTION_INHERIT:
16422                return (mParent != null);
16423            default:
16424                return true;
16425        }
16426    }
16427
16428    /**
16429     * Called when text alignment has been resolved. Subclasses that care about text alignment
16430     * resolution should override this method.
16431     *
16432     * The default implementation does nothing.
16433     */
16434    public void onResolvedTextAlignmentChanged() {
16435    }
16436
16437    /**
16438     * Reset resolved text alignment. Text alignment can be resolved with a call to
16439     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16440     * reset is done.
16441     */
16442    public void resetResolvedTextAlignment() {
16443        // Reset any previous text alignment resolution
16444        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16445        onResolvedTextAlignmentReset();
16446    }
16447
16448    /**
16449     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16450     * override this method and do a reset of the text alignment of their children. The default
16451     * implementation does nothing.
16452     */
16453    public void onResolvedTextAlignmentReset() {
16454    }
16455
16456    //
16457    // Properties
16458    //
16459    /**
16460     * A Property wrapper around the <code>alpha</code> functionality handled by the
16461     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16462     */
16463    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16464        @Override
16465        public void setValue(View object, float value) {
16466            object.setAlpha(value);
16467        }
16468
16469        @Override
16470        public Float get(View object) {
16471            return object.getAlpha();
16472        }
16473    };
16474
16475    /**
16476     * A Property wrapper around the <code>translationX</code> functionality handled by the
16477     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16478     */
16479    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16480        @Override
16481        public void setValue(View object, float value) {
16482            object.setTranslationX(value);
16483        }
16484
16485                @Override
16486        public Float get(View object) {
16487            return object.getTranslationX();
16488        }
16489    };
16490
16491    /**
16492     * A Property wrapper around the <code>translationY</code> functionality handled by the
16493     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16494     */
16495    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16496        @Override
16497        public void setValue(View object, float value) {
16498            object.setTranslationY(value);
16499        }
16500
16501        @Override
16502        public Float get(View object) {
16503            return object.getTranslationY();
16504        }
16505    };
16506
16507    /**
16508     * A Property wrapper around the <code>x</code> functionality handled by the
16509     * {@link View#setX(float)} and {@link View#getX()} methods.
16510     */
16511    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16512        @Override
16513        public void setValue(View object, float value) {
16514            object.setX(value);
16515        }
16516
16517        @Override
16518        public Float get(View object) {
16519            return object.getX();
16520        }
16521    };
16522
16523    /**
16524     * A Property wrapper around the <code>y</code> functionality handled by the
16525     * {@link View#setY(float)} and {@link View#getY()} methods.
16526     */
16527    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16528        @Override
16529        public void setValue(View object, float value) {
16530            object.setY(value);
16531        }
16532
16533        @Override
16534        public Float get(View object) {
16535            return object.getY();
16536        }
16537    };
16538
16539    /**
16540     * A Property wrapper around the <code>rotation</code> functionality handled by the
16541     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16542     */
16543    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16544        @Override
16545        public void setValue(View object, float value) {
16546            object.setRotation(value);
16547        }
16548
16549        @Override
16550        public Float get(View object) {
16551            return object.getRotation();
16552        }
16553    };
16554
16555    /**
16556     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16557     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16558     */
16559    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16560        @Override
16561        public void setValue(View object, float value) {
16562            object.setRotationX(value);
16563        }
16564
16565        @Override
16566        public Float get(View object) {
16567            return object.getRotationX();
16568        }
16569    };
16570
16571    /**
16572     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16573     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16574     */
16575    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16576        @Override
16577        public void setValue(View object, float value) {
16578            object.setRotationY(value);
16579        }
16580
16581        @Override
16582        public Float get(View object) {
16583            return object.getRotationY();
16584        }
16585    };
16586
16587    /**
16588     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16589     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16590     */
16591    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16592        @Override
16593        public void setValue(View object, float value) {
16594            object.setScaleX(value);
16595        }
16596
16597        @Override
16598        public Float get(View object) {
16599            return object.getScaleX();
16600        }
16601    };
16602
16603    /**
16604     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16605     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16606     */
16607    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16608        @Override
16609        public void setValue(View object, float value) {
16610            object.setScaleY(value);
16611        }
16612
16613        @Override
16614        public Float get(View object) {
16615            return object.getScaleY();
16616        }
16617    };
16618
16619    /**
16620     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16621     * Each MeasureSpec represents a requirement for either the width or the height.
16622     * A MeasureSpec is comprised of a size and a mode. There are three possible
16623     * modes:
16624     * <dl>
16625     * <dt>UNSPECIFIED</dt>
16626     * <dd>
16627     * The parent has not imposed any constraint on the child. It can be whatever size
16628     * it wants.
16629     * </dd>
16630     *
16631     * <dt>EXACTLY</dt>
16632     * <dd>
16633     * The parent has determined an exact size for the child. The child is going to be
16634     * given those bounds regardless of how big it wants to be.
16635     * </dd>
16636     *
16637     * <dt>AT_MOST</dt>
16638     * <dd>
16639     * The child can be as large as it wants up to the specified size.
16640     * </dd>
16641     * </dl>
16642     *
16643     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16644     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16645     */
16646    public static class MeasureSpec {
16647        private static final int MODE_SHIFT = 30;
16648        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16649
16650        /**
16651         * Measure specification mode: The parent has not imposed any constraint
16652         * on the child. It can be whatever size it wants.
16653         */
16654        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16655
16656        /**
16657         * Measure specification mode: The parent has determined an exact size
16658         * for the child. The child is going to be given those bounds regardless
16659         * of how big it wants to be.
16660         */
16661        public static final int EXACTLY     = 1 << MODE_SHIFT;
16662
16663        /**
16664         * Measure specification mode: The child can be as large as it wants up
16665         * to the specified size.
16666         */
16667        public static final int AT_MOST     = 2 << MODE_SHIFT;
16668
16669        /**
16670         * Creates a measure specification based on the supplied size and mode.
16671         *
16672         * The mode must always be one of the following:
16673         * <ul>
16674         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16675         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16676         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16677         * </ul>
16678         *
16679         * @param size the size of the measure specification
16680         * @param mode the mode of the measure specification
16681         * @return the measure specification based on size and mode
16682         */
16683        public static int makeMeasureSpec(int size, int mode) {
16684            return size + mode;
16685        }
16686
16687        /**
16688         * Extracts the mode from the supplied measure specification.
16689         *
16690         * @param measureSpec the measure specification to extract the mode from
16691         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16692         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16693         *         {@link android.view.View.MeasureSpec#EXACTLY}
16694         */
16695        public static int getMode(int measureSpec) {
16696            return (measureSpec & MODE_MASK);
16697        }
16698
16699        /**
16700         * Extracts the size from the supplied measure specification.
16701         *
16702         * @param measureSpec the measure specification to extract the size from
16703         * @return the size in pixels defined in the supplied measure specification
16704         */
16705        public static int getSize(int measureSpec) {
16706            return (measureSpec & ~MODE_MASK);
16707        }
16708
16709        /**
16710         * Returns a String representation of the specified measure
16711         * specification.
16712         *
16713         * @param measureSpec the measure specification to convert to a String
16714         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16715         */
16716        public static String toString(int measureSpec) {
16717            int mode = getMode(measureSpec);
16718            int size = getSize(measureSpec);
16719
16720            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16721
16722            if (mode == UNSPECIFIED)
16723                sb.append("UNSPECIFIED ");
16724            else if (mode == EXACTLY)
16725                sb.append("EXACTLY ");
16726            else if (mode == AT_MOST)
16727                sb.append("AT_MOST ");
16728            else
16729                sb.append(mode).append(" ");
16730
16731            sb.append(size);
16732            return sb.toString();
16733        }
16734    }
16735
16736    class CheckForLongPress implements Runnable {
16737
16738        private int mOriginalWindowAttachCount;
16739
16740        public void run() {
16741            if (isPressed() && (mParent != null)
16742                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16743                if (performLongClick()) {
16744                    mHasPerformedLongPress = true;
16745                }
16746            }
16747        }
16748
16749        public void rememberWindowAttachCount() {
16750            mOriginalWindowAttachCount = mWindowAttachCount;
16751        }
16752    }
16753
16754    private final class CheckForTap implements Runnable {
16755        public void run() {
16756            mPrivateFlags &= ~PREPRESSED;
16757            setPressed(true);
16758            checkForLongClick(ViewConfiguration.getTapTimeout());
16759        }
16760    }
16761
16762    private final class PerformClick implements Runnable {
16763        public void run() {
16764            performClick();
16765        }
16766    }
16767
16768    /** @hide */
16769    public void hackTurnOffWindowResizeAnim(boolean off) {
16770        mAttachInfo.mTurnOffWindowResizeAnim = off;
16771    }
16772
16773    /**
16774     * This method returns a ViewPropertyAnimator object, which can be used to animate
16775     * specific properties on this View.
16776     *
16777     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16778     */
16779    public ViewPropertyAnimator animate() {
16780        if (mAnimator == null) {
16781            mAnimator = new ViewPropertyAnimator(this);
16782        }
16783        return mAnimator;
16784    }
16785
16786    /**
16787     * Interface definition for a callback to be invoked when a hardware key event is
16788     * dispatched to this view. The callback will be invoked before the key event is
16789     * given to the view. This is only useful for hardware keyboards; a software input
16790     * method has no obligation to trigger this listener.
16791     */
16792    public interface OnKeyListener {
16793        /**
16794         * Called when a hardware key is dispatched to a view. This allows listeners to
16795         * get a chance to respond before the target view.
16796         * <p>Key presses in software keyboards will generally NOT trigger this method,
16797         * although some may elect to do so in some situations. Do not assume a
16798         * software input method has to be key-based; even if it is, it may use key presses
16799         * in a different way than you expect, so there is no way to reliably catch soft
16800         * input key presses.
16801         *
16802         * @param v The view the key has been dispatched to.
16803         * @param keyCode The code for the physical key that was pressed
16804         * @param event The KeyEvent object containing full information about
16805         *        the event.
16806         * @return True if the listener has consumed the event, false otherwise.
16807         */
16808        boolean onKey(View v, int keyCode, KeyEvent event);
16809    }
16810
16811    /**
16812     * Interface definition for a callback to be invoked when a touch event is
16813     * dispatched to this view. The callback will be invoked before the touch
16814     * event is given to the view.
16815     */
16816    public interface OnTouchListener {
16817        /**
16818         * Called when a touch event is dispatched to a view. This allows listeners to
16819         * get a chance to respond before the target view.
16820         *
16821         * @param v The view the touch event has been dispatched to.
16822         * @param event The MotionEvent object containing full information about
16823         *        the event.
16824         * @return True if the listener has consumed the event, false otherwise.
16825         */
16826        boolean onTouch(View v, MotionEvent event);
16827    }
16828
16829    /**
16830     * Interface definition for a callback to be invoked when a hover event is
16831     * dispatched to this view. The callback will be invoked before the hover
16832     * event is given to the view.
16833     */
16834    public interface OnHoverListener {
16835        /**
16836         * Called when a hover event is dispatched to a view. This allows listeners to
16837         * get a chance to respond before the target view.
16838         *
16839         * @param v The view the hover event has been dispatched to.
16840         * @param event The MotionEvent object containing full information about
16841         *        the event.
16842         * @return True if the listener has consumed the event, false otherwise.
16843         */
16844        boolean onHover(View v, MotionEvent event);
16845    }
16846
16847    /**
16848     * Interface definition for a callback to be invoked when a generic motion event is
16849     * dispatched to this view. The callback will be invoked before the generic motion
16850     * event is given to the view.
16851     */
16852    public interface OnGenericMotionListener {
16853        /**
16854         * Called when a generic motion event is dispatched to a view. This allows listeners to
16855         * get a chance to respond before the target view.
16856         *
16857         * @param v The view the generic motion event has been dispatched to.
16858         * @param event The MotionEvent object containing full information about
16859         *        the event.
16860         * @return True if the listener has consumed the event, false otherwise.
16861         */
16862        boolean onGenericMotion(View v, MotionEvent event);
16863    }
16864
16865    /**
16866     * Interface definition for a callback to be invoked when a view has been clicked and held.
16867     */
16868    public interface OnLongClickListener {
16869        /**
16870         * Called when a view has been clicked and held.
16871         *
16872         * @param v The view that was clicked and held.
16873         *
16874         * @return true if the callback consumed the long click, false otherwise.
16875         */
16876        boolean onLongClick(View v);
16877    }
16878
16879    /**
16880     * Interface definition for a callback to be invoked when a drag is being dispatched
16881     * to this view.  The callback will be invoked before the hosting view's own
16882     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16883     * onDrag(event) behavior, it should return 'false' from this callback.
16884     *
16885     * <div class="special reference">
16886     * <h3>Developer Guides</h3>
16887     * <p>For a guide to implementing drag and drop features, read the
16888     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16889     * </div>
16890     */
16891    public interface OnDragListener {
16892        /**
16893         * Called when a drag event is dispatched to a view. This allows listeners
16894         * to get a chance to override base View behavior.
16895         *
16896         * @param v The View that received the drag event.
16897         * @param event The {@link android.view.DragEvent} object for the drag event.
16898         * @return {@code true} if the drag event was handled successfully, or {@code false}
16899         * if the drag event was not handled. Note that {@code false} will trigger the View
16900         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16901         */
16902        boolean onDrag(View v, DragEvent event);
16903    }
16904
16905    /**
16906     * Interface definition for a callback to be invoked when the focus state of
16907     * a view changed.
16908     */
16909    public interface OnFocusChangeListener {
16910        /**
16911         * Called when the focus state of a view has changed.
16912         *
16913         * @param v The view whose state has changed.
16914         * @param hasFocus The new focus state of v.
16915         */
16916        void onFocusChange(View v, boolean hasFocus);
16917    }
16918
16919    /**
16920     * Interface definition for a callback to be invoked when a view is clicked.
16921     */
16922    public interface OnClickListener {
16923        /**
16924         * Called when a view has been clicked.
16925         *
16926         * @param v The view that was clicked.
16927         */
16928        void onClick(View v);
16929    }
16930
16931    /**
16932     * Interface definition for a callback to be invoked when the context menu
16933     * for this view is being built.
16934     */
16935    public interface OnCreateContextMenuListener {
16936        /**
16937         * Called when the context menu for this view is being built. It is not
16938         * safe to hold onto the menu after this method returns.
16939         *
16940         * @param menu The context menu that is being built
16941         * @param v The view for which the context menu is being built
16942         * @param menuInfo Extra information about the item for which the
16943         *            context menu should be shown. This information will vary
16944         *            depending on the class of v.
16945         */
16946        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16947    }
16948
16949    /**
16950     * Interface definition for a callback to be invoked when the status bar changes
16951     * visibility.  This reports <strong>global</strong> changes to the system UI
16952     * state, not what the application is requesting.
16953     *
16954     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16955     */
16956    public interface OnSystemUiVisibilityChangeListener {
16957        /**
16958         * Called when the status bar changes visibility because of a call to
16959         * {@link View#setSystemUiVisibility(int)}.
16960         *
16961         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16962         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
16963         * This tells you the <strong>global</strong> state of these UI visibility
16964         * flags, not what your app is currently applying.
16965         */
16966        public void onSystemUiVisibilityChange(int visibility);
16967    }
16968
16969    /**
16970     * Interface definition for a callback to be invoked when this view is attached
16971     * or detached from its window.
16972     */
16973    public interface OnAttachStateChangeListener {
16974        /**
16975         * Called when the view is attached to a window.
16976         * @param v The view that was attached
16977         */
16978        public void onViewAttachedToWindow(View v);
16979        /**
16980         * Called when the view is detached from a window.
16981         * @param v The view that was detached
16982         */
16983        public void onViewDetachedFromWindow(View v);
16984    }
16985
16986    private final class UnsetPressedState implements Runnable {
16987        public void run() {
16988            setPressed(false);
16989        }
16990    }
16991
16992    /**
16993     * Base class for derived classes that want to save and restore their own
16994     * state in {@link android.view.View#onSaveInstanceState()}.
16995     */
16996    public static class BaseSavedState extends AbsSavedState {
16997        /**
16998         * Constructor used when reading from a parcel. Reads the state of the superclass.
16999         *
17000         * @param source
17001         */
17002        public BaseSavedState(Parcel source) {
17003            super(source);
17004        }
17005
17006        /**
17007         * Constructor called by derived classes when creating their SavedState objects
17008         *
17009         * @param superState The state of the superclass of this view
17010         */
17011        public BaseSavedState(Parcelable superState) {
17012            super(superState);
17013        }
17014
17015        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17016                new Parcelable.Creator<BaseSavedState>() {
17017            public BaseSavedState createFromParcel(Parcel in) {
17018                return new BaseSavedState(in);
17019            }
17020
17021            public BaseSavedState[] newArray(int size) {
17022                return new BaseSavedState[size];
17023            }
17024        };
17025    }
17026
17027    /**
17028     * A set of information given to a view when it is attached to its parent
17029     * window.
17030     */
17031    static class AttachInfo {
17032        interface Callbacks {
17033            void playSoundEffect(int effectId);
17034            boolean performHapticFeedback(int effectId, boolean always);
17035        }
17036
17037        /**
17038         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17039         * to a Handler. This class contains the target (View) to invalidate and
17040         * the coordinates of the dirty rectangle.
17041         *
17042         * For performance purposes, this class also implements a pool of up to
17043         * POOL_LIMIT objects that get reused. This reduces memory allocations
17044         * whenever possible.
17045         */
17046        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17047            private static final int POOL_LIMIT = 10;
17048            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17049                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17050                        public InvalidateInfo newInstance() {
17051                            return new InvalidateInfo();
17052                        }
17053
17054                        public void onAcquired(InvalidateInfo element) {
17055                        }
17056
17057                        public void onReleased(InvalidateInfo element) {
17058                            element.target = null;
17059                        }
17060                    }, POOL_LIMIT)
17061            );
17062
17063            private InvalidateInfo mNext;
17064            private boolean mIsPooled;
17065
17066            View target;
17067
17068            int left;
17069            int top;
17070            int right;
17071            int bottom;
17072
17073            public void setNextPoolable(InvalidateInfo element) {
17074                mNext = element;
17075            }
17076
17077            public InvalidateInfo getNextPoolable() {
17078                return mNext;
17079            }
17080
17081            static InvalidateInfo acquire() {
17082                return sPool.acquire();
17083            }
17084
17085            void release() {
17086                sPool.release(this);
17087            }
17088
17089            public boolean isPooled() {
17090                return mIsPooled;
17091            }
17092
17093            public void setPooled(boolean isPooled) {
17094                mIsPooled = isPooled;
17095            }
17096        }
17097
17098        final IWindowSession mSession;
17099
17100        final IWindow mWindow;
17101
17102        final IBinder mWindowToken;
17103
17104        final Callbacks mRootCallbacks;
17105
17106        HardwareCanvas mHardwareCanvas;
17107
17108        /**
17109         * The top view of the hierarchy.
17110         */
17111        View mRootView;
17112
17113        IBinder mPanelParentWindowToken;
17114        Surface mSurface;
17115
17116        boolean mHardwareAccelerated;
17117        boolean mHardwareAccelerationRequested;
17118        HardwareRenderer mHardwareRenderer;
17119
17120        boolean mScreenOn;
17121
17122        /**
17123         * Scale factor used by the compatibility mode
17124         */
17125        float mApplicationScale;
17126
17127        /**
17128         * Indicates whether the application is in compatibility mode
17129         */
17130        boolean mScalingRequired;
17131
17132        /**
17133         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17134         */
17135        boolean mTurnOffWindowResizeAnim;
17136
17137        /**
17138         * Left position of this view's window
17139         */
17140        int mWindowLeft;
17141
17142        /**
17143         * Top position of this view's window
17144         */
17145        int mWindowTop;
17146
17147        /**
17148         * Left actual position of this view's window.
17149         *
17150         * TODO: This is a workaround for 6623031. Remove when fixed.
17151         */
17152        int mActualWindowLeft;
17153
17154        /**
17155         * Actual top position of this view's window.
17156         *
17157         * TODO: This is a workaround for 6623031. Remove when fixed.
17158         */
17159        int mActualWindowTop;
17160
17161        /**
17162         * Indicates whether views need to use 32-bit drawing caches
17163         */
17164        boolean mUse32BitDrawingCache;
17165
17166        /**
17167         * For windows that are full-screen but using insets to layout inside
17168         * of the screen decorations, these are the current insets for the
17169         * content of the window.
17170         */
17171        final Rect mContentInsets = new Rect();
17172
17173        /**
17174         * For windows that are full-screen but using insets to layout inside
17175         * of the screen decorations, these are the current insets for the
17176         * actual visible parts of the window.
17177         */
17178        final Rect mVisibleInsets = new Rect();
17179
17180        /**
17181         * The internal insets given by this window.  This value is
17182         * supplied by the client (through
17183         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17184         * be given to the window manager when changed to be used in laying
17185         * out windows behind it.
17186         */
17187        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17188                = new ViewTreeObserver.InternalInsetsInfo();
17189
17190        /**
17191         * All views in the window's hierarchy that serve as scroll containers,
17192         * used to determine if the window can be resized or must be panned
17193         * to adjust for a soft input area.
17194         */
17195        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17196
17197        final KeyEvent.DispatcherState mKeyDispatchState
17198                = new KeyEvent.DispatcherState();
17199
17200        /**
17201         * Indicates whether the view's window currently has the focus.
17202         */
17203        boolean mHasWindowFocus;
17204
17205        /**
17206         * The current visibility of the window.
17207         */
17208        int mWindowVisibility;
17209
17210        /**
17211         * Indicates the time at which drawing started to occur.
17212         */
17213        long mDrawingTime;
17214
17215        /**
17216         * Indicates whether or not ignoring the DIRTY_MASK flags.
17217         */
17218        boolean mIgnoreDirtyState;
17219
17220        /**
17221         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17222         * to avoid clearing that flag prematurely.
17223         */
17224        boolean mSetIgnoreDirtyState = false;
17225
17226        /**
17227         * Indicates whether the view's window is currently in touch mode.
17228         */
17229        boolean mInTouchMode;
17230
17231        /**
17232         * Indicates that ViewAncestor should trigger a global layout change
17233         * the next time it performs a traversal
17234         */
17235        boolean mRecomputeGlobalAttributes;
17236
17237        /**
17238         * Always report new attributes at next traversal.
17239         */
17240        boolean mForceReportNewAttributes;
17241
17242        /**
17243         * Set during a traveral if any views want to keep the screen on.
17244         */
17245        boolean mKeepScreenOn;
17246
17247        /**
17248         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17249         */
17250        int mSystemUiVisibility;
17251
17252        /**
17253         * Hack to force certain system UI visibility flags to be cleared.
17254         */
17255        int mDisabledSystemUiVisibility;
17256
17257        /**
17258         * Last global system UI visibility reported by the window manager.
17259         */
17260        int mGlobalSystemUiVisibility;
17261
17262        /**
17263         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17264         * attached.
17265         */
17266        boolean mHasSystemUiListeners;
17267
17268        /**
17269         * Set if the visibility of any views has changed.
17270         */
17271        boolean mViewVisibilityChanged;
17272
17273        /**
17274         * Set to true if a view has been scrolled.
17275         */
17276        boolean mViewScrollChanged;
17277
17278        /**
17279         * Global to the view hierarchy used as a temporary for dealing with
17280         * x/y points in the transparent region computations.
17281         */
17282        final int[] mTransparentLocation = new int[2];
17283
17284        /**
17285         * Global to the view hierarchy used as a temporary for dealing with
17286         * x/y points in the ViewGroup.invalidateChild implementation.
17287         */
17288        final int[] mInvalidateChildLocation = new int[2];
17289
17290
17291        /**
17292         * Global to the view hierarchy used as a temporary for dealing with
17293         * x/y location when view is transformed.
17294         */
17295        final float[] mTmpTransformLocation = new float[2];
17296
17297        /**
17298         * The view tree observer used to dispatch global events like
17299         * layout, pre-draw, touch mode change, etc.
17300         */
17301        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17302
17303        /**
17304         * A Canvas used by the view hierarchy to perform bitmap caching.
17305         */
17306        Canvas mCanvas;
17307
17308        /**
17309         * The view root impl.
17310         */
17311        final ViewRootImpl mViewRootImpl;
17312
17313        /**
17314         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17315         * handler can be used to pump events in the UI events queue.
17316         */
17317        final Handler mHandler;
17318
17319        /**
17320         * Temporary for use in computing invalidate rectangles while
17321         * calling up the hierarchy.
17322         */
17323        final Rect mTmpInvalRect = new Rect();
17324
17325        /**
17326         * Temporary for use in computing hit areas with transformed views
17327         */
17328        final RectF mTmpTransformRect = new RectF();
17329
17330        /**
17331         * Temporary list for use in collecting focusable descendents of a view.
17332         */
17333        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17334
17335        /**
17336         * The id of the window for accessibility purposes.
17337         */
17338        int mAccessibilityWindowId = View.NO_ID;
17339
17340        /**
17341         * Whether to ingore not exposed for accessibility Views when
17342         * reporting the view tree to accessibility services.
17343         */
17344        boolean mIncludeNotImportantViews;
17345
17346        /**
17347         * The drawable for highlighting accessibility focus.
17348         */
17349        Drawable mAccessibilityFocusDrawable;
17350
17351        /**
17352         * Show where the margins, bounds and layout bounds are for each view.
17353         */
17354        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17355
17356        /**
17357         * Point used to compute visible regions.
17358         */
17359        final Point mPoint = new Point();
17360
17361        /**
17362         * Creates a new set of attachment information with the specified
17363         * events handler and thread.
17364         *
17365         * @param handler the events handler the view must use
17366         */
17367        AttachInfo(IWindowSession session, IWindow window,
17368                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17369            mSession = session;
17370            mWindow = window;
17371            mWindowToken = window.asBinder();
17372            mViewRootImpl = viewRootImpl;
17373            mHandler = handler;
17374            mRootCallbacks = effectPlayer;
17375        }
17376    }
17377
17378    /**
17379     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17380     * is supported. This avoids keeping too many unused fields in most
17381     * instances of View.</p>
17382     */
17383    private static class ScrollabilityCache implements Runnable {
17384
17385        /**
17386         * Scrollbars are not visible
17387         */
17388        public static final int OFF = 0;
17389
17390        /**
17391         * Scrollbars are visible
17392         */
17393        public static final int ON = 1;
17394
17395        /**
17396         * Scrollbars are fading away
17397         */
17398        public static final int FADING = 2;
17399
17400        public boolean fadeScrollBars;
17401
17402        public int fadingEdgeLength;
17403        public int scrollBarDefaultDelayBeforeFade;
17404        public int scrollBarFadeDuration;
17405
17406        public int scrollBarSize;
17407        public ScrollBarDrawable scrollBar;
17408        public float[] interpolatorValues;
17409        public View host;
17410
17411        public final Paint paint;
17412        public final Matrix matrix;
17413        public Shader shader;
17414
17415        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17416
17417        private static final float[] OPAQUE = { 255 };
17418        private static final float[] TRANSPARENT = { 0.0f };
17419
17420        /**
17421         * When fading should start. This time moves into the future every time
17422         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17423         */
17424        public long fadeStartTime;
17425
17426
17427        /**
17428         * The current state of the scrollbars: ON, OFF, or FADING
17429         */
17430        public int state = OFF;
17431
17432        private int mLastColor;
17433
17434        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17435            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17436            scrollBarSize = configuration.getScaledScrollBarSize();
17437            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17438            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17439
17440            paint = new Paint();
17441            matrix = new Matrix();
17442            // use use a height of 1, and then wack the matrix each time we
17443            // actually use it.
17444            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17445
17446            paint.setShader(shader);
17447            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17448            this.host = host;
17449        }
17450
17451        public void setFadeColor(int color) {
17452            if (color != 0 && color != mLastColor) {
17453                mLastColor = color;
17454                color |= 0xFF000000;
17455
17456                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17457                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17458
17459                paint.setShader(shader);
17460                // Restore the default transfer mode (src_over)
17461                paint.setXfermode(null);
17462            }
17463        }
17464
17465        public void run() {
17466            long now = AnimationUtils.currentAnimationTimeMillis();
17467            if (now >= fadeStartTime) {
17468
17469                // the animation fades the scrollbars out by changing
17470                // the opacity (alpha) from fully opaque to fully
17471                // transparent
17472                int nextFrame = (int) now;
17473                int framesCount = 0;
17474
17475                Interpolator interpolator = scrollBarInterpolator;
17476
17477                // Start opaque
17478                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17479
17480                // End transparent
17481                nextFrame += scrollBarFadeDuration;
17482                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17483
17484                state = FADING;
17485
17486                // Kick off the fade animation
17487                host.invalidate(true);
17488            }
17489        }
17490    }
17491
17492    /**
17493     * Resuable callback for sending
17494     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17495     */
17496    private class SendViewScrolledAccessibilityEvent implements Runnable {
17497        public volatile boolean mIsPending;
17498
17499        public void run() {
17500            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17501            mIsPending = false;
17502        }
17503    }
17504
17505    /**
17506     * <p>
17507     * This class represents a delegate that can be registered in a {@link View}
17508     * to enhance accessibility support via composition rather via inheritance.
17509     * It is specifically targeted to widget developers that extend basic View
17510     * classes i.e. classes in package android.view, that would like their
17511     * applications to be backwards compatible.
17512     * </p>
17513     * <div class="special reference">
17514     * <h3>Developer Guides</h3>
17515     * <p>For more information about making applications accessible, read the
17516     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17517     * developer guide.</p>
17518     * </div>
17519     * <p>
17520     * A scenario in which a developer would like to use an accessibility delegate
17521     * is overriding a method introduced in a later API version then the minimal API
17522     * version supported by the application. For example, the method
17523     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17524     * in API version 4 when the accessibility APIs were first introduced. If a
17525     * developer would like his application to run on API version 4 devices (assuming
17526     * all other APIs used by the application are version 4 or lower) and take advantage
17527     * of this method, instead of overriding the method which would break the application's
17528     * backwards compatibility, he can override the corresponding method in this
17529     * delegate and register the delegate in the target View if the API version of
17530     * the system is high enough i.e. the API version is same or higher to the API
17531     * version that introduced
17532     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17533     * </p>
17534     * <p>
17535     * Here is an example implementation:
17536     * </p>
17537     * <code><pre><p>
17538     * if (Build.VERSION.SDK_INT >= 14) {
17539     *     // If the API version is equal of higher than the version in
17540     *     // which onInitializeAccessibilityNodeInfo was introduced we
17541     *     // register a delegate with a customized implementation.
17542     *     View view = findViewById(R.id.view_id);
17543     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17544     *         public void onInitializeAccessibilityNodeInfo(View host,
17545     *                 AccessibilityNodeInfo info) {
17546     *             // Let the default implementation populate the info.
17547     *             super.onInitializeAccessibilityNodeInfo(host, info);
17548     *             // Set some other information.
17549     *             info.setEnabled(host.isEnabled());
17550     *         }
17551     *     });
17552     * }
17553     * </code></pre></p>
17554     * <p>
17555     * This delegate contains methods that correspond to the accessibility methods
17556     * in View. If a delegate has been specified the implementation in View hands
17557     * off handling to the corresponding method in this delegate. The default
17558     * implementation the delegate methods behaves exactly as the corresponding
17559     * method in View for the case of no accessibility delegate been set. Hence,
17560     * to customize the behavior of a View method, clients can override only the
17561     * corresponding delegate method without altering the behavior of the rest
17562     * accessibility related methods of the host view.
17563     * </p>
17564     */
17565    public static class AccessibilityDelegate {
17566
17567        /**
17568         * Sends an accessibility event of the given type. If accessibility is not
17569         * enabled this method has no effect.
17570         * <p>
17571         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17572         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17573         * been set.
17574         * </p>
17575         *
17576         * @param host The View hosting the delegate.
17577         * @param eventType The type of the event to send.
17578         *
17579         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17580         */
17581        public void sendAccessibilityEvent(View host, int eventType) {
17582            host.sendAccessibilityEventInternal(eventType);
17583        }
17584
17585        /**
17586         * Performs the specified accessibility action on the view. For
17587         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17588         * <p>
17589         * The default implementation behaves as
17590         * {@link View#performAccessibilityAction(int, Bundle)
17591         *  View#performAccessibilityAction(int, Bundle)} for the case of
17592         *  no accessibility delegate been set.
17593         * </p>
17594         *
17595         * @param action The action to perform.
17596         * @return Whether the action was performed.
17597         *
17598         * @see View#performAccessibilityAction(int, Bundle)
17599         *      View#performAccessibilityAction(int, Bundle)
17600         */
17601        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17602            return host.performAccessibilityActionInternal(action, args);
17603        }
17604
17605        /**
17606         * Sends an accessibility event. This method behaves exactly as
17607         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17608         * empty {@link AccessibilityEvent} and does not perform a check whether
17609         * accessibility is enabled.
17610         * <p>
17611         * The default implementation behaves as
17612         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17613         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17614         * the case of no accessibility delegate been set.
17615         * </p>
17616         *
17617         * @param host The View hosting the delegate.
17618         * @param event The event to send.
17619         *
17620         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17621         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17622         */
17623        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17624            host.sendAccessibilityEventUncheckedInternal(event);
17625        }
17626
17627        /**
17628         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17629         * to its children for adding their text content to the event.
17630         * <p>
17631         * The default implementation behaves as
17632         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17633         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17634         * the case of no accessibility delegate been set.
17635         * </p>
17636         *
17637         * @param host The View hosting the delegate.
17638         * @param event The event.
17639         * @return True if the event population was completed.
17640         *
17641         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17642         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17643         */
17644        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17645            return host.dispatchPopulateAccessibilityEventInternal(event);
17646        }
17647
17648        /**
17649         * Gives a chance to the host View to populate the accessibility event with its
17650         * text content.
17651         * <p>
17652         * The default implementation behaves as
17653         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17654         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17655         * the case of no accessibility delegate been set.
17656         * </p>
17657         *
17658         * @param host The View hosting the delegate.
17659         * @param event The accessibility event which to populate.
17660         *
17661         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17662         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17663         */
17664        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17665            host.onPopulateAccessibilityEventInternal(event);
17666        }
17667
17668        /**
17669         * Initializes an {@link AccessibilityEvent} with information about the
17670         * the host View which is the event source.
17671         * <p>
17672         * The default implementation behaves as
17673         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17674         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17675         * the case of no accessibility delegate been set.
17676         * </p>
17677         *
17678         * @param host The View hosting the delegate.
17679         * @param event The event to initialize.
17680         *
17681         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17682         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17683         */
17684        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17685            host.onInitializeAccessibilityEventInternal(event);
17686        }
17687
17688        /**
17689         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17690         * <p>
17691         * The default implementation behaves as
17692         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17693         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17694         * the case of no accessibility delegate been set.
17695         * </p>
17696         *
17697         * @param host The View hosting the delegate.
17698         * @param info The instance to initialize.
17699         *
17700         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17701         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17702         */
17703        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17704            host.onInitializeAccessibilityNodeInfoInternal(info);
17705        }
17706
17707        /**
17708         * Called when a child of the host View has requested sending an
17709         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17710         * to augment the event.
17711         * <p>
17712         * The default implementation behaves as
17713         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17714         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17715         * the case of no accessibility delegate been set.
17716         * </p>
17717         *
17718         * @param host The View hosting the delegate.
17719         * @param child The child which requests sending the event.
17720         * @param event The event to be sent.
17721         * @return True if the event should be sent
17722         *
17723         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17724         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17725         */
17726        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17727                AccessibilityEvent event) {
17728            return host.onRequestSendAccessibilityEventInternal(child, event);
17729        }
17730
17731        /**
17732         * Gets the provider for managing a virtual view hierarchy rooted at this View
17733         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17734         * that explore the window content.
17735         * <p>
17736         * The default implementation behaves as
17737         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17738         * the case of no accessibility delegate been set.
17739         * </p>
17740         *
17741         * @return The provider.
17742         *
17743         * @see AccessibilityNodeProvider
17744         */
17745        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17746            return null;
17747        }
17748    }
17749}
17750