View.java revision 27e2da7c171afa39358bbead18fbe3e6b8ea6637
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()) {
4375            AccessibilityEvent event = AccessibilityEvent.obtain(
4376                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4377            event.getText().add(text);
4378            sendAccessibilityEventUnchecked(event);
4379        }
4380    }
4381
4382    /**
4383     * @see #sendAccessibilityEvent(int)
4384     *
4385     * Note: Called from the default {@link AccessibilityDelegate}.
4386     */
4387    void sendAccessibilityEventInternal(int eventType) {
4388        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4389            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4390        }
4391    }
4392
4393    /**
4394     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4395     * takes as an argument an empty {@link AccessibilityEvent} and does not
4396     * perform a check whether accessibility is enabled.
4397     * <p>
4398     * If an {@link AccessibilityDelegate} has been specified via calling
4399     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4400     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4401     * is responsible for handling this call.
4402     * </p>
4403     *
4404     * @param event The event to send.
4405     *
4406     * @see #sendAccessibilityEvent(int)
4407     */
4408    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4409        if (mAccessibilityDelegate != null) {
4410            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4411        } else {
4412            sendAccessibilityEventUncheckedInternal(event);
4413        }
4414    }
4415
4416    /**
4417     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4418     *
4419     * Note: Called from the default {@link AccessibilityDelegate}.
4420     */
4421    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4422        if (!isShown()) {
4423            return;
4424        }
4425        onInitializeAccessibilityEvent(event);
4426        // Only a subset of accessibility events populates text content.
4427        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4428            dispatchPopulateAccessibilityEvent(event);
4429        }
4430        // In the beginning we called #isShown(), so we know that getParent() is not null.
4431        getParent().requestSendAccessibilityEvent(this, event);
4432    }
4433
4434    /**
4435     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4436     * to its children for adding their text content to the event. Note that the
4437     * event text is populated in a separate dispatch path since we add to the
4438     * event not only the text of the source but also the text of all its descendants.
4439     * A typical implementation will call
4440     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4441     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4442     * on each child. Override this method if custom population of the event text
4443     * content is required.
4444     * <p>
4445     * If an {@link AccessibilityDelegate} has been specified via calling
4446     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4447     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4448     * is responsible for handling this call.
4449     * </p>
4450     * <p>
4451     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4452     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4453     * </p>
4454     *
4455     * @param event The event.
4456     *
4457     * @return True if the event population was completed.
4458     */
4459    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4460        if (mAccessibilityDelegate != null) {
4461            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4462        } else {
4463            return dispatchPopulateAccessibilityEventInternal(event);
4464        }
4465    }
4466
4467    /**
4468     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4469     *
4470     * Note: Called from the default {@link AccessibilityDelegate}.
4471     */
4472    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4473        onPopulateAccessibilityEvent(event);
4474        return false;
4475    }
4476
4477    /**
4478     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4479     * giving a chance to this View to populate the accessibility event with its
4480     * text content. While this method is free to modify event
4481     * attributes other than text content, doing so should normally be performed in
4482     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4483     * <p>
4484     * Example: Adding formatted date string to an accessibility event in addition
4485     *          to the text added by the super implementation:
4486     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4487     *     super.onPopulateAccessibilityEvent(event);
4488     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4489     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4490     *         mCurrentDate.getTimeInMillis(), flags);
4491     *     event.getText().add(selectedDateUtterance);
4492     * }</pre>
4493     * <p>
4494     * If an {@link AccessibilityDelegate} has been specified via calling
4495     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4496     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4497     * is responsible for handling this call.
4498     * </p>
4499     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4500     * information to the event, in case the default implementation has basic information to add.
4501     * </p>
4502     *
4503     * @param event The accessibility event which to populate.
4504     *
4505     * @see #sendAccessibilityEvent(int)
4506     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4507     */
4508    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4509        if (mAccessibilityDelegate != null) {
4510            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4511        } else {
4512            onPopulateAccessibilityEventInternal(event);
4513        }
4514    }
4515
4516    /**
4517     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4518     *
4519     * Note: Called from the default {@link AccessibilityDelegate}.
4520     */
4521    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4522
4523    }
4524
4525    /**
4526     * Initializes an {@link AccessibilityEvent} with information about
4527     * this View which is the event source. In other words, the source of
4528     * an accessibility event is the view whose state change triggered firing
4529     * the event.
4530     * <p>
4531     * Example: Setting the password property of an event in addition
4532     *          to properties set by the super implementation:
4533     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4534     *     super.onInitializeAccessibilityEvent(event);
4535     *     event.setPassword(true);
4536     * }</pre>
4537     * <p>
4538     * If an {@link AccessibilityDelegate} has been specified via calling
4539     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4540     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4541     * is responsible for handling this call.
4542     * </p>
4543     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4544     * information to the event, in case the default implementation has basic information to add.
4545     * </p>
4546     * @param event The event to initialize.
4547     *
4548     * @see #sendAccessibilityEvent(int)
4549     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4550     */
4551    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4552        if (mAccessibilityDelegate != null) {
4553            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4554        } else {
4555            onInitializeAccessibilityEventInternal(event);
4556        }
4557    }
4558
4559    /**
4560     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4561     *
4562     * Note: Called from the default {@link AccessibilityDelegate}.
4563     */
4564    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4565        event.setSource(this);
4566        event.setClassName(View.class.getName());
4567        event.setPackageName(getContext().getPackageName());
4568        event.setEnabled(isEnabled());
4569        event.setContentDescription(mContentDescription);
4570
4571        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4572            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4573            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4574                    FOCUSABLES_ALL);
4575            event.setItemCount(focusablesTempList.size());
4576            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4577            focusablesTempList.clear();
4578        }
4579    }
4580
4581    /**
4582     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4583     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4584     * This method is responsible for obtaining an accessibility node info from a
4585     * pool of reusable instances and calling
4586     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4587     * initialize the former.
4588     * <p>
4589     * Note: The client is responsible for recycling the obtained instance by calling
4590     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4591     * </p>
4592     *
4593     * @return A populated {@link AccessibilityNodeInfo}.
4594     *
4595     * @see AccessibilityNodeInfo
4596     */
4597    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4598        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4599        if (provider != null) {
4600            return provider.createAccessibilityNodeInfo(View.NO_ID);
4601        } else {
4602            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4603            onInitializeAccessibilityNodeInfo(info);
4604            return info;
4605        }
4606    }
4607
4608    /**
4609     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4610     * The base implementation sets:
4611     * <ul>
4612     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4613     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4614     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4615     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4616     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4617     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4618     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4619     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4620     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4621     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4622     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4623     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4624     * </ul>
4625     * <p>
4626     * Subclasses should override this method, call the super implementation,
4627     * and set additional attributes.
4628     * </p>
4629     * <p>
4630     * If an {@link AccessibilityDelegate} has been specified via calling
4631     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4632     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4633     * is responsible for handling this call.
4634     * </p>
4635     *
4636     * @param info The instance to initialize.
4637     */
4638    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4639        if (mAccessibilityDelegate != null) {
4640            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4641        } else {
4642            onInitializeAccessibilityNodeInfoInternal(info);
4643        }
4644    }
4645
4646    /**
4647     * Gets the location of this view in screen coordintates.
4648     *
4649     * @param outRect The output location
4650     */
4651    private void getBoundsOnScreen(Rect outRect) {
4652        if (mAttachInfo == null) {
4653            return;
4654        }
4655
4656        RectF position = mAttachInfo.mTmpTransformRect;
4657        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4658
4659        if (!hasIdentityMatrix()) {
4660            getMatrix().mapRect(position);
4661        }
4662
4663        position.offset(mLeft, mTop);
4664
4665        ViewParent parent = mParent;
4666        while (parent instanceof View) {
4667            View parentView = (View) parent;
4668
4669            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4670
4671            if (!parentView.hasIdentityMatrix()) {
4672                parentView.getMatrix().mapRect(position);
4673            }
4674
4675            position.offset(parentView.mLeft, parentView.mTop);
4676
4677            parent = parentView.mParent;
4678        }
4679
4680        if (parent instanceof ViewRootImpl) {
4681            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4682            position.offset(0, -viewRootImpl.mCurScrollY);
4683        }
4684
4685        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4686
4687        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4688                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4689    }
4690
4691    /**
4692     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4693     *
4694     * Note: Called from the default {@link AccessibilityDelegate}.
4695     */
4696    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4697        Rect bounds = mAttachInfo.mTmpInvalRect;
4698        getDrawingRect(bounds);
4699        info.setBoundsInParent(bounds);
4700
4701        getBoundsOnScreen(bounds);
4702        info.setBoundsInScreen(bounds);
4703
4704        ViewParent parent = getParentForAccessibility();
4705        if (parent instanceof View) {
4706            info.setParent((View) parent);
4707        }
4708
4709        info.setVisibleToUser(isVisibleToUser());
4710
4711        info.setPackageName(mContext.getPackageName());
4712        info.setClassName(View.class.getName());
4713        info.setContentDescription(getContentDescription());
4714
4715        info.setEnabled(isEnabled());
4716        info.setClickable(isClickable());
4717        info.setFocusable(isFocusable());
4718        info.setFocused(isFocused());
4719        info.setAccessibilityFocused(isAccessibilityFocused());
4720        info.setSelected(isSelected());
4721        info.setLongClickable(isLongClickable());
4722
4723        // TODO: These make sense only if we are in an AdapterView but all
4724        // views can be selected. Maybe from accessiiblity perspective
4725        // we should report as selectable view in an AdapterView.
4726        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4727        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4728
4729        if (isFocusable()) {
4730            if (isFocused()) {
4731                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4732            } else {
4733                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4734            }
4735        }
4736
4737        if (!isAccessibilityFocused()) {
4738            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4739        } else {
4740            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4741        }
4742
4743        if (isClickable() && isEnabled()) {
4744            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4745        }
4746
4747        if (isLongClickable() && isEnabled()) {
4748            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4749        }
4750
4751        if (mContentDescription != null && mContentDescription.length() > 0) {
4752            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4753            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4754            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4755                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4756                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4757        }
4758    }
4759
4760    /**
4761     * Returns the delta between the actual and last reported window left.
4762     *
4763     * @hide
4764     */
4765    public int getActualAndReportedWindowLeftDelta() {
4766        if (mAttachInfo != null) {
4767            return mAttachInfo.mActualWindowLeft - mAttachInfo.mWindowLeft;
4768        }
4769        return 0;
4770    }
4771
4772    /**
4773     * Returns the delta between the actual and last reported window top.
4774     *
4775     * @hide
4776     */
4777    public int getActualAndReportedWindowTopDelta() {
4778        if (mAttachInfo != null) {
4779            return mAttachInfo.mActualWindowTop - mAttachInfo.mWindowTop;
4780        }
4781        return 0;
4782    }
4783
4784    /**
4785     * Computes whether this view is visible to the user. Such a view is
4786     * attached, visible, all its predecessors are visible, it is not clipped
4787     * entirely by its predecessors, and has an alpha greater than zero.
4788     *
4789     * @return Whether the view is visible on the screen.
4790     *
4791     * @hide
4792     */
4793    protected boolean isVisibleToUser() {
4794        return isVisibleToUser(null);
4795    }
4796
4797    /**
4798     * Computes whether the given portion of this view is visible to the user. Such a view is
4799     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4800     * the specified portion is not clipped entirely by its predecessors.
4801     *
4802     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4803     *                    <code>null</code>, and the entire view will be tested in this case.
4804     *                    When <code>true</code> is returned by the function, the actual visible
4805     *                    region will be stored in this parameter; that is, if boundInView is fully
4806     *                    contained within the view, no modification will be made, otherwise regions
4807     *                    outside of the visible area of the view will be clipped.
4808     *
4809     * @return Whether the specified portion of the view is visible on the screen.
4810     *
4811     * @hide
4812     */
4813    protected boolean isVisibleToUser(Rect boundInView) {
4814        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4815        Point offset = mAttachInfo.mPoint;
4816        // The first two checks are made also made by isShown() which
4817        // however traverses the tree up to the parent to catch that.
4818        // Therefore, we do some fail fast check to minimize the up
4819        // tree traversal.
4820        boolean isVisible = mAttachInfo != null
4821            && mAttachInfo.mWindowVisibility == View.VISIBLE
4822            && getAlpha() > 0
4823            && isShown()
4824            && getGlobalVisibleRect(visibleRect, offset);
4825            if (isVisible && boundInView != null) {
4826                visibleRect.offset(-offset.x, -offset.y);
4827                isVisible &= boundInView.intersect(visibleRect);
4828            }
4829            return isVisible;
4830    }
4831
4832    /**
4833     * Sets a delegate for implementing accessibility support via compositon as
4834     * opposed to inheritance. The delegate's primary use is for implementing
4835     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4836     *
4837     * @param delegate The delegate instance.
4838     *
4839     * @see AccessibilityDelegate
4840     */
4841    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4842        mAccessibilityDelegate = delegate;
4843    }
4844
4845    /**
4846     * Gets the provider for managing a virtual view hierarchy rooted at this View
4847     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4848     * that explore the window content.
4849     * <p>
4850     * If this method returns an instance, this instance is responsible for managing
4851     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4852     * View including the one representing the View itself. Similarly the returned
4853     * instance is responsible for performing accessibility actions on any virtual
4854     * view or the root view itself.
4855     * </p>
4856     * <p>
4857     * If an {@link AccessibilityDelegate} has been specified via calling
4858     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4859     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4860     * is responsible for handling this call.
4861     * </p>
4862     *
4863     * @return The provider.
4864     *
4865     * @see AccessibilityNodeProvider
4866     */
4867    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4868        if (mAccessibilityDelegate != null) {
4869            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4870        } else {
4871            return null;
4872        }
4873    }
4874
4875    /**
4876     * Gets the unique identifier of this view on the screen for accessibility purposes.
4877     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4878     *
4879     * @return The view accessibility id.
4880     *
4881     * @hide
4882     */
4883    public int getAccessibilityViewId() {
4884        if (mAccessibilityViewId == NO_ID) {
4885            mAccessibilityViewId = sNextAccessibilityViewId++;
4886        }
4887        return mAccessibilityViewId;
4888    }
4889
4890    /**
4891     * Gets the unique identifier of the window in which this View reseides.
4892     *
4893     * @return The window accessibility id.
4894     *
4895     * @hide
4896     */
4897    public int getAccessibilityWindowId() {
4898        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4899    }
4900
4901    /**
4902     * Gets the {@link View} description. It briefly describes the view and is
4903     * primarily used for accessibility support. Set this property to enable
4904     * better accessibility support for your application. This is especially
4905     * true for views that do not have textual representation (For example,
4906     * ImageButton).
4907     *
4908     * @return The content description.
4909     *
4910     * @attr ref android.R.styleable#View_contentDescription
4911     */
4912    @ViewDebug.ExportedProperty(category = "accessibility")
4913    public CharSequence getContentDescription() {
4914        return mContentDescription;
4915    }
4916
4917    /**
4918     * Sets the {@link View} description. It briefly describes the view and is
4919     * primarily used for accessibility support. Set this property to enable
4920     * better accessibility support for your application. This is especially
4921     * true for views that do not have textual representation (For example,
4922     * ImageButton).
4923     *
4924     * @param contentDescription The content description.
4925     *
4926     * @attr ref android.R.styleable#View_contentDescription
4927     */
4928    @RemotableViewMethod
4929    public void setContentDescription(CharSequence contentDescription) {
4930        mContentDescription = contentDescription;
4931        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
4932        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
4933             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
4934        }
4935    }
4936
4937    /**
4938     * Invoked whenever this view loses focus, either by losing window focus or by losing
4939     * focus within its window. This method can be used to clear any state tied to the
4940     * focus. For instance, if a button is held pressed with the trackball and the window
4941     * loses focus, this method can be used to cancel the press.
4942     *
4943     * Subclasses of View overriding this method should always call super.onFocusLost().
4944     *
4945     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4946     * @see #onWindowFocusChanged(boolean)
4947     *
4948     * @hide pending API council approval
4949     */
4950    protected void onFocusLost() {
4951        resetPressedState();
4952    }
4953
4954    private void resetPressedState() {
4955        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4956            return;
4957        }
4958
4959        if (isPressed()) {
4960            setPressed(false);
4961
4962            if (!mHasPerformedLongPress) {
4963                removeLongPressCallback();
4964            }
4965        }
4966    }
4967
4968    /**
4969     * Returns true if this view has focus
4970     *
4971     * @return True if this view has focus, false otherwise.
4972     */
4973    @ViewDebug.ExportedProperty(category = "focus")
4974    public boolean isFocused() {
4975        return (mPrivateFlags & FOCUSED) != 0;
4976    }
4977
4978    /**
4979     * Find the view in the hierarchy rooted at this view that currently has
4980     * focus.
4981     *
4982     * @return The view that currently has focus, or null if no focused view can
4983     *         be found.
4984     */
4985    public View findFocus() {
4986        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4987    }
4988
4989    /**
4990     * Indicates whether this view is one of the set of scrollable containers in
4991     * its window.
4992     *
4993     * @return whether this view is one of the set of scrollable containers in
4994     * its window
4995     *
4996     * @attr ref android.R.styleable#View_isScrollContainer
4997     */
4998    public boolean isScrollContainer() {
4999        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5000    }
5001
5002    /**
5003     * Change whether this view is one of the set of scrollable containers in
5004     * its window.  This will be used to determine whether the window can
5005     * resize or must pan when a soft input area is open -- scrollable
5006     * containers allow the window to use resize mode since the container
5007     * will appropriately shrink.
5008     *
5009     * @attr ref android.R.styleable#View_isScrollContainer
5010     */
5011    public void setScrollContainer(boolean isScrollContainer) {
5012        if (isScrollContainer) {
5013            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5014                mAttachInfo.mScrollContainers.add(this);
5015                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5016            }
5017            mPrivateFlags |= SCROLL_CONTAINER;
5018        } else {
5019            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5020                mAttachInfo.mScrollContainers.remove(this);
5021            }
5022            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5023        }
5024    }
5025
5026    /**
5027     * Returns the quality of the drawing cache.
5028     *
5029     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5030     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5031     *
5032     * @see #setDrawingCacheQuality(int)
5033     * @see #setDrawingCacheEnabled(boolean)
5034     * @see #isDrawingCacheEnabled()
5035     *
5036     * @attr ref android.R.styleable#View_drawingCacheQuality
5037     */
5038    public int getDrawingCacheQuality() {
5039        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5040    }
5041
5042    /**
5043     * Set the drawing cache quality of this view. This value is used only when the
5044     * drawing cache is enabled
5045     *
5046     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5047     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5048     *
5049     * @see #getDrawingCacheQuality()
5050     * @see #setDrawingCacheEnabled(boolean)
5051     * @see #isDrawingCacheEnabled()
5052     *
5053     * @attr ref android.R.styleable#View_drawingCacheQuality
5054     */
5055    public void setDrawingCacheQuality(int quality) {
5056        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5057    }
5058
5059    /**
5060     * Returns whether the screen should remain on, corresponding to the current
5061     * value of {@link #KEEP_SCREEN_ON}.
5062     *
5063     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5064     *
5065     * @see #setKeepScreenOn(boolean)
5066     *
5067     * @attr ref android.R.styleable#View_keepScreenOn
5068     */
5069    public boolean getKeepScreenOn() {
5070        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5071    }
5072
5073    /**
5074     * Controls whether the screen should remain on, modifying the
5075     * value of {@link #KEEP_SCREEN_ON}.
5076     *
5077     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5078     *
5079     * @see #getKeepScreenOn()
5080     *
5081     * @attr ref android.R.styleable#View_keepScreenOn
5082     */
5083    public void setKeepScreenOn(boolean keepScreenOn) {
5084        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5085    }
5086
5087    /**
5088     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5089     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5090     *
5091     * @attr ref android.R.styleable#View_nextFocusLeft
5092     */
5093    public int getNextFocusLeftId() {
5094        return mNextFocusLeftId;
5095    }
5096
5097    /**
5098     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5099     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5100     * decide automatically.
5101     *
5102     * @attr ref android.R.styleable#View_nextFocusLeft
5103     */
5104    public void setNextFocusLeftId(int nextFocusLeftId) {
5105        mNextFocusLeftId = nextFocusLeftId;
5106    }
5107
5108    /**
5109     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5110     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5111     *
5112     * @attr ref android.R.styleable#View_nextFocusRight
5113     */
5114    public int getNextFocusRightId() {
5115        return mNextFocusRightId;
5116    }
5117
5118    /**
5119     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5120     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5121     * decide automatically.
5122     *
5123     * @attr ref android.R.styleable#View_nextFocusRight
5124     */
5125    public void setNextFocusRightId(int nextFocusRightId) {
5126        mNextFocusRightId = nextFocusRightId;
5127    }
5128
5129    /**
5130     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5131     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5132     *
5133     * @attr ref android.R.styleable#View_nextFocusUp
5134     */
5135    public int getNextFocusUpId() {
5136        return mNextFocusUpId;
5137    }
5138
5139    /**
5140     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5141     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5142     * decide automatically.
5143     *
5144     * @attr ref android.R.styleable#View_nextFocusUp
5145     */
5146    public void setNextFocusUpId(int nextFocusUpId) {
5147        mNextFocusUpId = nextFocusUpId;
5148    }
5149
5150    /**
5151     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5152     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5153     *
5154     * @attr ref android.R.styleable#View_nextFocusDown
5155     */
5156    public int getNextFocusDownId() {
5157        return mNextFocusDownId;
5158    }
5159
5160    /**
5161     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5162     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5163     * decide automatically.
5164     *
5165     * @attr ref android.R.styleable#View_nextFocusDown
5166     */
5167    public void setNextFocusDownId(int nextFocusDownId) {
5168        mNextFocusDownId = nextFocusDownId;
5169    }
5170
5171    /**
5172     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5173     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5174     *
5175     * @attr ref android.R.styleable#View_nextFocusForward
5176     */
5177    public int getNextFocusForwardId() {
5178        return mNextFocusForwardId;
5179    }
5180
5181    /**
5182     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5183     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5184     * decide automatically.
5185     *
5186     * @attr ref android.R.styleable#View_nextFocusForward
5187     */
5188    public void setNextFocusForwardId(int nextFocusForwardId) {
5189        mNextFocusForwardId = nextFocusForwardId;
5190    }
5191
5192    /**
5193     * Returns the visibility of this view and all of its ancestors
5194     *
5195     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5196     */
5197    public boolean isShown() {
5198        View current = this;
5199        //noinspection ConstantConditions
5200        do {
5201            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5202                return false;
5203            }
5204            ViewParent parent = current.mParent;
5205            if (parent == null) {
5206                return false; // We are not attached to the view root
5207            }
5208            if (!(parent instanceof View)) {
5209                return true;
5210            }
5211            current = (View) parent;
5212        } while (current != null);
5213
5214        return false;
5215    }
5216
5217    /**
5218     * Called by the view hierarchy when the content insets for a window have
5219     * changed, to allow it to adjust its content to fit within those windows.
5220     * The content insets tell you the space that the status bar, input method,
5221     * and other system windows infringe on the application's window.
5222     *
5223     * <p>You do not normally need to deal with this function, since the default
5224     * window decoration given to applications takes care of applying it to the
5225     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5226     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5227     * and your content can be placed under those system elements.  You can then
5228     * use this method within your view hierarchy if you have parts of your UI
5229     * which you would like to ensure are not being covered.
5230     *
5231     * <p>The default implementation of this method simply applies the content
5232     * inset's to the view's padding, consuming that content (modifying the
5233     * insets to be 0), and returning true.  This behavior is off by default, but can
5234     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5235     *
5236     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5237     * insets object is propagated down the hierarchy, so any changes made to it will
5238     * be seen by all following views (including potentially ones above in
5239     * the hierarchy since this is a depth-first traversal).  The first view
5240     * that returns true will abort the entire traversal.
5241     *
5242     * <p>The default implementation works well for a situation where it is
5243     * used with a container that covers the entire window, allowing it to
5244     * apply the appropriate insets to its content on all edges.  If you need
5245     * a more complicated layout (such as two different views fitting system
5246     * windows, one on the top of the window, and one on the bottom),
5247     * you can override the method and handle the insets however you would like.
5248     * Note that the insets provided by the framework are always relative to the
5249     * far edges of the window, not accounting for the location of the called view
5250     * within that window.  (In fact when this method is called you do not yet know
5251     * where the layout will place the view, as it is done before layout happens.)
5252     *
5253     * <p>Note: unlike many View methods, there is no dispatch phase to this
5254     * call.  If you are overriding it in a ViewGroup and want to allow the
5255     * call to continue to your children, you must be sure to call the super
5256     * implementation.
5257     *
5258     * <p>Here is a sample layout that makes use of fitting system windows
5259     * to have controls for a video view placed inside of the window decorations
5260     * that it hides and shows.  This can be used with code like the second
5261     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5262     *
5263     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5264     *
5265     * @param insets Current content insets of the window.  Prior to
5266     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5267     * the insets or else you and Android will be unhappy.
5268     *
5269     * @return Return true if this view applied the insets and it should not
5270     * continue propagating further down the hierarchy, false otherwise.
5271     * @see #getFitsSystemWindows()
5272     * @see #setFitsSystemWindows()
5273     * @see #setSystemUiVisibility(int)
5274     */
5275    protected boolean fitSystemWindows(Rect insets) {
5276        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5277            mUserPaddingStart = -1;
5278            mUserPaddingEnd = -1;
5279            mUserPaddingRelative = false;
5280            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5281                    || mAttachInfo == null
5282                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5283                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5284                return true;
5285            } else {
5286                internalSetPadding(0, 0, 0, 0);
5287                return false;
5288            }
5289        }
5290        return false;
5291    }
5292
5293    /**
5294     * Sets whether or not this view should account for system screen decorations
5295     * such as the status bar and inset its content; that is, controlling whether
5296     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5297     * executed.  See that method for more details.
5298     *
5299     * <p>Note that if you are providing your own implementation of
5300     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5301     * flag to true -- your implementation will be overriding the default
5302     * implementation that checks this flag.
5303     *
5304     * @param fitSystemWindows If true, then the default implementation of
5305     * {@link #fitSystemWindows(Rect)} will be executed.
5306     *
5307     * @attr ref android.R.styleable#View_fitsSystemWindows
5308     * @see #getFitsSystemWindows()
5309     * @see #fitSystemWindows(Rect)
5310     * @see #setSystemUiVisibility(int)
5311     */
5312    public void setFitsSystemWindows(boolean fitSystemWindows) {
5313        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5314    }
5315
5316    /**
5317     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5318     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5319     * will be executed.
5320     *
5321     * @return Returns true if the default implementation of
5322     * {@link #fitSystemWindows(Rect)} will be executed.
5323     *
5324     * @attr ref android.R.styleable#View_fitsSystemWindows
5325     * @see #setFitsSystemWindows()
5326     * @see #fitSystemWindows(Rect)
5327     * @see #setSystemUiVisibility(int)
5328     */
5329    public boolean getFitsSystemWindows() {
5330        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5331    }
5332
5333    /** @hide */
5334    public boolean fitsSystemWindows() {
5335        return getFitsSystemWindows();
5336    }
5337
5338    /**
5339     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5340     */
5341    public void requestFitSystemWindows() {
5342        if (mParent != null) {
5343            mParent.requestFitSystemWindows();
5344        }
5345    }
5346
5347    /**
5348     * For use by PhoneWindow to make its own system window fitting optional.
5349     * @hide
5350     */
5351    public void makeOptionalFitsSystemWindows() {
5352        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5353    }
5354
5355    /**
5356     * Returns the visibility status for this view.
5357     *
5358     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5359     * @attr ref android.R.styleable#View_visibility
5360     */
5361    @ViewDebug.ExportedProperty(mapping = {
5362        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5363        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5364        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5365    })
5366    public int getVisibility() {
5367        return mViewFlags & VISIBILITY_MASK;
5368    }
5369
5370    /**
5371     * Set the enabled state of this view.
5372     *
5373     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5374     * @attr ref android.R.styleable#View_visibility
5375     */
5376    @RemotableViewMethod
5377    public void setVisibility(int visibility) {
5378        setFlags(visibility, VISIBILITY_MASK);
5379        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5380    }
5381
5382    /**
5383     * Returns the enabled status for this view. The interpretation of the
5384     * enabled state varies by subclass.
5385     *
5386     * @return True if this view is enabled, false otherwise.
5387     */
5388    @ViewDebug.ExportedProperty
5389    public boolean isEnabled() {
5390        return (mViewFlags & ENABLED_MASK) == ENABLED;
5391    }
5392
5393    /**
5394     * Set the enabled state of this view. The interpretation of the enabled
5395     * state varies by subclass.
5396     *
5397     * @param enabled True if this view is enabled, false otherwise.
5398     */
5399    @RemotableViewMethod
5400    public void setEnabled(boolean enabled) {
5401        if (enabled == isEnabled()) return;
5402
5403        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5404
5405        /*
5406         * The View most likely has to change its appearance, so refresh
5407         * the drawable state.
5408         */
5409        refreshDrawableState();
5410
5411        // Invalidate too, since the default behavior for views is to be
5412        // be drawn at 50% alpha rather than to change the drawable.
5413        invalidate(true);
5414    }
5415
5416    /**
5417     * Set whether this view can receive the focus.
5418     *
5419     * Setting this to false will also ensure that this view is not focusable
5420     * in touch mode.
5421     *
5422     * @param focusable If true, this view can receive the focus.
5423     *
5424     * @see #setFocusableInTouchMode(boolean)
5425     * @attr ref android.R.styleable#View_focusable
5426     */
5427    public void setFocusable(boolean focusable) {
5428        if (!focusable) {
5429            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5430        }
5431        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5432    }
5433
5434    /**
5435     * Set whether this view can receive focus while in touch mode.
5436     *
5437     * Setting this to true will also ensure that this view is focusable.
5438     *
5439     * @param focusableInTouchMode If true, this view can receive the focus while
5440     *   in touch mode.
5441     *
5442     * @see #setFocusable(boolean)
5443     * @attr ref android.R.styleable#View_focusableInTouchMode
5444     */
5445    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5446        // Focusable in touch mode should always be set before the focusable flag
5447        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5448        // which, in touch mode, will not successfully request focus on this view
5449        // because the focusable in touch mode flag is not set
5450        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5451        if (focusableInTouchMode) {
5452            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5453        }
5454    }
5455
5456    /**
5457     * Set whether this view should have sound effects enabled for events such as
5458     * clicking and touching.
5459     *
5460     * <p>You may wish to disable sound effects for a view if you already play sounds,
5461     * for instance, a dial key that plays dtmf tones.
5462     *
5463     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5464     * @see #isSoundEffectsEnabled()
5465     * @see #playSoundEffect(int)
5466     * @attr ref android.R.styleable#View_soundEffectsEnabled
5467     */
5468    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5469        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5470    }
5471
5472    /**
5473     * @return whether this view should have sound effects enabled for events such as
5474     *     clicking and touching.
5475     *
5476     * @see #setSoundEffectsEnabled(boolean)
5477     * @see #playSoundEffect(int)
5478     * @attr ref android.R.styleable#View_soundEffectsEnabled
5479     */
5480    @ViewDebug.ExportedProperty
5481    public boolean isSoundEffectsEnabled() {
5482        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5483    }
5484
5485    /**
5486     * Set whether this view should have haptic feedback for events such as
5487     * long presses.
5488     *
5489     * <p>You may wish to disable haptic feedback if your view already controls
5490     * its own haptic feedback.
5491     *
5492     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5493     * @see #isHapticFeedbackEnabled()
5494     * @see #performHapticFeedback(int)
5495     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5496     */
5497    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5498        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5499    }
5500
5501    /**
5502     * @return whether this view should have haptic feedback enabled for events
5503     * long presses.
5504     *
5505     * @see #setHapticFeedbackEnabled(boolean)
5506     * @see #performHapticFeedback(int)
5507     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5508     */
5509    @ViewDebug.ExportedProperty
5510    public boolean isHapticFeedbackEnabled() {
5511        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5512    }
5513
5514    /**
5515     * Returns the layout direction for this view.
5516     *
5517     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5518     *   {@link #LAYOUT_DIRECTION_RTL},
5519     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5520     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5521     * @attr ref android.R.styleable#View_layoutDirection
5522     */
5523    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5524        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5525        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5526        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5527        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5528    })
5529    public int getLayoutDirection() {
5530        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5531    }
5532
5533    /**
5534     * Set the layout direction for this view. This will propagate a reset of layout direction
5535     * resolution to the view's children and resolve layout direction for this view.
5536     *
5537     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5538     *   {@link #LAYOUT_DIRECTION_RTL},
5539     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5540     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5541     *
5542     * @attr ref android.R.styleable#View_layoutDirection
5543     */
5544    @RemotableViewMethod
5545    public void setLayoutDirection(int layoutDirection) {
5546        if (getLayoutDirection() != layoutDirection) {
5547            // Reset the current layout direction and the resolved one
5548            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5549            resetResolvedLayoutDirection();
5550            // Set the new layout direction (filtered) and ask for a layout pass
5551            mPrivateFlags2 |=
5552                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5553            requestLayout();
5554        }
5555    }
5556
5557    /**
5558     * Returns the resolved layout direction for this view.
5559     *
5560     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5561     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5562     */
5563    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5564        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5565        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5566    })
5567    public int getResolvedLayoutDirection() {
5568        // The layout diretion will be resolved only if needed
5569        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5570            resolveLayoutDirection();
5571        }
5572        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5573                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5574    }
5575
5576    /**
5577     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5578     * layout attribute and/or the inherited value from the parent
5579     *
5580     * @return true if the layout is right-to-left.
5581     */
5582    @ViewDebug.ExportedProperty(category = "layout")
5583    public boolean isLayoutRtl() {
5584        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5585    }
5586
5587    /**
5588     * Indicates whether the view is currently tracking transient state that the
5589     * app should not need to concern itself with saving and restoring, but that
5590     * the framework should take special note to preserve when possible.
5591     *
5592     * <p>A view with transient state cannot be trivially rebound from an external
5593     * data source, such as an adapter binding item views in a list. This may be
5594     * because the view is performing an animation, tracking user selection
5595     * of content, or similar.</p>
5596     *
5597     * @return true if the view has transient state
5598     */
5599    @ViewDebug.ExportedProperty(category = "layout")
5600    public boolean hasTransientState() {
5601        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5602    }
5603
5604    /**
5605     * Set whether this view is currently tracking transient state that the
5606     * framework should attempt to preserve when possible. This flag is reference counted,
5607     * so every call to setHasTransientState(true) should be paired with a later call
5608     * to setHasTransientState(false).
5609     *
5610     * <p>A view with transient state cannot be trivially rebound from an external
5611     * data source, such as an adapter binding item views in a list. This may be
5612     * because the view is performing an animation, tracking user selection
5613     * of content, or similar.</p>
5614     *
5615     * @param hasTransientState true if this view has transient state
5616     */
5617    public void setHasTransientState(boolean hasTransientState) {
5618        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5619                mTransientStateCount - 1;
5620        if (mTransientStateCount < 0) {
5621            mTransientStateCount = 0;
5622            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5623                    "unmatched pair of setHasTransientState calls");
5624        }
5625        if ((hasTransientState && mTransientStateCount == 1) ||
5626                (!hasTransientState && mTransientStateCount == 0)) {
5627            // update flag if we've just incremented up from 0 or decremented down to 0
5628            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5629                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5630            if (mParent != null) {
5631                try {
5632                    mParent.childHasTransientStateChanged(this, hasTransientState);
5633                } catch (AbstractMethodError e) {
5634                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5635                            " does not fully implement ViewParent", e);
5636                }
5637            }
5638        }
5639    }
5640
5641    /**
5642     * If this view doesn't do any drawing on its own, set this flag to
5643     * allow further optimizations. By default, this flag is not set on
5644     * View, but could be set on some View subclasses such as ViewGroup.
5645     *
5646     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5647     * you should clear this flag.
5648     *
5649     * @param willNotDraw whether or not this View draw on its own
5650     */
5651    public void setWillNotDraw(boolean willNotDraw) {
5652        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5653    }
5654
5655    /**
5656     * Returns whether or not this View draws on its own.
5657     *
5658     * @return true if this view has nothing to draw, false otherwise
5659     */
5660    @ViewDebug.ExportedProperty(category = "drawing")
5661    public boolean willNotDraw() {
5662        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5663    }
5664
5665    /**
5666     * When a View's drawing cache is enabled, drawing is redirected to an
5667     * offscreen bitmap. Some views, like an ImageView, must be able to
5668     * bypass this mechanism if they already draw a single bitmap, to avoid
5669     * unnecessary usage of the memory.
5670     *
5671     * @param willNotCacheDrawing true if this view does not cache its
5672     *        drawing, false otherwise
5673     */
5674    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5675        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5676    }
5677
5678    /**
5679     * Returns whether or not this View can cache its drawing or not.
5680     *
5681     * @return true if this view does not cache its drawing, false otherwise
5682     */
5683    @ViewDebug.ExportedProperty(category = "drawing")
5684    public boolean willNotCacheDrawing() {
5685        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5686    }
5687
5688    /**
5689     * Indicates whether this view reacts to click events or not.
5690     *
5691     * @return true if the view is clickable, false otherwise
5692     *
5693     * @see #setClickable(boolean)
5694     * @attr ref android.R.styleable#View_clickable
5695     */
5696    @ViewDebug.ExportedProperty
5697    public boolean isClickable() {
5698        return (mViewFlags & CLICKABLE) == CLICKABLE;
5699    }
5700
5701    /**
5702     * Enables or disables click events for this view. When a view
5703     * is clickable it will change its state to "pressed" on every click.
5704     * Subclasses should set the view clickable to visually react to
5705     * user's clicks.
5706     *
5707     * @param clickable true to make the view clickable, false otherwise
5708     *
5709     * @see #isClickable()
5710     * @attr ref android.R.styleable#View_clickable
5711     */
5712    public void setClickable(boolean clickable) {
5713        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5714    }
5715
5716    /**
5717     * Indicates whether this view reacts to long click events or not.
5718     *
5719     * @return true if the view is long clickable, false otherwise
5720     *
5721     * @see #setLongClickable(boolean)
5722     * @attr ref android.R.styleable#View_longClickable
5723     */
5724    public boolean isLongClickable() {
5725        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5726    }
5727
5728    /**
5729     * Enables or disables long click events for this view. When a view is long
5730     * clickable it reacts to the user holding down the button for a longer
5731     * duration than a tap. This event can either launch the listener or a
5732     * context menu.
5733     *
5734     * @param longClickable true to make the view long clickable, false otherwise
5735     * @see #isLongClickable()
5736     * @attr ref android.R.styleable#View_longClickable
5737     */
5738    public void setLongClickable(boolean longClickable) {
5739        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5740    }
5741
5742    /**
5743     * Sets the pressed state for this view.
5744     *
5745     * @see #isClickable()
5746     * @see #setClickable(boolean)
5747     *
5748     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5749     *        the View's internal state from a previously set "pressed" state.
5750     */
5751    public void setPressed(boolean pressed) {
5752        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5753
5754        if (pressed) {
5755            mPrivateFlags |= PRESSED;
5756        } else {
5757            mPrivateFlags &= ~PRESSED;
5758        }
5759
5760        if (needsRefresh) {
5761            refreshDrawableState();
5762        }
5763        dispatchSetPressed(pressed);
5764    }
5765
5766    /**
5767     * Dispatch setPressed to all of this View's children.
5768     *
5769     * @see #setPressed(boolean)
5770     *
5771     * @param pressed The new pressed state
5772     */
5773    protected void dispatchSetPressed(boolean pressed) {
5774    }
5775
5776    /**
5777     * Indicates whether the view is currently in pressed state. Unless
5778     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5779     * the pressed state.
5780     *
5781     * @see #setPressed(boolean)
5782     * @see #isClickable()
5783     * @see #setClickable(boolean)
5784     *
5785     * @return true if the view is currently pressed, false otherwise
5786     */
5787    public boolean isPressed() {
5788        return (mPrivateFlags & PRESSED) == PRESSED;
5789    }
5790
5791    /**
5792     * Indicates whether this view will save its state (that is,
5793     * whether its {@link #onSaveInstanceState} method will be called).
5794     *
5795     * @return Returns true if the view state saving is enabled, else false.
5796     *
5797     * @see #setSaveEnabled(boolean)
5798     * @attr ref android.R.styleable#View_saveEnabled
5799     */
5800    public boolean isSaveEnabled() {
5801        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5802    }
5803
5804    /**
5805     * Controls whether the saving of this view's state is
5806     * enabled (that is, whether its {@link #onSaveInstanceState} method
5807     * will be called).  Note that even if freezing is enabled, the
5808     * view still must have an id assigned to it (via {@link #setId(int)})
5809     * for its state to be saved.  This flag can only disable the
5810     * saving of this view; any child views may still have their state saved.
5811     *
5812     * @param enabled Set to false to <em>disable</em> state saving, or true
5813     * (the default) to allow it.
5814     *
5815     * @see #isSaveEnabled()
5816     * @see #setId(int)
5817     * @see #onSaveInstanceState()
5818     * @attr ref android.R.styleable#View_saveEnabled
5819     */
5820    public void setSaveEnabled(boolean enabled) {
5821        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5822    }
5823
5824    /**
5825     * Gets whether the framework should discard touches when the view's
5826     * window is obscured by another visible window.
5827     * Refer to the {@link View} security documentation for more details.
5828     *
5829     * @return True if touch filtering is enabled.
5830     *
5831     * @see #setFilterTouchesWhenObscured(boolean)
5832     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5833     */
5834    @ViewDebug.ExportedProperty
5835    public boolean getFilterTouchesWhenObscured() {
5836        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5837    }
5838
5839    /**
5840     * Sets whether the framework should discard touches when the view's
5841     * window is obscured by another visible window.
5842     * Refer to the {@link View} security documentation for more details.
5843     *
5844     * @param enabled True if touch filtering should be enabled.
5845     *
5846     * @see #getFilterTouchesWhenObscured
5847     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5848     */
5849    public void setFilterTouchesWhenObscured(boolean enabled) {
5850        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5851                FILTER_TOUCHES_WHEN_OBSCURED);
5852    }
5853
5854    /**
5855     * Indicates whether the entire hierarchy under this view will save its
5856     * state when a state saving traversal occurs from its parent.  The default
5857     * is true; if false, these views will not be saved unless
5858     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5859     *
5860     * @return Returns true if the view state saving from parent is enabled, else false.
5861     *
5862     * @see #setSaveFromParentEnabled(boolean)
5863     */
5864    public boolean isSaveFromParentEnabled() {
5865        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5866    }
5867
5868    /**
5869     * Controls whether the entire hierarchy under this view will save its
5870     * state when a state saving traversal occurs from its parent.  The default
5871     * is true; if false, these views will not be saved unless
5872     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5873     *
5874     * @param enabled Set to false to <em>disable</em> state saving, or true
5875     * (the default) to allow it.
5876     *
5877     * @see #isSaveFromParentEnabled()
5878     * @see #setId(int)
5879     * @see #onSaveInstanceState()
5880     */
5881    public void setSaveFromParentEnabled(boolean enabled) {
5882        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5883    }
5884
5885
5886    /**
5887     * Returns whether this View is able to take focus.
5888     *
5889     * @return True if this view can take focus, or false otherwise.
5890     * @attr ref android.R.styleable#View_focusable
5891     */
5892    @ViewDebug.ExportedProperty(category = "focus")
5893    public final boolean isFocusable() {
5894        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5895    }
5896
5897    /**
5898     * When a view is focusable, it may not want to take focus when in touch mode.
5899     * For example, a button would like focus when the user is navigating via a D-pad
5900     * so that the user can click on it, but once the user starts touching the screen,
5901     * the button shouldn't take focus
5902     * @return Whether the view is focusable in touch mode.
5903     * @attr ref android.R.styleable#View_focusableInTouchMode
5904     */
5905    @ViewDebug.ExportedProperty
5906    public final boolean isFocusableInTouchMode() {
5907        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5908    }
5909
5910    /**
5911     * Find the nearest view in the specified direction that can take focus.
5912     * This does not actually give focus to that view.
5913     *
5914     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5915     *
5916     * @return The nearest focusable in the specified direction, or null if none
5917     *         can be found.
5918     */
5919    public View focusSearch(int direction) {
5920        if (mParent != null) {
5921            return mParent.focusSearch(this, direction);
5922        } else {
5923            return null;
5924        }
5925    }
5926
5927    /**
5928     * This method is the last chance for the focused view and its ancestors to
5929     * respond to an arrow key. This is called when the focused view did not
5930     * consume the key internally, nor could the view system find a new view in
5931     * the requested direction to give focus to.
5932     *
5933     * @param focused The currently focused view.
5934     * @param direction The direction focus wants to move. One of FOCUS_UP,
5935     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5936     * @return True if the this view consumed this unhandled move.
5937     */
5938    public boolean dispatchUnhandledMove(View focused, int direction) {
5939        return false;
5940    }
5941
5942    /**
5943     * If a user manually specified the next view id for a particular direction,
5944     * use the root to look up the view.
5945     * @param root The root view of the hierarchy containing this view.
5946     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5947     * or FOCUS_BACKWARD.
5948     * @return The user specified next view, or null if there is none.
5949     */
5950    View findUserSetNextFocus(View root, int direction) {
5951        switch (direction) {
5952            case FOCUS_LEFT:
5953                if (mNextFocusLeftId == View.NO_ID) return null;
5954                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5955            case FOCUS_RIGHT:
5956                if (mNextFocusRightId == View.NO_ID) return null;
5957                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5958            case FOCUS_UP:
5959                if (mNextFocusUpId == View.NO_ID) return null;
5960                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5961            case FOCUS_DOWN:
5962                if (mNextFocusDownId == View.NO_ID) return null;
5963                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5964            case FOCUS_FORWARD:
5965                if (mNextFocusForwardId == View.NO_ID) return null;
5966                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5967            case FOCUS_BACKWARD: {
5968                if (mID == View.NO_ID) return null;
5969                final int id = mID;
5970                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5971                    @Override
5972                    public boolean apply(View t) {
5973                        return t.mNextFocusForwardId == id;
5974                    }
5975                });
5976            }
5977        }
5978        return null;
5979    }
5980
5981    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5982        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5983            @Override
5984            public boolean apply(View t) {
5985                return t.mID == childViewId;
5986            }
5987        });
5988
5989        if (result == null) {
5990            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5991                    + "by user for id " + childViewId);
5992        }
5993        return result;
5994    }
5995
5996    /**
5997     * Find and return all focusable views that are descendants of this view,
5998     * possibly including this view if it is focusable itself.
5999     *
6000     * @param direction The direction of the focus
6001     * @return A list of focusable views
6002     */
6003    public ArrayList<View> getFocusables(int direction) {
6004        ArrayList<View> result = new ArrayList<View>(24);
6005        addFocusables(result, direction);
6006        return result;
6007    }
6008
6009    /**
6010     * Add any focusable views that are descendants of this view (possibly
6011     * including this view if it is focusable itself) to views.  If we are in touch mode,
6012     * only add views that are also focusable in touch mode.
6013     *
6014     * @param views Focusable views found so far
6015     * @param direction The direction of the focus
6016     */
6017    public void addFocusables(ArrayList<View> views, int direction) {
6018        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6019    }
6020
6021    /**
6022     * Adds any focusable views that are descendants of this view (possibly
6023     * including this view if it is focusable itself) to views. This method
6024     * adds all focusable views regardless if we are in touch mode or
6025     * only views focusable in touch mode if we are in touch mode or
6026     * only views that can take accessibility focus if accessibility is enabeld
6027     * depending on the focusable mode paramater.
6028     *
6029     * @param views Focusable views found so far or null if all we are interested is
6030     *        the number of focusables.
6031     * @param direction The direction of the focus.
6032     * @param focusableMode The type of focusables to be added.
6033     *
6034     * @see #FOCUSABLES_ALL
6035     * @see #FOCUSABLES_TOUCH_MODE
6036     */
6037    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6038        if (views == null) {
6039            return;
6040        }
6041        if (!isFocusable()) {
6042            return;
6043        }
6044        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6045                && isInTouchMode() && !isFocusableInTouchMode()) {
6046            return;
6047        }
6048        views.add(this);
6049    }
6050
6051    /**
6052     * Finds the Views that contain given text. The containment is case insensitive.
6053     * The search is performed by either the text that the View renders or the content
6054     * description that describes the view for accessibility purposes and the view does
6055     * not render or both. Clients can specify how the search is to be performed via
6056     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6057     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6058     *
6059     * @param outViews The output list of matching Views.
6060     * @param searched The text to match against.
6061     *
6062     * @see #FIND_VIEWS_WITH_TEXT
6063     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6064     * @see #setContentDescription(CharSequence)
6065     */
6066    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6067        if (getAccessibilityNodeProvider() != null) {
6068            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6069                outViews.add(this);
6070            }
6071        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6072                && (searched != null && searched.length() > 0)
6073                && (mContentDescription != null && mContentDescription.length() > 0)) {
6074            String searchedLowerCase = searched.toString().toLowerCase();
6075            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6076            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6077                outViews.add(this);
6078            }
6079        }
6080    }
6081
6082    /**
6083     * Find and return all touchable views that are descendants of this view,
6084     * possibly including this view if it is touchable itself.
6085     *
6086     * @return A list of touchable views
6087     */
6088    public ArrayList<View> getTouchables() {
6089        ArrayList<View> result = new ArrayList<View>();
6090        addTouchables(result);
6091        return result;
6092    }
6093
6094    /**
6095     * Add any touchable views that are descendants of this view (possibly
6096     * including this view if it is touchable itself) to views.
6097     *
6098     * @param views Touchable views found so far
6099     */
6100    public void addTouchables(ArrayList<View> views) {
6101        final int viewFlags = mViewFlags;
6102
6103        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6104                && (viewFlags & ENABLED_MASK) == ENABLED) {
6105            views.add(this);
6106        }
6107    }
6108
6109    /**
6110     * Returns whether this View is accessibility focused.
6111     *
6112     * @return True if this View is accessibility focused.
6113     */
6114    boolean isAccessibilityFocused() {
6115        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6116    }
6117
6118    /**
6119     * Call this to try to give accessibility focus to this view.
6120     *
6121     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6122     * returns false or the view is no visible or the view already has accessibility
6123     * focus.
6124     *
6125     * See also {@link #focusSearch(int)}, which is what you call to say that you
6126     * have focus, and you want your parent to look for the next one.
6127     *
6128     * @return Whether this view actually took accessibility focus.
6129     *
6130     * @hide
6131     */
6132    public boolean requestAccessibilityFocus() {
6133        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6134        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6135            return false;
6136        }
6137        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6138            return false;
6139        }
6140        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6141            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6142            ViewRootImpl viewRootImpl = getViewRootImpl();
6143            if (viewRootImpl != null) {
6144                viewRootImpl.setAccessibilityFocus(this, null);
6145            }
6146            invalidate();
6147            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6148            notifyAccessibilityStateChanged();
6149            return true;
6150        }
6151        return false;
6152    }
6153
6154    /**
6155     * Call this to try to clear accessibility focus of this view.
6156     *
6157     * See also {@link #focusSearch(int)}, which is what you call to say that you
6158     * have focus, and you want your parent to look for the next one.
6159     *
6160     * @hide
6161     */
6162    public void clearAccessibilityFocus() {
6163        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6164            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6165            invalidate();
6166            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6167            notifyAccessibilityStateChanged();
6168        }
6169        // Clear the global reference of accessibility focus if this
6170        // view or any of its descendants had accessibility focus.
6171        ViewRootImpl viewRootImpl = getViewRootImpl();
6172        if (viewRootImpl != null) {
6173            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6174            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6175                viewRootImpl.setAccessibilityFocus(null, null);
6176            }
6177        }
6178    }
6179
6180    private void sendAccessibilityHoverEvent(int eventType) {
6181        // Since we are not delivering to a client accessibility events from not
6182        // important views (unless the clinet request that) we need to fire the
6183        // event from the deepest view exposed to the client. As a consequence if
6184        // the user crosses a not exposed view the client will see enter and exit
6185        // of the exposed predecessor followed by and enter and exit of that same
6186        // predecessor when entering and exiting the not exposed descendant. This
6187        // is fine since the client has a clear idea which view is hovered at the
6188        // price of a couple more events being sent. This is a simple and
6189        // working solution.
6190        View source = this;
6191        while (true) {
6192            if (source.includeForAccessibility()) {
6193                source.sendAccessibilityEvent(eventType);
6194                return;
6195            }
6196            ViewParent parent = source.getParent();
6197            if (parent instanceof View) {
6198                source = (View) parent;
6199            } else {
6200                return;
6201            }
6202        }
6203    }
6204
6205    /**
6206     * Clears accessibility focus without calling any callback methods
6207     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6208     * is used for clearing accessibility focus when giving this focus to
6209     * another view.
6210     */
6211    void clearAccessibilityFocusNoCallbacks() {
6212        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6213            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6214            invalidate();
6215        }
6216    }
6217
6218    /**
6219     * Call this to try to give focus to a specific view or to one of its
6220     * descendants.
6221     *
6222     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6223     * false), or if it is focusable and it is not focusable in touch mode
6224     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6225     *
6226     * See also {@link #focusSearch(int)}, which is what you call to say that you
6227     * have focus, and you want your parent to look for the next one.
6228     *
6229     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6230     * {@link #FOCUS_DOWN} and <code>null</code>.
6231     *
6232     * @return Whether this view or one of its descendants actually took focus.
6233     */
6234    public final boolean requestFocus() {
6235        return requestFocus(View.FOCUS_DOWN);
6236    }
6237
6238    /**
6239     * Call this to try to give focus to a specific view or to one of its
6240     * descendants and give it a hint about what direction focus is heading.
6241     *
6242     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6243     * false), or if it is focusable and it is not focusable in touch mode
6244     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6245     *
6246     * See also {@link #focusSearch(int)}, which is what you call to say that you
6247     * have focus, and you want your parent to look for the next one.
6248     *
6249     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6250     * <code>null</code> set for the previously focused rectangle.
6251     *
6252     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6253     * @return Whether this view or one of its descendants actually took focus.
6254     */
6255    public final boolean requestFocus(int direction) {
6256        return requestFocus(direction, null);
6257    }
6258
6259    /**
6260     * Call this to try to give focus to a specific view or to one of its descendants
6261     * and give it hints about the direction and a specific rectangle that the focus
6262     * is coming from.  The rectangle can help give larger views a finer grained hint
6263     * about where focus is coming from, and therefore, where to show selection, or
6264     * forward focus change internally.
6265     *
6266     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6267     * false), or if it is focusable and it is not focusable in touch mode
6268     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6269     *
6270     * A View will not take focus if it is not visible.
6271     *
6272     * A View will not take focus if one of its parents has
6273     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6274     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6275     *
6276     * See also {@link #focusSearch(int)}, which is what you call to say that you
6277     * have focus, and you want your parent to look for the next one.
6278     *
6279     * You may wish to override this method if your custom {@link View} has an internal
6280     * {@link View} that it wishes to forward the request to.
6281     *
6282     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6283     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6284     *        to give a finer grained hint about where focus is coming from.  May be null
6285     *        if there is no hint.
6286     * @return Whether this view or one of its descendants actually took focus.
6287     */
6288    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6289        return requestFocusNoSearch(direction, previouslyFocusedRect);
6290    }
6291
6292    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6293        // need to be focusable
6294        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6295                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6296            return false;
6297        }
6298
6299        // need to be focusable in touch mode if in touch mode
6300        if (isInTouchMode() &&
6301            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6302               return false;
6303        }
6304
6305        // need to not have any parents blocking us
6306        if (hasAncestorThatBlocksDescendantFocus()) {
6307            return false;
6308        }
6309
6310        handleFocusGainInternal(direction, previouslyFocusedRect);
6311        return true;
6312    }
6313
6314    /**
6315     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6316     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6317     * touch mode to request focus when they are touched.
6318     *
6319     * @return Whether this view or one of its descendants actually took focus.
6320     *
6321     * @see #isInTouchMode()
6322     *
6323     */
6324    public final boolean requestFocusFromTouch() {
6325        // Leave touch mode if we need to
6326        if (isInTouchMode()) {
6327            ViewRootImpl viewRoot = getViewRootImpl();
6328            if (viewRoot != null) {
6329                viewRoot.ensureTouchMode(false);
6330            }
6331        }
6332        return requestFocus(View.FOCUS_DOWN);
6333    }
6334
6335    /**
6336     * @return Whether any ancestor of this view blocks descendant focus.
6337     */
6338    private boolean hasAncestorThatBlocksDescendantFocus() {
6339        ViewParent ancestor = mParent;
6340        while (ancestor instanceof ViewGroup) {
6341            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6342            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6343                return true;
6344            } else {
6345                ancestor = vgAncestor.getParent();
6346            }
6347        }
6348        return false;
6349    }
6350
6351    /**
6352     * Gets the mode for determining whether this View is important for accessibility
6353     * which is if it fires accessibility events and if it is reported to
6354     * accessibility services that query the screen.
6355     *
6356     * @return The mode for determining whether a View is important for accessibility.
6357     *
6358     * @attr ref android.R.styleable#View_importantForAccessibility
6359     *
6360     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6361     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6362     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6363     */
6364    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6365            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6366            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6367            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6368        })
6369    public int getImportantForAccessibility() {
6370        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6371                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6372    }
6373
6374    /**
6375     * Sets how to determine whether this view is important for accessibility
6376     * which is if it fires accessibility events and if it is reported to
6377     * accessibility services that query the screen.
6378     *
6379     * @param mode How to determine whether this view is important for accessibility.
6380     *
6381     * @attr ref android.R.styleable#View_importantForAccessibility
6382     *
6383     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6384     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6385     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6386     */
6387    public void setImportantForAccessibility(int mode) {
6388        if (mode != getImportantForAccessibility()) {
6389            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6390            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6391                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6392            notifyAccessibilityStateChanged();
6393        }
6394    }
6395
6396    /**
6397     * Gets whether this view should be exposed for accessibility.
6398     *
6399     * @return Whether the view is exposed for accessibility.
6400     *
6401     * @hide
6402     */
6403    public boolean isImportantForAccessibility() {
6404        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6405                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6406        switch (mode) {
6407            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6408                return true;
6409            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6410                return false;
6411            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6412                return isActionableForAccessibility() || hasListenersForAccessibility();
6413            default:
6414                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6415                        + mode);
6416        }
6417    }
6418
6419    /**
6420     * Gets the parent for accessibility purposes. Note that the parent for
6421     * accessibility is not necessary the immediate parent. It is the first
6422     * predecessor that is important for accessibility.
6423     *
6424     * @return The parent for accessibility purposes.
6425     */
6426    public ViewParent getParentForAccessibility() {
6427        if (mParent instanceof View) {
6428            View parentView = (View) mParent;
6429            if (parentView.includeForAccessibility()) {
6430                return mParent;
6431            } else {
6432                return mParent.getParentForAccessibility();
6433            }
6434        }
6435        return null;
6436    }
6437
6438    /**
6439     * Adds the children of a given View for accessibility. Since some Views are
6440     * not important for accessibility the children for accessibility are not
6441     * necessarily direct children of the riew, rather they are the first level of
6442     * descendants important for accessibility.
6443     *
6444     * @param children The list of children for accessibility.
6445     */
6446    public void addChildrenForAccessibility(ArrayList<View> children) {
6447        if (includeForAccessibility()) {
6448            children.add(this);
6449        }
6450    }
6451
6452    /**
6453     * Whether to regard this view for accessibility. A view is regarded for
6454     * accessibility if it is important for accessibility or the querying
6455     * accessibility service has explicitly requested that view not
6456     * important for accessibility are regarded.
6457     *
6458     * @return Whether to regard the view for accessibility.
6459     *
6460     * @hide
6461     */
6462    public boolean includeForAccessibility() {
6463        if (mAttachInfo != null) {
6464            if (!mAttachInfo.mIncludeNotImportantViews) {
6465                return isImportantForAccessibility();
6466            }
6467            return true;
6468        }
6469        return false;
6470    }
6471
6472    /**
6473     * Returns whether the View is considered actionable from
6474     * accessibility perspective. Such view are important for
6475     * accessiiblity.
6476     *
6477     * @return True if the view is actionable for accessibility.
6478     *
6479     * @hide
6480     */
6481    public boolean isActionableForAccessibility() {
6482        return (isClickable() || isLongClickable() || isFocusable());
6483    }
6484
6485    /**
6486     * Returns whether the View has registered callbacks wich makes it
6487     * important for accessiiblity.
6488     *
6489     * @return True if the view is actionable for accessibility.
6490     */
6491    private boolean hasListenersForAccessibility() {
6492        ListenerInfo info = getListenerInfo();
6493        return mTouchDelegate != null || info.mOnKeyListener != null
6494                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6495                || info.mOnHoverListener != null || info.mOnDragListener != null;
6496    }
6497
6498    /**
6499     * Notifies accessibility services that some view's important for
6500     * accessibility state has changed. Note that such notifications
6501     * are made at most once every
6502     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6503     * to avoid unnecessary load to the system. Also once a view has
6504     * made a notifucation this method is a NOP until the notification has
6505     * been sent to clients.
6506     *
6507     * @hide
6508     *
6509     * TODO: Makse sure this method is called for any view state change
6510     *       that is interesting for accessilility purposes.
6511     */
6512    public void notifyAccessibilityStateChanged() {
6513        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6514            return;
6515        }
6516        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6517            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6518            if (mParent != null) {
6519                mParent.childAccessibilityStateChanged(this);
6520            }
6521        }
6522    }
6523
6524    /**
6525     * Reset the state indicating the this view has requested clients
6526     * interested in its accessiblity state to be notified.
6527     *
6528     * @hide
6529     */
6530    public void resetAccessibilityStateChanged() {
6531        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6532    }
6533
6534    /**
6535     * Performs the specified accessibility action on the view. For
6536     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6537    * <p>
6538    * If an {@link AccessibilityDelegate} has been specified via calling
6539    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6540    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6541    * is responsible for handling this call.
6542    * </p>
6543     *
6544     * @param action The action to perform.
6545     * @param arguments Optional action arguments.
6546     * @return Whether the action was performed.
6547     */
6548    public boolean performAccessibilityAction(int action, Bundle arguments) {
6549      if (mAccessibilityDelegate != null) {
6550          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6551      } else {
6552          return performAccessibilityActionInternal(action, arguments);
6553      }
6554    }
6555
6556   /**
6557    * @see #performAccessibilityAction(int, Bundle)
6558    *
6559    * Note: Called from the default {@link AccessibilityDelegate}.
6560    */
6561    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6562        switch (action) {
6563            case AccessibilityNodeInfo.ACTION_CLICK: {
6564                if (isClickable()) {
6565                    return performClick();
6566                }
6567            } break;
6568            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6569                if (isLongClickable()) {
6570                    return performLongClick();
6571                }
6572            } break;
6573            case AccessibilityNodeInfo.ACTION_FOCUS: {
6574                if (!hasFocus()) {
6575                    // Get out of touch mode since accessibility
6576                    // wants to move focus around.
6577                    getViewRootImpl().ensureTouchMode(false);
6578                    return requestFocus();
6579                }
6580            } break;
6581            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6582                if (hasFocus()) {
6583                    clearFocus();
6584                    return !isFocused();
6585                }
6586            } break;
6587            case AccessibilityNodeInfo.ACTION_SELECT: {
6588                if (!isSelected()) {
6589                    setSelected(true);
6590                    return isSelected();
6591                }
6592            } break;
6593            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6594                if (isSelected()) {
6595                    setSelected(false);
6596                    return !isSelected();
6597                }
6598            } break;
6599            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6600                if (!isAccessibilityFocused()) {
6601                    return requestAccessibilityFocus();
6602                }
6603            } break;
6604            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6605                if (isAccessibilityFocused()) {
6606                    clearAccessibilityFocus();
6607                    return true;
6608                }
6609            } break;
6610            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6611                if (arguments != null) {
6612                    final int granularity = arguments.getInt(
6613                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6614                    return nextAtGranularity(granularity);
6615                }
6616            } break;
6617            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6618                if (arguments != null) {
6619                    final int granularity = arguments.getInt(
6620                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6621                    return previousAtGranularity(granularity);
6622                }
6623            } break;
6624        }
6625        return false;
6626    }
6627
6628    private boolean nextAtGranularity(int granularity) {
6629        CharSequence text = getIterableTextForAccessibility();
6630        if (text == null || text.length() == 0) {
6631            return false;
6632        }
6633        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6634        if (iterator == null) {
6635            return false;
6636        }
6637        final int current = getAccessibilityCursorPosition();
6638        final int[] range = iterator.following(current);
6639        if (range == null) {
6640            return false;
6641        }
6642        final int start = range[0];
6643        final int end = range[1];
6644        setAccessibilityCursorPosition(end);
6645        sendViewTextTraversedAtGranularityEvent(
6646                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6647                granularity, start, end);
6648        return true;
6649    }
6650
6651    private boolean previousAtGranularity(int granularity) {
6652        CharSequence text = getIterableTextForAccessibility();
6653        if (text == null || text.length() == 0) {
6654            return false;
6655        }
6656        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6657        if (iterator == null) {
6658            return false;
6659        }
6660        int current = getAccessibilityCursorPosition();
6661        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6662            current = text.length();
6663        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6664            // When traversing by character we always put the cursor after the character
6665            // to ease edit and have to compensate before asking the for previous segment.
6666            current--;
6667        }
6668        final int[] range = iterator.preceding(current);
6669        if (range == null) {
6670            return false;
6671        }
6672        final int start = range[0];
6673        final int end = range[1];
6674        // Always put the cursor after the character to ease edit.
6675        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6676            setAccessibilityCursorPosition(end);
6677        } else {
6678            setAccessibilityCursorPosition(start);
6679        }
6680        sendViewTextTraversedAtGranularityEvent(
6681                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6682                granularity, start, end);
6683        return true;
6684    }
6685
6686    /**
6687     * Gets the text reported for accessibility purposes.
6688     *
6689     * @return The accessibility text.
6690     *
6691     * @hide
6692     */
6693    public CharSequence getIterableTextForAccessibility() {
6694        return mContentDescription;
6695    }
6696
6697    /**
6698     * @hide
6699     */
6700    public int getAccessibilityCursorPosition() {
6701        return mAccessibilityCursorPosition;
6702    }
6703
6704    /**
6705     * @hide
6706     */
6707    public void setAccessibilityCursorPosition(int position) {
6708        mAccessibilityCursorPosition = position;
6709    }
6710
6711    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6712            int fromIndex, int toIndex) {
6713        if (mParent == null) {
6714            return;
6715        }
6716        AccessibilityEvent event = AccessibilityEvent.obtain(
6717                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6718        onInitializeAccessibilityEvent(event);
6719        onPopulateAccessibilityEvent(event);
6720        event.setFromIndex(fromIndex);
6721        event.setToIndex(toIndex);
6722        event.setAction(action);
6723        event.setMovementGranularity(granularity);
6724        mParent.requestSendAccessibilityEvent(this, event);
6725    }
6726
6727    /**
6728     * @hide
6729     */
6730    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6731        switch (granularity) {
6732            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6733                CharSequence text = getIterableTextForAccessibility();
6734                if (text != null && text.length() > 0) {
6735                    CharacterTextSegmentIterator iterator =
6736                        CharacterTextSegmentIterator.getInstance(
6737                                mContext.getResources().getConfiguration().locale);
6738                    iterator.initialize(text.toString());
6739                    return iterator;
6740                }
6741            } break;
6742            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6743                CharSequence text = getIterableTextForAccessibility();
6744                if (text != null && text.length() > 0) {
6745                    WordTextSegmentIterator iterator =
6746                        WordTextSegmentIterator.getInstance(
6747                                mContext.getResources().getConfiguration().locale);
6748                    iterator.initialize(text.toString());
6749                    return iterator;
6750                }
6751            } break;
6752            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6753                CharSequence text = getIterableTextForAccessibility();
6754                if (text != null && text.length() > 0) {
6755                    ParagraphTextSegmentIterator iterator =
6756                        ParagraphTextSegmentIterator.getInstance();
6757                    iterator.initialize(text.toString());
6758                    return iterator;
6759                }
6760            } break;
6761        }
6762        return null;
6763    }
6764
6765    /**
6766     * @hide
6767     */
6768    public void dispatchStartTemporaryDetach() {
6769        clearAccessibilityFocus();
6770        clearDisplayList();
6771
6772        onStartTemporaryDetach();
6773    }
6774
6775    /**
6776     * This is called when a container is going to temporarily detach a child, with
6777     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6778     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6779     * {@link #onDetachedFromWindow()} when the container is done.
6780     */
6781    public void onStartTemporaryDetach() {
6782        removeUnsetPressCallback();
6783        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6784    }
6785
6786    /**
6787     * @hide
6788     */
6789    public void dispatchFinishTemporaryDetach() {
6790        onFinishTemporaryDetach();
6791    }
6792
6793    /**
6794     * Called after {@link #onStartTemporaryDetach} when the container is done
6795     * changing the view.
6796     */
6797    public void onFinishTemporaryDetach() {
6798    }
6799
6800    /**
6801     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6802     * for this view's window.  Returns null if the view is not currently attached
6803     * to the window.  Normally you will not need to use this directly, but
6804     * just use the standard high-level event callbacks like
6805     * {@link #onKeyDown(int, KeyEvent)}.
6806     */
6807    public KeyEvent.DispatcherState getKeyDispatcherState() {
6808        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6809    }
6810
6811    /**
6812     * Dispatch a key event before it is processed by any input method
6813     * associated with the view hierarchy.  This can be used to intercept
6814     * key events in special situations before the IME consumes them; a
6815     * typical example would be handling the BACK key to update the application's
6816     * UI instead of allowing the IME to see it and close itself.
6817     *
6818     * @param event The key event to be dispatched.
6819     * @return True if the event was handled, false otherwise.
6820     */
6821    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6822        return onKeyPreIme(event.getKeyCode(), event);
6823    }
6824
6825    /**
6826     * Dispatch a key event to the next view on the focus path. This path runs
6827     * from the top of the view tree down to the currently focused view. If this
6828     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6829     * the next node down the focus path. This method also fires any key
6830     * listeners.
6831     *
6832     * @param event The key event to be dispatched.
6833     * @return True if the event was handled, false otherwise.
6834     */
6835    public boolean dispatchKeyEvent(KeyEvent event) {
6836        if (mInputEventConsistencyVerifier != null) {
6837            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6838        }
6839
6840        // Give any attached key listener a first crack at the event.
6841        //noinspection SimplifiableIfStatement
6842        ListenerInfo li = mListenerInfo;
6843        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6844                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6845            return true;
6846        }
6847
6848        if (event.dispatch(this, mAttachInfo != null
6849                ? mAttachInfo.mKeyDispatchState : null, this)) {
6850            return true;
6851        }
6852
6853        if (mInputEventConsistencyVerifier != null) {
6854            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6855        }
6856        return false;
6857    }
6858
6859    /**
6860     * Dispatches a key shortcut event.
6861     *
6862     * @param event The key event to be dispatched.
6863     * @return True if the event was handled by the view, false otherwise.
6864     */
6865    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6866        return onKeyShortcut(event.getKeyCode(), event);
6867    }
6868
6869    /**
6870     * Pass the touch screen motion event down to the target view, or this
6871     * view if it is the target.
6872     *
6873     * @param event The motion event to be dispatched.
6874     * @return True if the event was handled by the view, false otherwise.
6875     */
6876    public boolean dispatchTouchEvent(MotionEvent event) {
6877        if (mInputEventConsistencyVerifier != null) {
6878            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6879        }
6880
6881        if (onFilterTouchEventForSecurity(event)) {
6882            //noinspection SimplifiableIfStatement
6883            ListenerInfo li = mListenerInfo;
6884            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6885                    && li.mOnTouchListener.onTouch(this, event)) {
6886                return true;
6887            }
6888
6889            if (onTouchEvent(event)) {
6890                return true;
6891            }
6892        }
6893
6894        if (mInputEventConsistencyVerifier != null) {
6895            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6896        }
6897        return false;
6898    }
6899
6900    /**
6901     * Filter the touch event to apply security policies.
6902     *
6903     * @param event The motion event to be filtered.
6904     * @return True if the event should be dispatched, false if the event should be dropped.
6905     *
6906     * @see #getFilterTouchesWhenObscured
6907     */
6908    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6909        //noinspection RedundantIfStatement
6910        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6911                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6912            // Window is obscured, drop this touch.
6913            return false;
6914        }
6915        return true;
6916    }
6917
6918    /**
6919     * Pass a trackball motion event down to the focused view.
6920     *
6921     * @param event The motion event to be dispatched.
6922     * @return True if the event was handled by the view, false otherwise.
6923     */
6924    public boolean dispatchTrackballEvent(MotionEvent event) {
6925        if (mInputEventConsistencyVerifier != null) {
6926            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6927        }
6928
6929        return onTrackballEvent(event);
6930    }
6931
6932    /**
6933     * Dispatch a generic motion event.
6934     * <p>
6935     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6936     * are delivered to the view under the pointer.  All other generic motion events are
6937     * delivered to the focused view.  Hover events are handled specially and are delivered
6938     * to {@link #onHoverEvent(MotionEvent)}.
6939     * </p>
6940     *
6941     * @param event The motion event to be dispatched.
6942     * @return True if the event was handled by the view, false otherwise.
6943     */
6944    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6945        if (mInputEventConsistencyVerifier != null) {
6946            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6947        }
6948
6949        final int source = event.getSource();
6950        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6951            final int action = event.getAction();
6952            if (action == MotionEvent.ACTION_HOVER_ENTER
6953                    || action == MotionEvent.ACTION_HOVER_MOVE
6954                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6955                if (dispatchHoverEvent(event)) {
6956                    return true;
6957                }
6958            } else if (dispatchGenericPointerEvent(event)) {
6959                return true;
6960            }
6961        } else if (dispatchGenericFocusedEvent(event)) {
6962            return true;
6963        }
6964
6965        if (dispatchGenericMotionEventInternal(event)) {
6966            return true;
6967        }
6968
6969        if (mInputEventConsistencyVerifier != null) {
6970            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6971        }
6972        return false;
6973    }
6974
6975    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6976        //noinspection SimplifiableIfStatement
6977        ListenerInfo li = mListenerInfo;
6978        if (li != null && li.mOnGenericMotionListener != null
6979                && (mViewFlags & ENABLED_MASK) == ENABLED
6980                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6981            return true;
6982        }
6983
6984        if (onGenericMotionEvent(event)) {
6985            return true;
6986        }
6987
6988        if (mInputEventConsistencyVerifier != null) {
6989            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6990        }
6991        return false;
6992    }
6993
6994    /**
6995     * Dispatch a hover event.
6996     * <p>
6997     * Do not call this method directly.
6998     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6999     * </p>
7000     *
7001     * @param event The motion event to be dispatched.
7002     * @return True if the event was handled by the view, false otherwise.
7003     */
7004    protected boolean dispatchHoverEvent(MotionEvent event) {
7005        //noinspection SimplifiableIfStatement
7006        ListenerInfo li = mListenerInfo;
7007        if (li != null && li.mOnHoverListener != null
7008                && (mViewFlags & ENABLED_MASK) == ENABLED
7009                && li.mOnHoverListener.onHover(this, event)) {
7010            return true;
7011        }
7012
7013        return onHoverEvent(event);
7014    }
7015
7016    /**
7017     * Returns true if the view has a child to which it has recently sent
7018     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7019     * it does not have a hovered child, then it must be the innermost hovered view.
7020     * @hide
7021     */
7022    protected boolean hasHoveredChild() {
7023        return false;
7024    }
7025
7026    /**
7027     * Dispatch a generic motion event to the view under the first pointer.
7028     * <p>
7029     * Do not call this method directly.
7030     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7031     * </p>
7032     *
7033     * @param event The motion event to be dispatched.
7034     * @return True if the event was handled by the view, false otherwise.
7035     */
7036    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7037        return false;
7038    }
7039
7040    /**
7041     * Dispatch a generic motion event to the currently focused view.
7042     * <p>
7043     * Do not call this method directly.
7044     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7045     * </p>
7046     *
7047     * @param event The motion event to be dispatched.
7048     * @return True if the event was handled by the view, false otherwise.
7049     */
7050    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7051        return false;
7052    }
7053
7054    /**
7055     * Dispatch a pointer event.
7056     * <p>
7057     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7058     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7059     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7060     * and should not be expected to handle other pointing device features.
7061     * </p>
7062     *
7063     * @param event The motion event to be dispatched.
7064     * @return True if the event was handled by the view, false otherwise.
7065     * @hide
7066     */
7067    public final boolean dispatchPointerEvent(MotionEvent event) {
7068        if (event.isTouchEvent()) {
7069            return dispatchTouchEvent(event);
7070        } else {
7071            return dispatchGenericMotionEvent(event);
7072        }
7073    }
7074
7075    /**
7076     * Called when the window containing this view gains or loses window focus.
7077     * ViewGroups should override to route to their children.
7078     *
7079     * @param hasFocus True if the window containing this view now has focus,
7080     *        false otherwise.
7081     */
7082    public void dispatchWindowFocusChanged(boolean hasFocus) {
7083        onWindowFocusChanged(hasFocus);
7084    }
7085
7086    /**
7087     * Called when the window containing this view gains or loses focus.  Note
7088     * that this is separate from view focus: to receive key events, both
7089     * your view and its window must have focus.  If a window is displayed
7090     * on top of yours that takes input focus, then your own window will lose
7091     * focus but the view focus will remain unchanged.
7092     *
7093     * @param hasWindowFocus True if the window containing this view now has
7094     *        focus, false otherwise.
7095     */
7096    public void onWindowFocusChanged(boolean hasWindowFocus) {
7097        InputMethodManager imm = InputMethodManager.peekInstance();
7098        if (!hasWindowFocus) {
7099            if (isPressed()) {
7100                setPressed(false);
7101            }
7102            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7103                imm.focusOut(this);
7104            }
7105            removeLongPressCallback();
7106            removeTapCallback();
7107            onFocusLost();
7108        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7109            imm.focusIn(this);
7110        }
7111        refreshDrawableState();
7112    }
7113
7114    /**
7115     * Returns true if this view is in a window that currently has window focus.
7116     * Note that this is not the same as the view itself having focus.
7117     *
7118     * @return True if this view is in a window that currently has window focus.
7119     */
7120    public boolean hasWindowFocus() {
7121        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7122    }
7123
7124    /**
7125     * Dispatch a view visibility change down the view hierarchy.
7126     * ViewGroups should override to route to their children.
7127     * @param changedView The view whose visibility changed. Could be 'this' or
7128     * an ancestor view.
7129     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7130     * {@link #INVISIBLE} or {@link #GONE}.
7131     */
7132    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7133        onVisibilityChanged(changedView, visibility);
7134    }
7135
7136    /**
7137     * Called when the visibility of the view or an ancestor of the view is changed.
7138     * @param changedView The view whose visibility changed. Could be 'this' or
7139     * an ancestor view.
7140     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7141     * {@link #INVISIBLE} or {@link #GONE}.
7142     */
7143    protected void onVisibilityChanged(View changedView, int visibility) {
7144        if (visibility == VISIBLE) {
7145            if (mAttachInfo != null) {
7146                initialAwakenScrollBars();
7147            } else {
7148                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7149            }
7150        }
7151    }
7152
7153    /**
7154     * Dispatch a hint about whether this view is displayed. For instance, when
7155     * a View moves out of the screen, it might receives a display hint indicating
7156     * the view is not displayed. Applications should not <em>rely</em> on this hint
7157     * as there is no guarantee that they will receive one.
7158     *
7159     * @param hint A hint about whether or not this view is displayed:
7160     * {@link #VISIBLE} or {@link #INVISIBLE}.
7161     */
7162    public void dispatchDisplayHint(int hint) {
7163        onDisplayHint(hint);
7164    }
7165
7166    /**
7167     * Gives this view a hint about whether is displayed or not. For instance, when
7168     * a View moves out of the screen, it might receives a display hint indicating
7169     * the view is not displayed. Applications should not <em>rely</em> on this hint
7170     * as there is no guarantee that they will receive one.
7171     *
7172     * @param hint A hint about whether or not this view is displayed:
7173     * {@link #VISIBLE} or {@link #INVISIBLE}.
7174     */
7175    protected void onDisplayHint(int hint) {
7176    }
7177
7178    /**
7179     * Dispatch a window visibility change down the view hierarchy.
7180     * ViewGroups should override to route to their children.
7181     *
7182     * @param visibility The new visibility of the window.
7183     *
7184     * @see #onWindowVisibilityChanged(int)
7185     */
7186    public void dispatchWindowVisibilityChanged(int visibility) {
7187        onWindowVisibilityChanged(visibility);
7188    }
7189
7190    /**
7191     * Called when the window containing has change its visibility
7192     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7193     * that this tells you whether or not your window is being made visible
7194     * to the window manager; this does <em>not</em> tell you whether or not
7195     * your window is obscured by other windows on the screen, even if it
7196     * is itself visible.
7197     *
7198     * @param visibility The new visibility of the window.
7199     */
7200    protected void onWindowVisibilityChanged(int visibility) {
7201        if (visibility == VISIBLE) {
7202            initialAwakenScrollBars();
7203        }
7204    }
7205
7206    /**
7207     * Returns the current visibility of the window this view is attached to
7208     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7209     *
7210     * @return Returns the current visibility of the view's window.
7211     */
7212    public int getWindowVisibility() {
7213        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7214    }
7215
7216    /**
7217     * Retrieve the overall visible display size in which the window this view is
7218     * attached to has been positioned in.  This takes into account screen
7219     * decorations above the window, for both cases where the window itself
7220     * is being position inside of them or the window is being placed under
7221     * then and covered insets are used for the window to position its content
7222     * inside.  In effect, this tells you the available area where content can
7223     * be placed and remain visible to users.
7224     *
7225     * <p>This function requires an IPC back to the window manager to retrieve
7226     * the requested information, so should not be used in performance critical
7227     * code like drawing.
7228     *
7229     * @param outRect Filled in with the visible display frame.  If the view
7230     * is not attached to a window, this is simply the raw display size.
7231     */
7232    public void getWindowVisibleDisplayFrame(Rect outRect) {
7233        if (mAttachInfo != null) {
7234            try {
7235                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7236            } catch (RemoteException e) {
7237                return;
7238            }
7239            // XXX This is really broken, and probably all needs to be done
7240            // in the window manager, and we need to know more about whether
7241            // we want the area behind or in front of the IME.
7242            final Rect insets = mAttachInfo.mVisibleInsets;
7243            outRect.left += insets.left;
7244            outRect.top += insets.top;
7245            outRect.right -= insets.right;
7246            outRect.bottom -= insets.bottom;
7247            return;
7248        }
7249        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7250        d.getRectSize(outRect);
7251    }
7252
7253    /**
7254     * Dispatch a notification about a resource configuration change down
7255     * the view hierarchy.
7256     * ViewGroups should override to route to their children.
7257     *
7258     * @param newConfig The new resource configuration.
7259     *
7260     * @see #onConfigurationChanged(android.content.res.Configuration)
7261     */
7262    public void dispatchConfigurationChanged(Configuration newConfig) {
7263        onConfigurationChanged(newConfig);
7264    }
7265
7266    /**
7267     * Called when the current configuration of the resources being used
7268     * by the application have changed.  You can use this to decide when
7269     * to reload resources that can changed based on orientation and other
7270     * configuration characterstics.  You only need to use this if you are
7271     * not relying on the normal {@link android.app.Activity} mechanism of
7272     * recreating the activity instance upon a configuration change.
7273     *
7274     * @param newConfig The new resource configuration.
7275     */
7276    protected void onConfigurationChanged(Configuration newConfig) {
7277    }
7278
7279    /**
7280     * Private function to aggregate all per-view attributes in to the view
7281     * root.
7282     */
7283    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7284        performCollectViewAttributes(attachInfo, visibility);
7285    }
7286
7287    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7288        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7289            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7290                attachInfo.mKeepScreenOn = true;
7291            }
7292            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7293            ListenerInfo li = mListenerInfo;
7294            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7295                attachInfo.mHasSystemUiListeners = true;
7296            }
7297        }
7298    }
7299
7300    void needGlobalAttributesUpdate(boolean force) {
7301        final AttachInfo ai = mAttachInfo;
7302        if (ai != null) {
7303            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7304                    || ai.mHasSystemUiListeners) {
7305                ai.mRecomputeGlobalAttributes = true;
7306            }
7307        }
7308    }
7309
7310    /**
7311     * Returns whether the device is currently in touch mode.  Touch mode is entered
7312     * once the user begins interacting with the device by touch, and affects various
7313     * things like whether focus is always visible to the user.
7314     *
7315     * @return Whether the device is in touch mode.
7316     */
7317    @ViewDebug.ExportedProperty
7318    public boolean isInTouchMode() {
7319        if (mAttachInfo != null) {
7320            return mAttachInfo.mInTouchMode;
7321        } else {
7322            return ViewRootImpl.isInTouchMode();
7323        }
7324    }
7325
7326    /**
7327     * Returns the context the view is running in, through which it can
7328     * access the current theme, resources, etc.
7329     *
7330     * @return The view's Context.
7331     */
7332    @ViewDebug.CapturedViewProperty
7333    public final Context getContext() {
7334        return mContext;
7335    }
7336
7337    /**
7338     * Handle a key event before it is processed by any input method
7339     * associated with the view hierarchy.  This can be used to intercept
7340     * key events in special situations before the IME consumes them; a
7341     * typical example would be handling the BACK key to update the application's
7342     * UI instead of allowing the IME to see it and close itself.
7343     *
7344     * @param keyCode The value in event.getKeyCode().
7345     * @param event Description of the key event.
7346     * @return If you handled the event, return true. If you want to allow the
7347     *         event to be handled by the next receiver, return false.
7348     */
7349    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7350        return false;
7351    }
7352
7353    /**
7354     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7355     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7356     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7357     * is released, if the view is enabled and clickable.
7358     *
7359     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7360     * although some may elect to do so in some situations. Do not rely on this to
7361     * catch software key presses.
7362     *
7363     * @param keyCode A key code that represents the button pressed, from
7364     *                {@link android.view.KeyEvent}.
7365     * @param event   The KeyEvent object that defines the button action.
7366     */
7367    public boolean onKeyDown(int keyCode, KeyEvent event) {
7368        boolean result = false;
7369
7370        switch (keyCode) {
7371            case KeyEvent.KEYCODE_DPAD_CENTER:
7372            case KeyEvent.KEYCODE_ENTER: {
7373                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7374                    return true;
7375                }
7376                // Long clickable items don't necessarily have to be clickable
7377                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7378                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7379                        (event.getRepeatCount() == 0)) {
7380                    setPressed(true);
7381                    checkForLongClick(0);
7382                    return true;
7383                }
7384                break;
7385            }
7386        }
7387        return result;
7388    }
7389
7390    /**
7391     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7392     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7393     * the event).
7394     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7395     * although some may elect to do so in some situations. Do not rely on this to
7396     * catch software key presses.
7397     */
7398    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7399        return false;
7400    }
7401
7402    /**
7403     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7404     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7405     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7406     * {@link KeyEvent#KEYCODE_ENTER} is released.
7407     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7408     * although some may elect to do so in some situations. Do not rely on this to
7409     * catch software key presses.
7410     *
7411     * @param keyCode A key code that represents the button pressed, from
7412     *                {@link android.view.KeyEvent}.
7413     * @param event   The KeyEvent object that defines the button action.
7414     */
7415    public boolean onKeyUp(int keyCode, KeyEvent event) {
7416        boolean result = false;
7417
7418        switch (keyCode) {
7419            case KeyEvent.KEYCODE_DPAD_CENTER:
7420            case KeyEvent.KEYCODE_ENTER: {
7421                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7422                    return true;
7423                }
7424                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7425                    setPressed(false);
7426
7427                    if (!mHasPerformedLongPress) {
7428                        // This is a tap, so remove the longpress check
7429                        removeLongPressCallback();
7430
7431                        result = performClick();
7432                    }
7433                }
7434                break;
7435            }
7436        }
7437        return result;
7438    }
7439
7440    /**
7441     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7442     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7443     * the event).
7444     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7445     * although some may elect to do so in some situations. Do not rely on this to
7446     * catch software key presses.
7447     *
7448     * @param keyCode     A key code that represents the button pressed, from
7449     *                    {@link android.view.KeyEvent}.
7450     * @param repeatCount The number of times the action was made.
7451     * @param event       The KeyEvent object that defines the button action.
7452     */
7453    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7454        return false;
7455    }
7456
7457    /**
7458     * Called on the focused view when a key shortcut event is not handled.
7459     * Override this method to implement local key shortcuts for the View.
7460     * Key shortcuts can also be implemented by setting the
7461     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7462     *
7463     * @param keyCode The value in event.getKeyCode().
7464     * @param event Description of the key event.
7465     * @return If you handled the event, return true. If you want to allow the
7466     *         event to be handled by the next receiver, return false.
7467     */
7468    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7469        return false;
7470    }
7471
7472    /**
7473     * Check whether the called view is a text editor, in which case it
7474     * would make sense to automatically display a soft input window for
7475     * it.  Subclasses should override this if they implement
7476     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7477     * a call on that method would return a non-null InputConnection, and
7478     * they are really a first-class editor that the user would normally
7479     * start typing on when the go into a window containing your view.
7480     *
7481     * <p>The default implementation always returns false.  This does
7482     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7483     * will not be called or the user can not otherwise perform edits on your
7484     * view; it is just a hint to the system that this is not the primary
7485     * purpose of this view.
7486     *
7487     * @return Returns true if this view is a text editor, else false.
7488     */
7489    public boolean onCheckIsTextEditor() {
7490        return false;
7491    }
7492
7493    /**
7494     * Create a new InputConnection for an InputMethod to interact
7495     * with the view.  The default implementation returns null, since it doesn't
7496     * support input methods.  You can override this to implement such support.
7497     * This is only needed for views that take focus and text input.
7498     *
7499     * <p>When implementing this, you probably also want to implement
7500     * {@link #onCheckIsTextEditor()} to indicate you will return a
7501     * non-null InputConnection.
7502     *
7503     * @param outAttrs Fill in with attribute information about the connection.
7504     */
7505    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7506        return null;
7507    }
7508
7509    /**
7510     * Called by the {@link android.view.inputmethod.InputMethodManager}
7511     * when a view who is not the current
7512     * input connection target is trying to make a call on the manager.  The
7513     * default implementation returns false; you can override this to return
7514     * true for certain views if you are performing InputConnection proxying
7515     * to them.
7516     * @param view The View that is making the InputMethodManager call.
7517     * @return Return true to allow the call, false to reject.
7518     */
7519    public boolean checkInputConnectionProxy(View view) {
7520        return false;
7521    }
7522
7523    /**
7524     * Show the context menu for this view. It is not safe to hold on to the
7525     * menu after returning from this method.
7526     *
7527     * You should normally not overload this method. Overload
7528     * {@link #onCreateContextMenu(ContextMenu)} or define an
7529     * {@link OnCreateContextMenuListener} to add items to the context menu.
7530     *
7531     * @param menu The context menu to populate
7532     */
7533    public void createContextMenu(ContextMenu menu) {
7534        ContextMenuInfo menuInfo = getContextMenuInfo();
7535
7536        // Sets the current menu info so all items added to menu will have
7537        // my extra info set.
7538        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7539
7540        onCreateContextMenu(menu);
7541        ListenerInfo li = mListenerInfo;
7542        if (li != null && li.mOnCreateContextMenuListener != null) {
7543            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7544        }
7545
7546        // Clear the extra information so subsequent items that aren't mine don't
7547        // have my extra info.
7548        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7549
7550        if (mParent != null) {
7551            mParent.createContextMenu(menu);
7552        }
7553    }
7554
7555    /**
7556     * Views should implement this if they have extra information to associate
7557     * with the context menu. The return result is supplied as a parameter to
7558     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7559     * callback.
7560     *
7561     * @return Extra information about the item for which the context menu
7562     *         should be shown. This information will vary across different
7563     *         subclasses of View.
7564     */
7565    protected ContextMenuInfo getContextMenuInfo() {
7566        return null;
7567    }
7568
7569    /**
7570     * Views should implement this if the view itself is going to add items to
7571     * the context menu.
7572     *
7573     * @param menu the context menu to populate
7574     */
7575    protected void onCreateContextMenu(ContextMenu menu) {
7576    }
7577
7578    /**
7579     * Implement this method to handle trackball motion events.  The
7580     * <em>relative</em> movement of the trackball since the last event
7581     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7582     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7583     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7584     * they will often be fractional values, representing the more fine-grained
7585     * movement information available from a trackball).
7586     *
7587     * @param event The motion event.
7588     * @return True if the event was handled, false otherwise.
7589     */
7590    public boolean onTrackballEvent(MotionEvent event) {
7591        return false;
7592    }
7593
7594    /**
7595     * Implement this method to handle generic motion events.
7596     * <p>
7597     * Generic motion events describe joystick movements, mouse hovers, track pad
7598     * touches, scroll wheel movements and other input events.  The
7599     * {@link MotionEvent#getSource() source} of the motion event specifies
7600     * the class of input that was received.  Implementations of this method
7601     * must examine the bits in the source before processing the event.
7602     * The following code example shows how this is done.
7603     * </p><p>
7604     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7605     * are delivered to the view under the pointer.  All other generic motion events are
7606     * delivered to the focused view.
7607     * </p>
7608     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7609     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7610     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7611     *             // process the joystick movement...
7612     *             return true;
7613     *         }
7614     *     }
7615     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7616     *         switch (event.getAction()) {
7617     *             case MotionEvent.ACTION_HOVER_MOVE:
7618     *                 // process the mouse hover movement...
7619     *                 return true;
7620     *             case MotionEvent.ACTION_SCROLL:
7621     *                 // process the scroll wheel movement...
7622     *                 return true;
7623     *         }
7624     *     }
7625     *     return super.onGenericMotionEvent(event);
7626     * }</pre>
7627     *
7628     * @param event The generic motion event being processed.
7629     * @return True if the event was handled, false otherwise.
7630     */
7631    public boolean onGenericMotionEvent(MotionEvent event) {
7632        return false;
7633    }
7634
7635    /**
7636     * Implement this method to handle hover events.
7637     * <p>
7638     * This method is called whenever a pointer is hovering into, over, or out of the
7639     * bounds of a view and the view is not currently being touched.
7640     * Hover events are represented as pointer events with action
7641     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7642     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7643     * </p>
7644     * <ul>
7645     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7646     * when the pointer enters the bounds of the view.</li>
7647     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7648     * when the pointer has already entered the bounds of the view and has moved.</li>
7649     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7650     * when the pointer has exited the bounds of the view or when the pointer is
7651     * about to go down due to a button click, tap, or similar user action that
7652     * causes the view to be touched.</li>
7653     * </ul>
7654     * <p>
7655     * The view should implement this method to return true to indicate that it is
7656     * handling the hover event, such as by changing its drawable state.
7657     * </p><p>
7658     * The default implementation calls {@link #setHovered} to update the hovered state
7659     * of the view when a hover enter or hover exit event is received, if the view
7660     * is enabled and is clickable.  The default implementation also sends hover
7661     * accessibility events.
7662     * </p>
7663     *
7664     * @param event The motion event that describes the hover.
7665     * @return True if the view handled the hover event.
7666     *
7667     * @see #isHovered
7668     * @see #setHovered
7669     * @see #onHoverChanged
7670     */
7671    public boolean onHoverEvent(MotionEvent event) {
7672        // The root view may receive hover (or touch) events that are outside the bounds of
7673        // the window.  This code ensures that we only send accessibility events for
7674        // hovers that are actually within the bounds of the root view.
7675        final int action = event.getActionMasked();
7676        if (!mSendingHoverAccessibilityEvents) {
7677            if ((action == MotionEvent.ACTION_HOVER_ENTER
7678                    || action == MotionEvent.ACTION_HOVER_MOVE)
7679                    && !hasHoveredChild()
7680                    && pointInView(event.getX(), event.getY())) {
7681                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7682                mSendingHoverAccessibilityEvents = true;
7683            }
7684        } else {
7685            if (action == MotionEvent.ACTION_HOVER_EXIT
7686                    || (action == MotionEvent.ACTION_MOVE
7687                            && !pointInView(event.getX(), event.getY()))) {
7688                mSendingHoverAccessibilityEvents = false;
7689                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7690                // If the window does not have input focus we take away accessibility
7691                // focus as soon as the user stop hovering over the view.
7692                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7693                    getViewRootImpl().setAccessibilityFocus(null, null);
7694                }
7695            }
7696        }
7697
7698        if (isHoverable()) {
7699            switch (action) {
7700                case MotionEvent.ACTION_HOVER_ENTER:
7701                    setHovered(true);
7702                    break;
7703                case MotionEvent.ACTION_HOVER_EXIT:
7704                    setHovered(false);
7705                    break;
7706            }
7707
7708            // Dispatch the event to onGenericMotionEvent before returning true.
7709            // This is to provide compatibility with existing applications that
7710            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7711            // break because of the new default handling for hoverable views
7712            // in onHoverEvent.
7713            // Note that onGenericMotionEvent will be called by default when
7714            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7715            dispatchGenericMotionEventInternal(event);
7716            return true;
7717        }
7718
7719        return false;
7720    }
7721
7722    /**
7723     * Returns true if the view should handle {@link #onHoverEvent}
7724     * by calling {@link #setHovered} to change its hovered state.
7725     *
7726     * @return True if the view is hoverable.
7727     */
7728    private boolean isHoverable() {
7729        final int viewFlags = mViewFlags;
7730        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7731            return false;
7732        }
7733
7734        return (viewFlags & CLICKABLE) == CLICKABLE
7735                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7736    }
7737
7738    /**
7739     * Returns true if the view is currently hovered.
7740     *
7741     * @return True if the view is currently hovered.
7742     *
7743     * @see #setHovered
7744     * @see #onHoverChanged
7745     */
7746    @ViewDebug.ExportedProperty
7747    public boolean isHovered() {
7748        return (mPrivateFlags & HOVERED) != 0;
7749    }
7750
7751    /**
7752     * Sets whether the view is currently hovered.
7753     * <p>
7754     * Calling this method also changes the drawable state of the view.  This
7755     * enables the view to react to hover by using different drawable resources
7756     * to change its appearance.
7757     * </p><p>
7758     * The {@link #onHoverChanged} method is called when the hovered state changes.
7759     * </p>
7760     *
7761     * @param hovered True if the view is hovered.
7762     *
7763     * @see #isHovered
7764     * @see #onHoverChanged
7765     */
7766    public void setHovered(boolean hovered) {
7767        if (hovered) {
7768            if ((mPrivateFlags & HOVERED) == 0) {
7769                mPrivateFlags |= HOVERED;
7770                refreshDrawableState();
7771                onHoverChanged(true);
7772            }
7773        } else {
7774            if ((mPrivateFlags & HOVERED) != 0) {
7775                mPrivateFlags &= ~HOVERED;
7776                refreshDrawableState();
7777                onHoverChanged(false);
7778            }
7779        }
7780    }
7781
7782    /**
7783     * Implement this method to handle hover state changes.
7784     * <p>
7785     * This method is called whenever the hover state changes as a result of a
7786     * call to {@link #setHovered}.
7787     * </p>
7788     *
7789     * @param hovered The current hover state, as returned by {@link #isHovered}.
7790     *
7791     * @see #isHovered
7792     * @see #setHovered
7793     */
7794    public void onHoverChanged(boolean hovered) {
7795    }
7796
7797    /**
7798     * Implement this method to handle touch screen motion events.
7799     *
7800     * @param event The motion event.
7801     * @return True if the event was handled, false otherwise.
7802     */
7803    public boolean onTouchEvent(MotionEvent event) {
7804        final int viewFlags = mViewFlags;
7805
7806        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7807            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7808                setPressed(false);
7809            }
7810            // A disabled view that is clickable still consumes the touch
7811            // events, it just doesn't respond to them.
7812            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7813                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7814        }
7815
7816        if (mTouchDelegate != null) {
7817            if (mTouchDelegate.onTouchEvent(event)) {
7818                return true;
7819            }
7820        }
7821
7822        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7823                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7824            switch (event.getAction()) {
7825                case MotionEvent.ACTION_UP:
7826                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7827                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7828                        // take focus if we don't have it already and we should in
7829                        // touch mode.
7830                        boolean focusTaken = false;
7831                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7832                            focusTaken = requestFocus();
7833                        }
7834
7835                        if (prepressed) {
7836                            // The button is being released before we actually
7837                            // showed it as pressed.  Make it show the pressed
7838                            // state now (before scheduling the click) to ensure
7839                            // the user sees it.
7840                            setPressed(true);
7841                       }
7842
7843                        if (!mHasPerformedLongPress) {
7844                            // This is a tap, so remove the longpress check
7845                            removeLongPressCallback();
7846
7847                            // Only perform take click actions if we were in the pressed state
7848                            if (!focusTaken) {
7849                                // Use a Runnable and post this rather than calling
7850                                // performClick directly. This lets other visual state
7851                                // of the view update before click actions start.
7852                                if (mPerformClick == null) {
7853                                    mPerformClick = new PerformClick();
7854                                }
7855                                if (!post(mPerformClick)) {
7856                                    performClick();
7857                                }
7858                            }
7859                        }
7860
7861                        if (mUnsetPressedState == null) {
7862                            mUnsetPressedState = new UnsetPressedState();
7863                        }
7864
7865                        if (prepressed) {
7866                            postDelayed(mUnsetPressedState,
7867                                    ViewConfiguration.getPressedStateDuration());
7868                        } else if (!post(mUnsetPressedState)) {
7869                            // If the post failed, unpress right now
7870                            mUnsetPressedState.run();
7871                        }
7872                        removeTapCallback();
7873                    }
7874                    break;
7875
7876                case MotionEvent.ACTION_DOWN:
7877                    mHasPerformedLongPress = false;
7878
7879                    if (performButtonActionOnTouchDown(event)) {
7880                        break;
7881                    }
7882
7883                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7884                    boolean isInScrollingContainer = isInScrollingContainer();
7885
7886                    // For views inside a scrolling container, delay the pressed feedback for
7887                    // a short period in case this is a scroll.
7888                    if (isInScrollingContainer) {
7889                        mPrivateFlags |= PREPRESSED;
7890                        if (mPendingCheckForTap == null) {
7891                            mPendingCheckForTap = new CheckForTap();
7892                        }
7893                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7894                    } else {
7895                        // Not inside a scrolling container, so show the feedback right away
7896                        setPressed(true);
7897                        checkForLongClick(0);
7898                    }
7899                    break;
7900
7901                case MotionEvent.ACTION_CANCEL:
7902                    setPressed(false);
7903                    removeTapCallback();
7904                    break;
7905
7906                case MotionEvent.ACTION_MOVE:
7907                    final int x = (int) event.getX();
7908                    final int y = (int) event.getY();
7909
7910                    // Be lenient about moving outside of buttons
7911                    if (!pointInView(x, y, mTouchSlop)) {
7912                        // Outside button
7913                        removeTapCallback();
7914                        if ((mPrivateFlags & PRESSED) != 0) {
7915                            // Remove any future long press/tap checks
7916                            removeLongPressCallback();
7917
7918                            setPressed(false);
7919                        }
7920                    }
7921                    break;
7922            }
7923            return true;
7924        }
7925
7926        return false;
7927    }
7928
7929    /**
7930     * @hide
7931     */
7932    public boolean isInScrollingContainer() {
7933        ViewParent p = getParent();
7934        while (p != null && p instanceof ViewGroup) {
7935            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7936                return true;
7937            }
7938            p = p.getParent();
7939        }
7940        return false;
7941    }
7942
7943    /**
7944     * Remove the longpress detection timer.
7945     */
7946    private void removeLongPressCallback() {
7947        if (mPendingCheckForLongPress != null) {
7948          removeCallbacks(mPendingCheckForLongPress);
7949        }
7950    }
7951
7952    /**
7953     * Remove the pending click action
7954     */
7955    private void removePerformClickCallback() {
7956        if (mPerformClick != null) {
7957            removeCallbacks(mPerformClick);
7958        }
7959    }
7960
7961    /**
7962     * Remove the prepress detection timer.
7963     */
7964    private void removeUnsetPressCallback() {
7965        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7966            setPressed(false);
7967            removeCallbacks(mUnsetPressedState);
7968        }
7969    }
7970
7971    /**
7972     * Remove the tap detection timer.
7973     */
7974    private void removeTapCallback() {
7975        if (mPendingCheckForTap != null) {
7976            mPrivateFlags &= ~PREPRESSED;
7977            removeCallbacks(mPendingCheckForTap);
7978        }
7979    }
7980
7981    /**
7982     * Cancels a pending long press.  Your subclass can use this if you
7983     * want the context menu to come up if the user presses and holds
7984     * at the same place, but you don't want it to come up if they press
7985     * and then move around enough to cause scrolling.
7986     */
7987    public void cancelLongPress() {
7988        removeLongPressCallback();
7989
7990        /*
7991         * The prepressed state handled by the tap callback is a display
7992         * construct, but the tap callback will post a long press callback
7993         * less its own timeout. Remove it here.
7994         */
7995        removeTapCallback();
7996    }
7997
7998    /**
7999     * Remove the pending callback for sending a
8000     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8001     */
8002    private void removeSendViewScrolledAccessibilityEventCallback() {
8003        if (mSendViewScrolledAccessibilityEvent != null) {
8004            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8005            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8006        }
8007    }
8008
8009    /**
8010     * Sets the TouchDelegate for this View.
8011     */
8012    public void setTouchDelegate(TouchDelegate delegate) {
8013        mTouchDelegate = delegate;
8014    }
8015
8016    /**
8017     * Gets the TouchDelegate for this View.
8018     */
8019    public TouchDelegate getTouchDelegate() {
8020        return mTouchDelegate;
8021    }
8022
8023    /**
8024     * Set flags controlling behavior of this view.
8025     *
8026     * @param flags Constant indicating the value which should be set
8027     * @param mask Constant indicating the bit range that should be changed
8028     */
8029    void setFlags(int flags, int mask) {
8030        int old = mViewFlags;
8031        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8032
8033        int changed = mViewFlags ^ old;
8034        if (changed == 0) {
8035            return;
8036        }
8037        int privateFlags = mPrivateFlags;
8038
8039        /* Check if the FOCUSABLE bit has changed */
8040        if (((changed & FOCUSABLE_MASK) != 0) &&
8041                ((privateFlags & HAS_BOUNDS) !=0)) {
8042            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8043                    && ((privateFlags & FOCUSED) != 0)) {
8044                /* Give up focus if we are no longer focusable */
8045                clearFocus();
8046            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8047                    && ((privateFlags & FOCUSED) == 0)) {
8048                /*
8049                 * Tell the view system that we are now available to take focus
8050                 * if no one else already has it.
8051                 */
8052                if (mParent != null) mParent.focusableViewAvailable(this);
8053            }
8054            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8055                notifyAccessibilityStateChanged();
8056            }
8057        }
8058
8059        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8060            if ((changed & VISIBILITY_MASK) != 0) {
8061                /*
8062                 * If this view is becoming visible, invalidate it in case it changed while
8063                 * it was not visible. Marking it drawn ensures that the invalidation will
8064                 * go through.
8065                 */
8066                mPrivateFlags |= DRAWN;
8067                invalidate(true);
8068
8069                needGlobalAttributesUpdate(true);
8070
8071                // a view becoming visible is worth notifying the parent
8072                // about in case nothing has focus.  even if this specific view
8073                // isn't focusable, it may contain something that is, so let
8074                // the root view try to give this focus if nothing else does.
8075                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8076                    mParent.focusableViewAvailable(this);
8077                }
8078            }
8079        }
8080
8081        /* Check if the GONE bit has changed */
8082        if ((changed & GONE) != 0) {
8083            needGlobalAttributesUpdate(false);
8084            requestLayout();
8085
8086            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8087                if (hasFocus()) clearFocus();
8088                clearAccessibilityFocus();
8089                destroyDrawingCache();
8090                if (mParent instanceof View) {
8091                    // GONE views noop invalidation, so invalidate the parent
8092                    ((View) mParent).invalidate(true);
8093                }
8094                // Mark the view drawn to ensure that it gets invalidated properly the next
8095                // time it is visible and gets invalidated
8096                mPrivateFlags |= DRAWN;
8097            }
8098            if (mAttachInfo != null) {
8099                mAttachInfo.mViewVisibilityChanged = true;
8100            }
8101        }
8102
8103        /* Check if the VISIBLE bit has changed */
8104        if ((changed & INVISIBLE) != 0) {
8105            needGlobalAttributesUpdate(false);
8106            /*
8107             * If this view is becoming invisible, set the DRAWN flag so that
8108             * the next invalidate() will not be skipped.
8109             */
8110            mPrivateFlags |= DRAWN;
8111
8112            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8113                // root view becoming invisible shouldn't clear focus and accessibility focus
8114                if (getRootView() != this) {
8115                    clearFocus();
8116                    clearAccessibilityFocus();
8117                }
8118            }
8119            if (mAttachInfo != null) {
8120                mAttachInfo.mViewVisibilityChanged = true;
8121            }
8122        }
8123
8124        if ((changed & VISIBILITY_MASK) != 0) {
8125            if (mParent instanceof ViewGroup) {
8126                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8127                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8128                ((View) mParent).invalidate(true);
8129            } else if (mParent != null) {
8130                mParent.invalidateChild(this, null);
8131            }
8132            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8133        }
8134
8135        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8136            destroyDrawingCache();
8137        }
8138
8139        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8140            destroyDrawingCache();
8141            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8142            invalidateParentCaches();
8143        }
8144
8145        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8146            destroyDrawingCache();
8147            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8148        }
8149
8150        if ((changed & DRAW_MASK) != 0) {
8151            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8152                if (mBackground != null) {
8153                    mPrivateFlags &= ~SKIP_DRAW;
8154                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8155                } else {
8156                    mPrivateFlags |= SKIP_DRAW;
8157                }
8158            } else {
8159                mPrivateFlags &= ~SKIP_DRAW;
8160            }
8161            requestLayout();
8162            invalidate(true);
8163        }
8164
8165        if ((changed & KEEP_SCREEN_ON) != 0) {
8166            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8167                mParent.recomputeViewAttributes(this);
8168            }
8169        }
8170
8171        if (AccessibilityManager.getInstance(mContext).isEnabled()
8172                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8173                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8174            notifyAccessibilityStateChanged();
8175        }
8176    }
8177
8178    /**
8179     * Change the view's z order in the tree, so it's on top of other sibling
8180     * views
8181     */
8182    public void bringToFront() {
8183        if (mParent != null) {
8184            mParent.bringChildToFront(this);
8185        }
8186    }
8187
8188    /**
8189     * This is called in response to an internal scroll in this view (i.e., the
8190     * view scrolled its own contents). This is typically as a result of
8191     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8192     * called.
8193     *
8194     * @param l Current horizontal scroll origin.
8195     * @param t Current vertical scroll origin.
8196     * @param oldl Previous horizontal scroll origin.
8197     * @param oldt Previous vertical scroll origin.
8198     */
8199    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8200        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8201            postSendViewScrolledAccessibilityEventCallback();
8202        }
8203
8204        mBackgroundSizeChanged = true;
8205
8206        final AttachInfo ai = mAttachInfo;
8207        if (ai != null) {
8208            ai.mViewScrollChanged = true;
8209        }
8210    }
8211
8212    /**
8213     * Interface definition for a callback to be invoked when the layout bounds of a view
8214     * changes due to layout processing.
8215     */
8216    public interface OnLayoutChangeListener {
8217        /**
8218         * Called when the focus state of a view has changed.
8219         *
8220         * @param v The view whose state has changed.
8221         * @param left The new value of the view's left property.
8222         * @param top The new value of the view's top property.
8223         * @param right The new value of the view's right property.
8224         * @param bottom The new value of the view's bottom property.
8225         * @param oldLeft The previous value of the view's left property.
8226         * @param oldTop The previous value of the view's top property.
8227         * @param oldRight The previous value of the view's right property.
8228         * @param oldBottom The previous value of the view's bottom property.
8229         */
8230        void onLayoutChange(View v, int left, int top, int right, int bottom,
8231            int oldLeft, int oldTop, int oldRight, int oldBottom);
8232    }
8233
8234    /**
8235     * This is called during layout when the size of this view has changed. If
8236     * you were just added to the view hierarchy, you're called with the old
8237     * values of 0.
8238     *
8239     * @param w Current width of this view.
8240     * @param h Current height of this view.
8241     * @param oldw Old width of this view.
8242     * @param oldh Old height of this view.
8243     */
8244    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8245    }
8246
8247    /**
8248     * Called by draw to draw the child views. This may be overridden
8249     * by derived classes to gain control just before its children are drawn
8250     * (but after its own view has been drawn).
8251     * @param canvas the canvas on which to draw the view
8252     */
8253    protected void dispatchDraw(Canvas canvas) {
8254
8255    }
8256
8257    /**
8258     * Gets the parent of this view. Note that the parent is a
8259     * ViewParent and not necessarily a View.
8260     *
8261     * @return Parent of this view.
8262     */
8263    public final ViewParent getParent() {
8264        return mParent;
8265    }
8266
8267    /**
8268     * Set the horizontal scrolled position of your view. This will cause a call to
8269     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8270     * invalidated.
8271     * @param value the x position to scroll to
8272     */
8273    public void setScrollX(int value) {
8274        scrollTo(value, mScrollY);
8275    }
8276
8277    /**
8278     * Set the vertical scrolled position of your view. This will cause a call to
8279     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8280     * invalidated.
8281     * @param value the y position to scroll to
8282     */
8283    public void setScrollY(int value) {
8284        scrollTo(mScrollX, value);
8285    }
8286
8287    /**
8288     * Return the scrolled left position of this view. This is the left edge of
8289     * the displayed part of your view. You do not need to draw any pixels
8290     * farther left, since those are outside of the frame of your view on
8291     * screen.
8292     *
8293     * @return The left edge of the displayed part of your view, in pixels.
8294     */
8295    public final int getScrollX() {
8296        return mScrollX;
8297    }
8298
8299    /**
8300     * Return the scrolled top position of this view. This is the top edge of
8301     * the displayed part of your view. You do not need to draw any pixels above
8302     * it, since those are outside of the frame of your view on screen.
8303     *
8304     * @return The top edge of the displayed part of your view, in pixels.
8305     */
8306    public final int getScrollY() {
8307        return mScrollY;
8308    }
8309
8310    /**
8311     * Return the width of the your view.
8312     *
8313     * @return The width of your view, in pixels.
8314     */
8315    @ViewDebug.ExportedProperty(category = "layout")
8316    public final int getWidth() {
8317        return mRight - mLeft;
8318    }
8319
8320    /**
8321     * Return the height of your view.
8322     *
8323     * @return The height of your view, in pixels.
8324     */
8325    @ViewDebug.ExportedProperty(category = "layout")
8326    public final int getHeight() {
8327        return mBottom - mTop;
8328    }
8329
8330    /**
8331     * Return the visible drawing bounds of your view. Fills in the output
8332     * rectangle with the values from getScrollX(), getScrollY(),
8333     * getWidth(), and getHeight().
8334     *
8335     * @param outRect The (scrolled) drawing bounds of the view.
8336     */
8337    public void getDrawingRect(Rect outRect) {
8338        outRect.left = mScrollX;
8339        outRect.top = mScrollY;
8340        outRect.right = mScrollX + (mRight - mLeft);
8341        outRect.bottom = mScrollY + (mBottom - mTop);
8342    }
8343
8344    /**
8345     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8346     * raw width component (that is the result is masked by
8347     * {@link #MEASURED_SIZE_MASK}).
8348     *
8349     * @return The raw measured width of this view.
8350     */
8351    public final int getMeasuredWidth() {
8352        return mMeasuredWidth & MEASURED_SIZE_MASK;
8353    }
8354
8355    /**
8356     * Return the full width measurement information for this view as computed
8357     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8358     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8359     * This should be used during measurement and layout calculations only. Use
8360     * {@link #getWidth()} to see how wide a view is after layout.
8361     *
8362     * @return The measured width of this view as a bit mask.
8363     */
8364    public final int getMeasuredWidthAndState() {
8365        return mMeasuredWidth;
8366    }
8367
8368    /**
8369     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8370     * raw width component (that is the result is masked by
8371     * {@link #MEASURED_SIZE_MASK}).
8372     *
8373     * @return The raw measured height of this view.
8374     */
8375    public final int getMeasuredHeight() {
8376        return mMeasuredHeight & MEASURED_SIZE_MASK;
8377    }
8378
8379    /**
8380     * Return the full height measurement information for this view as computed
8381     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8382     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8383     * This should be used during measurement and layout calculations only. Use
8384     * {@link #getHeight()} to see how wide a view is after layout.
8385     *
8386     * @return The measured width of this view as a bit mask.
8387     */
8388    public final int getMeasuredHeightAndState() {
8389        return mMeasuredHeight;
8390    }
8391
8392    /**
8393     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8394     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8395     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8396     * and the height component is at the shifted bits
8397     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8398     */
8399    public final int getMeasuredState() {
8400        return (mMeasuredWidth&MEASURED_STATE_MASK)
8401                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8402                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8403    }
8404
8405    /**
8406     * The transform matrix of this view, which is calculated based on the current
8407     * roation, scale, and pivot properties.
8408     *
8409     * @see #getRotation()
8410     * @see #getScaleX()
8411     * @see #getScaleY()
8412     * @see #getPivotX()
8413     * @see #getPivotY()
8414     * @return The current transform matrix for the view
8415     */
8416    public Matrix getMatrix() {
8417        if (mTransformationInfo != null) {
8418            updateMatrix();
8419            return mTransformationInfo.mMatrix;
8420        }
8421        return Matrix.IDENTITY_MATRIX;
8422    }
8423
8424    /**
8425     * Utility function to determine if the value is far enough away from zero to be
8426     * considered non-zero.
8427     * @param value A floating point value to check for zero-ness
8428     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8429     */
8430    private static boolean nonzero(float value) {
8431        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8432    }
8433
8434    /**
8435     * Returns true if the transform matrix is the identity matrix.
8436     * Recomputes the matrix if necessary.
8437     *
8438     * @return True if the transform matrix is the identity matrix, false otherwise.
8439     */
8440    final boolean hasIdentityMatrix() {
8441        if (mTransformationInfo != null) {
8442            updateMatrix();
8443            return mTransformationInfo.mMatrixIsIdentity;
8444        }
8445        return true;
8446    }
8447
8448    void ensureTransformationInfo() {
8449        if (mTransformationInfo == null) {
8450            mTransformationInfo = new TransformationInfo();
8451        }
8452    }
8453
8454    /**
8455     * Recomputes the transform matrix if necessary.
8456     */
8457    private void updateMatrix() {
8458        final TransformationInfo info = mTransformationInfo;
8459        if (info == null) {
8460            return;
8461        }
8462        if (info.mMatrixDirty) {
8463            // transform-related properties have changed since the last time someone
8464            // asked for the matrix; recalculate it with the current values
8465
8466            // Figure out if we need to update the pivot point
8467            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8468                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8469                    info.mPrevWidth = mRight - mLeft;
8470                    info.mPrevHeight = mBottom - mTop;
8471                    info.mPivotX = info.mPrevWidth / 2f;
8472                    info.mPivotY = info.mPrevHeight / 2f;
8473                }
8474            }
8475            info.mMatrix.reset();
8476            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8477                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8478                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8479                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8480            } else {
8481                if (info.mCamera == null) {
8482                    info.mCamera = new Camera();
8483                    info.matrix3D = new Matrix();
8484                }
8485                info.mCamera.save();
8486                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8487                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8488                info.mCamera.getMatrix(info.matrix3D);
8489                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8490                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8491                        info.mPivotY + info.mTranslationY);
8492                info.mMatrix.postConcat(info.matrix3D);
8493                info.mCamera.restore();
8494            }
8495            info.mMatrixDirty = false;
8496            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8497            info.mInverseMatrixDirty = true;
8498        }
8499    }
8500
8501    /**
8502     * When searching for a view to focus this rectangle is used when considering if this view is
8503     * a good candidate for receiving focus.
8504     *
8505     * By default, the rectangle is the {@link #getDrawingRect}) of the view.
8506     *
8507     * @param r The rectangle to fill in, in this view's coordinates.
8508     */
8509    public void getFocusRect(Rect r) {
8510        getDrawingRect(r);
8511    }
8512
8513   /**
8514     * Utility method to retrieve the inverse of the current mMatrix property.
8515     * We cache the matrix to avoid recalculating it when transform properties
8516     * have not changed.
8517     *
8518     * @return The inverse of the current matrix of this view.
8519     */
8520    final Matrix getInverseMatrix() {
8521        final TransformationInfo info = mTransformationInfo;
8522        if (info != null) {
8523            updateMatrix();
8524            if (info.mInverseMatrixDirty) {
8525                if (info.mInverseMatrix == null) {
8526                    info.mInverseMatrix = new Matrix();
8527                }
8528                info.mMatrix.invert(info.mInverseMatrix);
8529                info.mInverseMatrixDirty = false;
8530            }
8531            return info.mInverseMatrix;
8532        }
8533        return Matrix.IDENTITY_MATRIX;
8534    }
8535
8536    /**
8537     * Gets the distance along the Z axis from the camera to this view.
8538     *
8539     * @see #setCameraDistance(float)
8540     *
8541     * @return The distance along the Z axis.
8542     */
8543    public float getCameraDistance() {
8544        ensureTransformationInfo();
8545        final float dpi = mResources.getDisplayMetrics().densityDpi;
8546        final TransformationInfo info = mTransformationInfo;
8547        if (info.mCamera == null) {
8548            info.mCamera = new Camera();
8549            info.matrix3D = new Matrix();
8550        }
8551        return -(info.mCamera.getLocationZ() * dpi);
8552    }
8553
8554    /**
8555     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8556     * views are drawn) from the camera to this view. The camera's distance
8557     * affects 3D transformations, for instance rotations around the X and Y
8558     * axis. If the rotationX or rotationY properties are changed and this view is
8559     * large (more than half the size of the screen), it is recommended to always
8560     * use a camera distance that's greater than the height (X axis rotation) or
8561     * the width (Y axis rotation) of this view.</p>
8562     *
8563     * <p>The distance of the camera from the view plane can have an affect on the
8564     * perspective distortion of the view when it is rotated around the x or y axis.
8565     * For example, a large distance will result in a large viewing angle, and there
8566     * will not be much perspective distortion of the view as it rotates. A short
8567     * distance may cause much more perspective distortion upon rotation, and can
8568     * also result in some drawing artifacts if the rotated view ends up partially
8569     * behind the camera (which is why the recommendation is to use a distance at
8570     * least as far as the size of the view, if the view is to be rotated.)</p>
8571     *
8572     * <p>The distance is expressed in "depth pixels." The default distance depends
8573     * on the screen density. For instance, on a medium density display, the
8574     * default distance is 1280. On a high density display, the default distance
8575     * is 1920.</p>
8576     *
8577     * <p>If you want to specify a distance that leads to visually consistent
8578     * results across various densities, use the following formula:</p>
8579     * <pre>
8580     * float scale = context.getResources().getDisplayMetrics().density;
8581     * view.setCameraDistance(distance * scale);
8582     * </pre>
8583     *
8584     * <p>The density scale factor of a high density display is 1.5,
8585     * and 1920 = 1280 * 1.5.</p>
8586     *
8587     * @param distance The distance in "depth pixels", if negative the opposite
8588     *        value is used
8589     *
8590     * @see #setRotationX(float)
8591     * @see #setRotationY(float)
8592     */
8593    public void setCameraDistance(float distance) {
8594        invalidateViewProperty(true, false);
8595
8596        ensureTransformationInfo();
8597        final float dpi = mResources.getDisplayMetrics().densityDpi;
8598        final TransformationInfo info = mTransformationInfo;
8599        if (info.mCamera == null) {
8600            info.mCamera = new Camera();
8601            info.matrix3D = new Matrix();
8602        }
8603
8604        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8605        info.mMatrixDirty = true;
8606
8607        invalidateViewProperty(false, false);
8608        if (mDisplayList != null) {
8609            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8610        }
8611        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8612            // View was rejected last time it was drawn by its parent; this may have changed
8613            invalidateParentIfNeeded();
8614        }
8615    }
8616
8617    /**
8618     * The degrees that the view is rotated around the pivot point.
8619     *
8620     * @see #setRotation(float)
8621     * @see #getPivotX()
8622     * @see #getPivotY()
8623     *
8624     * @return The degrees of rotation.
8625     */
8626    @ViewDebug.ExportedProperty(category = "drawing")
8627    public float getRotation() {
8628        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8629    }
8630
8631    /**
8632     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8633     * result in clockwise rotation.
8634     *
8635     * @param rotation The degrees of rotation.
8636     *
8637     * @see #getRotation()
8638     * @see #getPivotX()
8639     * @see #getPivotY()
8640     * @see #setRotationX(float)
8641     * @see #setRotationY(float)
8642     *
8643     * @attr ref android.R.styleable#View_rotation
8644     */
8645    public void setRotation(float rotation) {
8646        ensureTransformationInfo();
8647        final TransformationInfo info = mTransformationInfo;
8648        if (info.mRotation != rotation) {
8649            // Double-invalidation is necessary to capture view's old and new areas
8650            invalidateViewProperty(true, false);
8651            info.mRotation = rotation;
8652            info.mMatrixDirty = true;
8653            invalidateViewProperty(false, true);
8654            if (mDisplayList != null) {
8655                mDisplayList.setRotation(rotation);
8656            }
8657            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8658                // View was rejected last time it was drawn by its parent; this may have changed
8659                invalidateParentIfNeeded();
8660            }
8661        }
8662    }
8663
8664    /**
8665     * The degrees that the view is rotated around the vertical axis through the pivot point.
8666     *
8667     * @see #getPivotX()
8668     * @see #getPivotY()
8669     * @see #setRotationY(float)
8670     *
8671     * @return The degrees of Y rotation.
8672     */
8673    @ViewDebug.ExportedProperty(category = "drawing")
8674    public float getRotationY() {
8675        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8676    }
8677
8678    /**
8679     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8680     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8681     * down the y axis.
8682     *
8683     * When rotating large views, it is recommended to adjust the camera distance
8684     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8685     *
8686     * @param rotationY The degrees of Y rotation.
8687     *
8688     * @see #getRotationY()
8689     * @see #getPivotX()
8690     * @see #getPivotY()
8691     * @see #setRotation(float)
8692     * @see #setRotationX(float)
8693     * @see #setCameraDistance(float)
8694     *
8695     * @attr ref android.R.styleable#View_rotationY
8696     */
8697    public void setRotationY(float rotationY) {
8698        ensureTransformationInfo();
8699        final TransformationInfo info = mTransformationInfo;
8700        if (info.mRotationY != rotationY) {
8701            invalidateViewProperty(true, false);
8702            info.mRotationY = rotationY;
8703            info.mMatrixDirty = true;
8704            invalidateViewProperty(false, true);
8705            if (mDisplayList != null) {
8706                mDisplayList.setRotationY(rotationY);
8707            }
8708            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8709                // View was rejected last time it was drawn by its parent; this may have changed
8710                invalidateParentIfNeeded();
8711            }
8712        }
8713    }
8714
8715    /**
8716     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8717     *
8718     * @see #getPivotX()
8719     * @see #getPivotY()
8720     * @see #setRotationX(float)
8721     *
8722     * @return The degrees of X rotation.
8723     */
8724    @ViewDebug.ExportedProperty(category = "drawing")
8725    public float getRotationX() {
8726        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8727    }
8728
8729    /**
8730     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8731     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8732     * x axis.
8733     *
8734     * When rotating large views, it is recommended to adjust the camera distance
8735     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8736     *
8737     * @param rotationX The degrees of X rotation.
8738     *
8739     * @see #getRotationX()
8740     * @see #getPivotX()
8741     * @see #getPivotY()
8742     * @see #setRotation(float)
8743     * @see #setRotationY(float)
8744     * @see #setCameraDistance(float)
8745     *
8746     * @attr ref android.R.styleable#View_rotationX
8747     */
8748    public void setRotationX(float rotationX) {
8749        ensureTransformationInfo();
8750        final TransformationInfo info = mTransformationInfo;
8751        if (info.mRotationX != rotationX) {
8752            invalidateViewProperty(true, false);
8753            info.mRotationX = rotationX;
8754            info.mMatrixDirty = true;
8755            invalidateViewProperty(false, true);
8756            if (mDisplayList != null) {
8757                mDisplayList.setRotationX(rotationX);
8758            }
8759            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8760                // View was rejected last time it was drawn by its parent; this may have changed
8761                invalidateParentIfNeeded();
8762            }
8763        }
8764    }
8765
8766    /**
8767     * The amount that the view is scaled in x around the pivot point, as a proportion of
8768     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8769     *
8770     * <p>By default, this is 1.0f.
8771     *
8772     * @see #getPivotX()
8773     * @see #getPivotY()
8774     * @return The scaling factor.
8775     */
8776    @ViewDebug.ExportedProperty(category = "drawing")
8777    public float getScaleX() {
8778        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8779    }
8780
8781    /**
8782     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8783     * the view's unscaled width. A value of 1 means that no scaling is applied.
8784     *
8785     * @param scaleX The scaling factor.
8786     * @see #getPivotX()
8787     * @see #getPivotY()
8788     *
8789     * @attr ref android.R.styleable#View_scaleX
8790     */
8791    public void setScaleX(float scaleX) {
8792        ensureTransformationInfo();
8793        final TransformationInfo info = mTransformationInfo;
8794        if (info.mScaleX != scaleX) {
8795            invalidateViewProperty(true, false);
8796            info.mScaleX = scaleX;
8797            info.mMatrixDirty = true;
8798            invalidateViewProperty(false, true);
8799            if (mDisplayList != null) {
8800                mDisplayList.setScaleX(scaleX);
8801            }
8802            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8803                // View was rejected last time it was drawn by its parent; this may have changed
8804                invalidateParentIfNeeded();
8805            }
8806        }
8807    }
8808
8809    /**
8810     * The amount that the view is scaled in y around the pivot point, as a proportion of
8811     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8812     *
8813     * <p>By default, this is 1.0f.
8814     *
8815     * @see #getPivotX()
8816     * @see #getPivotY()
8817     * @return The scaling factor.
8818     */
8819    @ViewDebug.ExportedProperty(category = "drawing")
8820    public float getScaleY() {
8821        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8822    }
8823
8824    /**
8825     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8826     * the view's unscaled width. A value of 1 means that no scaling is applied.
8827     *
8828     * @param scaleY The scaling factor.
8829     * @see #getPivotX()
8830     * @see #getPivotY()
8831     *
8832     * @attr ref android.R.styleable#View_scaleY
8833     */
8834    public void setScaleY(float scaleY) {
8835        ensureTransformationInfo();
8836        final TransformationInfo info = mTransformationInfo;
8837        if (info.mScaleY != scaleY) {
8838            invalidateViewProperty(true, false);
8839            info.mScaleY = scaleY;
8840            info.mMatrixDirty = true;
8841            invalidateViewProperty(false, true);
8842            if (mDisplayList != null) {
8843                mDisplayList.setScaleY(scaleY);
8844            }
8845            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8846                // View was rejected last time it was drawn by its parent; this may have changed
8847                invalidateParentIfNeeded();
8848            }
8849        }
8850    }
8851
8852    /**
8853     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8854     * and {@link #setScaleX(float) scaled}.
8855     *
8856     * @see #getRotation()
8857     * @see #getScaleX()
8858     * @see #getScaleY()
8859     * @see #getPivotY()
8860     * @return The x location of the pivot point.
8861     *
8862     * @attr ref android.R.styleable#View_transformPivotX
8863     */
8864    @ViewDebug.ExportedProperty(category = "drawing")
8865    public float getPivotX() {
8866        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8867    }
8868
8869    /**
8870     * Sets the x location of the point around which the view is
8871     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8872     * By default, the pivot point is centered on the object.
8873     * Setting this property disables this behavior and causes the view to use only the
8874     * explicitly set pivotX and pivotY values.
8875     *
8876     * @param pivotX The x location of the pivot point.
8877     * @see #getRotation()
8878     * @see #getScaleX()
8879     * @see #getScaleY()
8880     * @see #getPivotY()
8881     *
8882     * @attr ref android.R.styleable#View_transformPivotX
8883     */
8884    public void setPivotX(float pivotX) {
8885        ensureTransformationInfo();
8886        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8887        final TransformationInfo info = mTransformationInfo;
8888        if (info.mPivotX != pivotX) {
8889            invalidateViewProperty(true, false);
8890            info.mPivotX = pivotX;
8891            info.mMatrixDirty = true;
8892            invalidateViewProperty(false, true);
8893            if (mDisplayList != null) {
8894                mDisplayList.setPivotX(pivotX);
8895            }
8896            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8897                // View was rejected last time it was drawn by its parent; this may have changed
8898                invalidateParentIfNeeded();
8899            }
8900        }
8901    }
8902
8903    /**
8904     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8905     * and {@link #setScaleY(float) scaled}.
8906     *
8907     * @see #getRotation()
8908     * @see #getScaleX()
8909     * @see #getScaleY()
8910     * @see #getPivotY()
8911     * @return The y location of the pivot point.
8912     *
8913     * @attr ref android.R.styleable#View_transformPivotY
8914     */
8915    @ViewDebug.ExportedProperty(category = "drawing")
8916    public float getPivotY() {
8917        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8918    }
8919
8920    /**
8921     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8922     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8923     * Setting this property disables this behavior and causes the view to use only the
8924     * explicitly set pivotX and pivotY values.
8925     *
8926     * @param pivotY The y location of the pivot point.
8927     * @see #getRotation()
8928     * @see #getScaleX()
8929     * @see #getScaleY()
8930     * @see #getPivotY()
8931     *
8932     * @attr ref android.R.styleable#View_transformPivotY
8933     */
8934    public void setPivotY(float pivotY) {
8935        ensureTransformationInfo();
8936        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8937        final TransformationInfo info = mTransformationInfo;
8938        if (info.mPivotY != pivotY) {
8939            invalidateViewProperty(true, false);
8940            info.mPivotY = pivotY;
8941            info.mMatrixDirty = true;
8942            invalidateViewProperty(false, true);
8943            if (mDisplayList != null) {
8944                mDisplayList.setPivotY(pivotY);
8945            }
8946            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8947                // View was rejected last time it was drawn by its parent; this may have changed
8948                invalidateParentIfNeeded();
8949            }
8950        }
8951    }
8952
8953    /**
8954     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8955     * completely transparent and 1 means the view is completely opaque.
8956     *
8957     * <p>By default this is 1.0f.
8958     * @return The opacity of the view.
8959     */
8960    @ViewDebug.ExportedProperty(category = "drawing")
8961    public float getAlpha() {
8962        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8963    }
8964
8965    /**
8966     * Returns whether this View has content which overlaps. This function, intended to be
8967     * overridden by specific View types, is an optimization when alpha is set on a view. If
8968     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8969     * and then composited it into place, which can be expensive. If the view has no overlapping
8970     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8971     * An example of overlapping rendering is a TextView with a background image, such as a
8972     * Button. An example of non-overlapping rendering is a TextView with no background, or
8973     * an ImageView with only the foreground image. The default implementation returns true;
8974     * subclasses should override if they have cases which can be optimized.
8975     *
8976     * @return true if the content in this view might overlap, false otherwise.
8977     */
8978    public boolean hasOverlappingRendering() {
8979        return true;
8980    }
8981
8982    /**
8983     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8984     * completely transparent and 1 means the view is completely opaque.</p>
8985     *
8986     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8987     * responsible for applying the opacity itself. Otherwise, calling this method is
8988     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8989     * setting a hardware layer.</p>
8990     *
8991     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8992     * performance implications. It is generally best to use the alpha property sparingly and
8993     * transiently, as in the case of fading animations.</p>
8994     *
8995     * @param alpha The opacity of the view.
8996     *
8997     * @see #setLayerType(int, android.graphics.Paint)
8998     *
8999     * @attr ref android.R.styleable#View_alpha
9000     */
9001    public void setAlpha(float alpha) {
9002        ensureTransformationInfo();
9003        if (mTransformationInfo.mAlpha != alpha) {
9004            mTransformationInfo.mAlpha = alpha;
9005            if (onSetAlpha((int) (alpha * 255))) {
9006                mPrivateFlags |= ALPHA_SET;
9007                // subclass is handling alpha - don't optimize rendering cache invalidation
9008                invalidateParentCaches();
9009                invalidate(true);
9010            } else {
9011                mPrivateFlags &= ~ALPHA_SET;
9012                invalidateViewProperty(true, false);
9013                if (mDisplayList != null) {
9014                    mDisplayList.setAlpha(alpha);
9015                }
9016            }
9017        }
9018    }
9019
9020    /**
9021     * Faster version of setAlpha() which performs the same steps except there are
9022     * no calls to invalidate(). The caller of this function should perform proper invalidation
9023     * on the parent and this object. The return value indicates whether the subclass handles
9024     * alpha (the return value for onSetAlpha()).
9025     *
9026     * @param alpha The new value for the alpha property
9027     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9028     *         the new value for the alpha property is different from the old value
9029     */
9030    boolean setAlphaNoInvalidation(float alpha) {
9031        ensureTransformationInfo();
9032        if (mTransformationInfo.mAlpha != alpha) {
9033            mTransformationInfo.mAlpha = alpha;
9034            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9035            if (subclassHandlesAlpha) {
9036                mPrivateFlags |= ALPHA_SET;
9037                return true;
9038            } else {
9039                mPrivateFlags &= ~ALPHA_SET;
9040                if (mDisplayList != null) {
9041                    mDisplayList.setAlpha(alpha);
9042                }
9043            }
9044        }
9045        return false;
9046    }
9047
9048    /**
9049     * Top position of this view relative to its parent.
9050     *
9051     * @return The top of this view, in pixels.
9052     */
9053    @ViewDebug.CapturedViewProperty
9054    public final int getTop() {
9055        return mTop;
9056    }
9057
9058    /**
9059     * Sets the top position of this view relative to its parent. This method is meant to be called
9060     * by the layout system and should not generally be called otherwise, because the property
9061     * may be changed at any time by the layout.
9062     *
9063     * @param top The top of this view, in pixels.
9064     */
9065    public final void setTop(int top) {
9066        if (top != mTop) {
9067            updateMatrix();
9068            final boolean matrixIsIdentity = mTransformationInfo == null
9069                    || mTransformationInfo.mMatrixIsIdentity;
9070            if (matrixIsIdentity) {
9071                if (mAttachInfo != null) {
9072                    int minTop;
9073                    int yLoc;
9074                    if (top < mTop) {
9075                        minTop = top;
9076                        yLoc = top - mTop;
9077                    } else {
9078                        minTop = mTop;
9079                        yLoc = 0;
9080                    }
9081                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9082                }
9083            } else {
9084                // Double-invalidation is necessary to capture view's old and new areas
9085                invalidate(true);
9086            }
9087
9088            int width = mRight - mLeft;
9089            int oldHeight = mBottom - mTop;
9090
9091            mTop = top;
9092            if (mDisplayList != null) {
9093                mDisplayList.setTop(mTop);
9094            }
9095
9096            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9097
9098            if (!matrixIsIdentity) {
9099                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9100                    // A change in dimension means an auto-centered pivot point changes, too
9101                    mTransformationInfo.mMatrixDirty = true;
9102                }
9103                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9104                invalidate(true);
9105            }
9106            mBackgroundSizeChanged = true;
9107            invalidateParentIfNeeded();
9108            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9109                // View was rejected last time it was drawn by its parent; this may have changed
9110                invalidateParentIfNeeded();
9111            }
9112        }
9113    }
9114
9115    /**
9116     * Bottom position of this view relative to its parent.
9117     *
9118     * @return The bottom of this view, in pixels.
9119     */
9120    @ViewDebug.CapturedViewProperty
9121    public final int getBottom() {
9122        return mBottom;
9123    }
9124
9125    /**
9126     * True if this view has changed since the last time being drawn.
9127     *
9128     * @return The dirty state of this view.
9129     */
9130    public boolean isDirty() {
9131        return (mPrivateFlags & DIRTY_MASK) != 0;
9132    }
9133
9134    /**
9135     * Sets the bottom position of this view relative to its parent. This method is meant to be
9136     * called by the layout system and should not generally be called otherwise, because the
9137     * property may be changed at any time by the layout.
9138     *
9139     * @param bottom The bottom of this view, in pixels.
9140     */
9141    public final void setBottom(int bottom) {
9142        if (bottom != mBottom) {
9143            updateMatrix();
9144            final boolean matrixIsIdentity = mTransformationInfo == null
9145                    || mTransformationInfo.mMatrixIsIdentity;
9146            if (matrixIsIdentity) {
9147                if (mAttachInfo != null) {
9148                    int maxBottom;
9149                    if (bottom < mBottom) {
9150                        maxBottom = mBottom;
9151                    } else {
9152                        maxBottom = bottom;
9153                    }
9154                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9155                }
9156            } else {
9157                // Double-invalidation is necessary to capture view's old and new areas
9158                invalidate(true);
9159            }
9160
9161            int width = mRight - mLeft;
9162            int oldHeight = mBottom - mTop;
9163
9164            mBottom = bottom;
9165            if (mDisplayList != null) {
9166                mDisplayList.setBottom(mBottom);
9167            }
9168
9169            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9170
9171            if (!matrixIsIdentity) {
9172                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9173                    // A change in dimension means an auto-centered pivot point changes, too
9174                    mTransformationInfo.mMatrixDirty = true;
9175                }
9176                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9177                invalidate(true);
9178            }
9179            mBackgroundSizeChanged = true;
9180            invalidateParentIfNeeded();
9181            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9182                // View was rejected last time it was drawn by its parent; this may have changed
9183                invalidateParentIfNeeded();
9184            }
9185        }
9186    }
9187
9188    /**
9189     * Left position of this view relative to its parent.
9190     *
9191     * @return The left edge of this view, in pixels.
9192     */
9193    @ViewDebug.CapturedViewProperty
9194    public final int getLeft() {
9195        return mLeft;
9196    }
9197
9198    /**
9199     * Sets the left position of this view relative to its parent. This method is meant to be called
9200     * by the layout system and should not generally be called otherwise, because the property
9201     * may be changed at any time by the layout.
9202     *
9203     * @param left The bottom of this view, in pixels.
9204     */
9205    public final void setLeft(int left) {
9206        if (left != mLeft) {
9207            updateMatrix();
9208            final boolean matrixIsIdentity = mTransformationInfo == null
9209                    || mTransformationInfo.mMatrixIsIdentity;
9210            if (matrixIsIdentity) {
9211                if (mAttachInfo != null) {
9212                    int minLeft;
9213                    int xLoc;
9214                    if (left < mLeft) {
9215                        minLeft = left;
9216                        xLoc = left - mLeft;
9217                    } else {
9218                        minLeft = mLeft;
9219                        xLoc = 0;
9220                    }
9221                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9222                }
9223            } else {
9224                // Double-invalidation is necessary to capture view's old and new areas
9225                invalidate(true);
9226            }
9227
9228            int oldWidth = mRight - mLeft;
9229            int height = mBottom - mTop;
9230
9231            mLeft = left;
9232            if (mDisplayList != null) {
9233                mDisplayList.setLeft(left);
9234            }
9235
9236            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9237
9238            if (!matrixIsIdentity) {
9239                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9240                    // A change in dimension means an auto-centered pivot point changes, too
9241                    mTransformationInfo.mMatrixDirty = true;
9242                }
9243                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9244                invalidate(true);
9245            }
9246            mBackgroundSizeChanged = true;
9247            invalidateParentIfNeeded();
9248            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9249                // View was rejected last time it was drawn by its parent; this may have changed
9250                invalidateParentIfNeeded();
9251            }
9252        }
9253    }
9254
9255    /**
9256     * Right position of this view relative to its parent.
9257     *
9258     * @return The right edge of this view, in pixels.
9259     */
9260    @ViewDebug.CapturedViewProperty
9261    public final int getRight() {
9262        return mRight;
9263    }
9264
9265    /**
9266     * Sets the right position of this view relative to its parent. This method is meant to be called
9267     * by the layout system and should not generally be called otherwise, because the property
9268     * may be changed at any time by the layout.
9269     *
9270     * @param right The bottom of this view, in pixels.
9271     */
9272    public final void setRight(int right) {
9273        if (right != mRight) {
9274            updateMatrix();
9275            final boolean matrixIsIdentity = mTransformationInfo == null
9276                    || mTransformationInfo.mMatrixIsIdentity;
9277            if (matrixIsIdentity) {
9278                if (mAttachInfo != null) {
9279                    int maxRight;
9280                    if (right < mRight) {
9281                        maxRight = mRight;
9282                    } else {
9283                        maxRight = right;
9284                    }
9285                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9286                }
9287            } else {
9288                // Double-invalidation is necessary to capture view's old and new areas
9289                invalidate(true);
9290            }
9291
9292            int oldWidth = mRight - mLeft;
9293            int height = mBottom - mTop;
9294
9295            mRight = right;
9296            if (mDisplayList != null) {
9297                mDisplayList.setRight(mRight);
9298            }
9299
9300            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9301
9302            if (!matrixIsIdentity) {
9303                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9304                    // A change in dimension means an auto-centered pivot point changes, too
9305                    mTransformationInfo.mMatrixDirty = true;
9306                }
9307                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9308                invalidate(true);
9309            }
9310            mBackgroundSizeChanged = true;
9311            invalidateParentIfNeeded();
9312            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9313                // View was rejected last time it was drawn by its parent; this may have changed
9314                invalidateParentIfNeeded();
9315            }
9316        }
9317    }
9318
9319    /**
9320     * The visual x position of this view, in pixels. This is equivalent to the
9321     * {@link #setTranslationX(float) translationX} property plus the current
9322     * {@link #getLeft() left} property.
9323     *
9324     * @return The visual x position of this view, in pixels.
9325     */
9326    @ViewDebug.ExportedProperty(category = "drawing")
9327    public float getX() {
9328        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9329    }
9330
9331    /**
9332     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9333     * {@link #setTranslationX(float) translationX} property to be the difference between
9334     * the x value passed in and the current {@link #getLeft() left} property.
9335     *
9336     * @param x The visual x position of this view, in pixels.
9337     */
9338    public void setX(float x) {
9339        setTranslationX(x - mLeft);
9340    }
9341
9342    /**
9343     * The visual y position of this view, in pixels. This is equivalent to the
9344     * {@link #setTranslationY(float) translationY} property plus the current
9345     * {@link #getTop() top} property.
9346     *
9347     * @return The visual y position of this view, in pixels.
9348     */
9349    @ViewDebug.ExportedProperty(category = "drawing")
9350    public float getY() {
9351        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9352    }
9353
9354    /**
9355     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9356     * {@link #setTranslationY(float) translationY} property to be the difference between
9357     * the y value passed in and the current {@link #getTop() top} property.
9358     *
9359     * @param y The visual y position of this view, in pixels.
9360     */
9361    public void setY(float y) {
9362        setTranslationY(y - mTop);
9363    }
9364
9365
9366    /**
9367     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9368     * This position is post-layout, in addition to wherever the object's
9369     * layout placed it.
9370     *
9371     * @return The horizontal position of this view relative to its left position, in pixels.
9372     */
9373    @ViewDebug.ExportedProperty(category = "drawing")
9374    public float getTranslationX() {
9375        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9376    }
9377
9378    /**
9379     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9380     * This effectively positions the object post-layout, in addition to wherever the object's
9381     * layout placed it.
9382     *
9383     * @param translationX The horizontal position of this view relative to its left position,
9384     * in pixels.
9385     *
9386     * @attr ref android.R.styleable#View_translationX
9387     */
9388    public void setTranslationX(float translationX) {
9389        ensureTransformationInfo();
9390        final TransformationInfo info = mTransformationInfo;
9391        if (info.mTranslationX != translationX) {
9392            // Double-invalidation is necessary to capture view's old and new areas
9393            invalidateViewProperty(true, false);
9394            info.mTranslationX = translationX;
9395            info.mMatrixDirty = true;
9396            invalidateViewProperty(false, true);
9397            if (mDisplayList != null) {
9398                mDisplayList.setTranslationX(translationX);
9399            }
9400            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9401                // View was rejected last time it was drawn by its parent; this may have changed
9402                invalidateParentIfNeeded();
9403            }
9404        }
9405    }
9406
9407    /**
9408     * The horizontal location of this view relative to its {@link #getTop() top} position.
9409     * This position is post-layout, in addition to wherever the object's
9410     * layout placed it.
9411     *
9412     * @return The vertical position of this view relative to its top position,
9413     * in pixels.
9414     */
9415    @ViewDebug.ExportedProperty(category = "drawing")
9416    public float getTranslationY() {
9417        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9418    }
9419
9420    /**
9421     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9422     * This effectively positions the object post-layout, in addition to wherever the object's
9423     * layout placed it.
9424     *
9425     * @param translationY The vertical position of this view relative to its top position,
9426     * in pixels.
9427     *
9428     * @attr ref android.R.styleable#View_translationY
9429     */
9430    public void setTranslationY(float translationY) {
9431        ensureTransformationInfo();
9432        final TransformationInfo info = mTransformationInfo;
9433        if (info.mTranslationY != translationY) {
9434            invalidateViewProperty(true, false);
9435            info.mTranslationY = translationY;
9436            info.mMatrixDirty = true;
9437            invalidateViewProperty(false, true);
9438            if (mDisplayList != null) {
9439                mDisplayList.setTranslationY(translationY);
9440            }
9441            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9442                // View was rejected last time it was drawn by its parent; this may have changed
9443                invalidateParentIfNeeded();
9444            }
9445        }
9446    }
9447
9448    /**
9449     * Hit rectangle in parent's coordinates
9450     *
9451     * @param outRect The hit rectangle of the view.
9452     */
9453    public void getHitRect(Rect outRect) {
9454        updateMatrix();
9455        final TransformationInfo info = mTransformationInfo;
9456        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9457            outRect.set(mLeft, mTop, mRight, mBottom);
9458        } else {
9459            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9460            tmpRect.set(-info.mPivotX, -info.mPivotY,
9461                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9462            info.mMatrix.mapRect(tmpRect);
9463            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9464                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9465        }
9466    }
9467
9468    /**
9469     * Determines whether the given point, in local coordinates is inside the view.
9470     */
9471    /*package*/ final boolean pointInView(float localX, float localY) {
9472        return localX >= 0 && localX < (mRight - mLeft)
9473                && localY >= 0 && localY < (mBottom - mTop);
9474    }
9475
9476    /**
9477     * Utility method to determine whether the given point, in local coordinates,
9478     * is inside the view, where the area of the view is expanded by the slop factor.
9479     * This method is called while processing touch-move events to determine if the event
9480     * is still within the view.
9481     */
9482    private boolean pointInView(float localX, float localY, float slop) {
9483        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9484                localY < ((mBottom - mTop) + slop);
9485    }
9486
9487    /**
9488     * When a view has focus and the user navigates away from it, the next view is searched for
9489     * starting from the rectangle filled in by this method.
9490     *
9491     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9492     * of the view.  However, if your view maintains some idea of internal selection,
9493     * such as a cursor, or a selected row or column, you should override this method and
9494     * fill in a more specific rectangle.
9495     *
9496     * @param r The rectangle to fill in, in this view's coordinates.
9497     */
9498    public void getFocusedRect(Rect r) {
9499        getDrawingRect(r);
9500    }
9501
9502    /**
9503     * If some part of this view is not clipped by any of its parents, then
9504     * return that area in r in global (root) coordinates. To convert r to local
9505     * coordinates (without taking possible View rotations into account), offset
9506     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9507     * If the view is completely clipped or translated out, return false.
9508     *
9509     * @param r If true is returned, r holds the global coordinates of the
9510     *        visible portion of this view.
9511     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9512     *        between this view and its root. globalOffet may be null.
9513     * @return true if r is non-empty (i.e. part of the view is visible at the
9514     *         root level.
9515     */
9516    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9517        int width = mRight - mLeft;
9518        int height = mBottom - mTop;
9519        if (width > 0 && height > 0) {
9520            r.set(0, 0, width, height);
9521            if (globalOffset != null) {
9522                globalOffset.set(-mScrollX, -mScrollY);
9523            }
9524            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9525        }
9526        return false;
9527    }
9528
9529    public final boolean getGlobalVisibleRect(Rect r) {
9530        return getGlobalVisibleRect(r, null);
9531    }
9532
9533    public final boolean getLocalVisibleRect(Rect r) {
9534        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9535        if (getGlobalVisibleRect(r, offset)) {
9536            r.offset(-offset.x, -offset.y); // make r local
9537            return true;
9538        }
9539        return false;
9540    }
9541
9542    /**
9543     * Offset this view's vertical location by the specified number of pixels.
9544     *
9545     * @param offset the number of pixels to offset the view by
9546     */
9547    public void offsetTopAndBottom(int offset) {
9548        if (offset != 0) {
9549            updateMatrix();
9550            final boolean matrixIsIdentity = mTransformationInfo == null
9551                    || mTransformationInfo.mMatrixIsIdentity;
9552            if (matrixIsIdentity) {
9553                if (mDisplayList != null) {
9554                    invalidateViewProperty(false, false);
9555                } else {
9556                    final ViewParent p = mParent;
9557                    if (p != null && mAttachInfo != null) {
9558                        final Rect r = mAttachInfo.mTmpInvalRect;
9559                        int minTop;
9560                        int maxBottom;
9561                        int yLoc;
9562                        if (offset < 0) {
9563                            minTop = mTop + offset;
9564                            maxBottom = mBottom;
9565                            yLoc = offset;
9566                        } else {
9567                            minTop = mTop;
9568                            maxBottom = mBottom + offset;
9569                            yLoc = 0;
9570                        }
9571                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9572                        p.invalidateChild(this, r);
9573                    }
9574                }
9575            } else {
9576                invalidateViewProperty(false, false);
9577            }
9578
9579            mTop += offset;
9580            mBottom += offset;
9581            if (mDisplayList != null) {
9582                mDisplayList.offsetTopBottom(offset);
9583                invalidateViewProperty(false, false);
9584            } else {
9585                if (!matrixIsIdentity) {
9586                    invalidateViewProperty(false, true);
9587                }
9588                invalidateParentIfNeeded();
9589            }
9590        }
9591    }
9592
9593    /**
9594     * Offset this view's horizontal location by the specified amount of pixels.
9595     *
9596     * @param offset the numer of pixels to offset the view by
9597     */
9598    public void offsetLeftAndRight(int offset) {
9599        if (offset != 0) {
9600            updateMatrix();
9601            final boolean matrixIsIdentity = mTransformationInfo == null
9602                    || mTransformationInfo.mMatrixIsIdentity;
9603            if (matrixIsIdentity) {
9604                if (mDisplayList != null) {
9605                    invalidateViewProperty(false, false);
9606                } else {
9607                    final ViewParent p = mParent;
9608                    if (p != null && mAttachInfo != null) {
9609                        final Rect r = mAttachInfo.mTmpInvalRect;
9610                        int minLeft;
9611                        int maxRight;
9612                        if (offset < 0) {
9613                            minLeft = mLeft + offset;
9614                            maxRight = mRight;
9615                        } else {
9616                            minLeft = mLeft;
9617                            maxRight = mRight + offset;
9618                        }
9619                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9620                        p.invalidateChild(this, r);
9621                    }
9622                }
9623            } else {
9624                invalidateViewProperty(false, false);
9625            }
9626
9627            mLeft += offset;
9628            mRight += offset;
9629            if (mDisplayList != null) {
9630                mDisplayList.offsetLeftRight(offset);
9631                invalidateViewProperty(false, false);
9632            } else {
9633                if (!matrixIsIdentity) {
9634                    invalidateViewProperty(false, true);
9635                }
9636                invalidateParentIfNeeded();
9637            }
9638        }
9639    }
9640
9641    /**
9642     * Get the LayoutParams associated with this view. All views should have
9643     * layout parameters. These supply parameters to the <i>parent</i> of this
9644     * view specifying how it should be arranged. There are many subclasses of
9645     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9646     * of ViewGroup that are responsible for arranging their children.
9647     *
9648     * This method may return null if this View is not attached to a parent
9649     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9650     * was not invoked successfully. When a View is attached to a parent
9651     * ViewGroup, this method must not return null.
9652     *
9653     * @return The LayoutParams associated with this view, or null if no
9654     *         parameters have been set yet
9655     */
9656    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9657    public ViewGroup.LayoutParams getLayoutParams() {
9658        return mLayoutParams;
9659    }
9660
9661    /**
9662     * Set the layout parameters associated with this view. These supply
9663     * parameters to the <i>parent</i> of this view specifying how it should be
9664     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9665     * correspond to the different subclasses of ViewGroup that are responsible
9666     * for arranging their children.
9667     *
9668     * @param params The layout parameters for this view, cannot be null
9669     */
9670    public void setLayoutParams(ViewGroup.LayoutParams params) {
9671        if (params == null) {
9672            throw new NullPointerException("Layout parameters cannot be null");
9673        }
9674        mLayoutParams = params;
9675        if (mParent instanceof ViewGroup) {
9676            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9677        }
9678        requestLayout();
9679    }
9680
9681    /**
9682     * Set the scrolled position of your view. This will cause a call to
9683     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9684     * invalidated.
9685     * @param x the x position to scroll to
9686     * @param y the y position to scroll to
9687     */
9688    public void scrollTo(int x, int y) {
9689        if (mScrollX != x || mScrollY != y) {
9690            int oldX = mScrollX;
9691            int oldY = mScrollY;
9692            mScrollX = x;
9693            mScrollY = y;
9694            invalidateParentCaches();
9695            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9696            if (!awakenScrollBars()) {
9697                postInvalidateOnAnimation();
9698            }
9699        }
9700    }
9701
9702    /**
9703     * Move the scrolled position of your view. This will cause a call to
9704     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9705     * invalidated.
9706     * @param x the amount of pixels to scroll by horizontally
9707     * @param y the amount of pixels to scroll by vertically
9708     */
9709    public void scrollBy(int x, int y) {
9710        scrollTo(mScrollX + x, mScrollY + y);
9711    }
9712
9713    /**
9714     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9715     * animation to fade the scrollbars out after a default delay. If a subclass
9716     * provides animated scrolling, the start delay should equal the duration
9717     * of the scrolling animation.</p>
9718     *
9719     * <p>The animation starts only if at least one of the scrollbars is
9720     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9721     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9722     * this method returns true, and false otherwise. If the animation is
9723     * started, this method calls {@link #invalidate()}; in that case the
9724     * caller should not call {@link #invalidate()}.</p>
9725     *
9726     * <p>This method should be invoked every time a subclass directly updates
9727     * the scroll parameters.</p>
9728     *
9729     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9730     * and {@link #scrollTo(int, int)}.</p>
9731     *
9732     * @return true if the animation is played, false otherwise
9733     *
9734     * @see #awakenScrollBars(int)
9735     * @see #scrollBy(int, int)
9736     * @see #scrollTo(int, int)
9737     * @see #isHorizontalScrollBarEnabled()
9738     * @see #isVerticalScrollBarEnabled()
9739     * @see #setHorizontalScrollBarEnabled(boolean)
9740     * @see #setVerticalScrollBarEnabled(boolean)
9741     */
9742    protected boolean awakenScrollBars() {
9743        return mScrollCache != null &&
9744                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9745    }
9746
9747    /**
9748     * Trigger the scrollbars to draw.
9749     * This method differs from awakenScrollBars() only in its default duration.
9750     * initialAwakenScrollBars() will show the scroll bars for longer than
9751     * usual to give the user more of a chance to notice them.
9752     *
9753     * @return true if the animation is played, false otherwise.
9754     */
9755    private boolean initialAwakenScrollBars() {
9756        return mScrollCache != null &&
9757                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9758    }
9759
9760    /**
9761     * <p>
9762     * Trigger the scrollbars to draw. When invoked this method starts an
9763     * animation to fade the scrollbars out after a fixed delay. If a subclass
9764     * provides animated scrolling, the start delay should equal the duration of
9765     * the scrolling animation.
9766     * </p>
9767     *
9768     * <p>
9769     * The animation starts only if at least one of the scrollbars is enabled,
9770     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9771     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9772     * this method returns true, and false otherwise. If the animation is
9773     * started, this method calls {@link #invalidate()}; in that case the caller
9774     * should not call {@link #invalidate()}.
9775     * </p>
9776     *
9777     * <p>
9778     * This method should be invoked everytime a subclass directly updates the
9779     * scroll parameters.
9780     * </p>
9781     *
9782     * @param startDelay the delay, in milliseconds, after which the animation
9783     *        should start; when the delay is 0, the animation starts
9784     *        immediately
9785     * @return true if the animation is played, false otherwise
9786     *
9787     * @see #scrollBy(int, int)
9788     * @see #scrollTo(int, int)
9789     * @see #isHorizontalScrollBarEnabled()
9790     * @see #isVerticalScrollBarEnabled()
9791     * @see #setHorizontalScrollBarEnabled(boolean)
9792     * @see #setVerticalScrollBarEnabled(boolean)
9793     */
9794    protected boolean awakenScrollBars(int startDelay) {
9795        return awakenScrollBars(startDelay, true);
9796    }
9797
9798    /**
9799     * <p>
9800     * Trigger the scrollbars to draw. When invoked this method starts an
9801     * animation to fade the scrollbars out after a fixed delay. If a subclass
9802     * provides animated scrolling, the start delay should equal the duration of
9803     * the scrolling animation.
9804     * </p>
9805     *
9806     * <p>
9807     * The animation starts only if at least one of the scrollbars is enabled,
9808     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9809     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9810     * this method returns true, and false otherwise. If the animation is
9811     * started, this method calls {@link #invalidate()} if the invalidate parameter
9812     * is set to true; in that case the caller
9813     * should not call {@link #invalidate()}.
9814     * </p>
9815     *
9816     * <p>
9817     * This method should be invoked everytime a subclass directly updates the
9818     * scroll parameters.
9819     * </p>
9820     *
9821     * @param startDelay the delay, in milliseconds, after which the animation
9822     *        should start; when the delay is 0, the animation starts
9823     *        immediately
9824     *
9825     * @param invalidate Wheter this method should call invalidate
9826     *
9827     * @return true if the animation is played, false otherwise
9828     *
9829     * @see #scrollBy(int, int)
9830     * @see #scrollTo(int, int)
9831     * @see #isHorizontalScrollBarEnabled()
9832     * @see #isVerticalScrollBarEnabled()
9833     * @see #setHorizontalScrollBarEnabled(boolean)
9834     * @see #setVerticalScrollBarEnabled(boolean)
9835     */
9836    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9837        final ScrollabilityCache scrollCache = mScrollCache;
9838
9839        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9840            return false;
9841        }
9842
9843        if (scrollCache.scrollBar == null) {
9844            scrollCache.scrollBar = new ScrollBarDrawable();
9845        }
9846
9847        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9848
9849            if (invalidate) {
9850                // Invalidate to show the scrollbars
9851                postInvalidateOnAnimation();
9852            }
9853
9854            if (scrollCache.state == ScrollabilityCache.OFF) {
9855                // FIXME: this is copied from WindowManagerService.
9856                // We should get this value from the system when it
9857                // is possible to do so.
9858                final int KEY_REPEAT_FIRST_DELAY = 750;
9859                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9860            }
9861
9862            // Tell mScrollCache when we should start fading. This may
9863            // extend the fade start time if one was already scheduled
9864            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9865            scrollCache.fadeStartTime = fadeStartTime;
9866            scrollCache.state = ScrollabilityCache.ON;
9867
9868            // Schedule our fader to run, unscheduling any old ones first
9869            if (mAttachInfo != null) {
9870                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9871                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9872            }
9873
9874            return true;
9875        }
9876
9877        return false;
9878    }
9879
9880    /**
9881     * Do not invalidate views which are not visible and which are not running an animation. They
9882     * will not get drawn and they should not set dirty flags as if they will be drawn
9883     */
9884    private boolean skipInvalidate() {
9885        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9886                (!(mParent instanceof ViewGroup) ||
9887                        !((ViewGroup) mParent).isViewTransitioning(this));
9888    }
9889    /**
9890     * Mark the area defined by dirty as needing to be drawn. If the view is
9891     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9892     * in the future. This must be called from a UI thread. To call from a non-UI
9893     * thread, call {@link #postInvalidate()}.
9894     *
9895     * WARNING: This method is destructive to dirty.
9896     * @param dirty the rectangle representing the bounds of the dirty region
9897     */
9898    public void invalidate(Rect dirty) {
9899        if (skipInvalidate()) {
9900            return;
9901        }
9902        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9903                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9904                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9905            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9906            mPrivateFlags |= INVALIDATED;
9907            mPrivateFlags |= DIRTY;
9908            final ViewParent p = mParent;
9909            final AttachInfo ai = mAttachInfo;
9910            //noinspection PointlessBooleanExpression,ConstantConditions
9911            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9912                if (p != null && ai != null && ai.mHardwareAccelerated) {
9913                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9914                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9915                    p.invalidateChild(this, null);
9916                    return;
9917                }
9918            }
9919            if (p != null && ai != null) {
9920                final int scrollX = mScrollX;
9921                final int scrollY = mScrollY;
9922                final Rect r = ai.mTmpInvalRect;
9923                r.set(dirty.left - scrollX, dirty.top - scrollY,
9924                        dirty.right - scrollX, dirty.bottom - scrollY);
9925                mParent.invalidateChild(this, r);
9926            }
9927        }
9928    }
9929
9930    /**
9931     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9932     * The coordinates of the dirty rect are relative to the view.
9933     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9934     * will be called at some point in the future. This must be called from
9935     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9936     * @param l the left position of the dirty region
9937     * @param t the top position of the dirty region
9938     * @param r the right position of the dirty region
9939     * @param b the bottom position of the dirty region
9940     */
9941    public void invalidate(int l, int t, int r, int b) {
9942        if (skipInvalidate()) {
9943            return;
9944        }
9945        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9946                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9947                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9948            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9949            mPrivateFlags |= INVALIDATED;
9950            mPrivateFlags |= DIRTY;
9951            final ViewParent p = mParent;
9952            final AttachInfo ai = mAttachInfo;
9953            //noinspection PointlessBooleanExpression,ConstantConditions
9954            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9955                if (p != null && ai != null && ai.mHardwareAccelerated) {
9956                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9957                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9958                    p.invalidateChild(this, null);
9959                    return;
9960                }
9961            }
9962            if (p != null && ai != null && l < r && t < b) {
9963                final int scrollX = mScrollX;
9964                final int scrollY = mScrollY;
9965                final Rect tmpr = ai.mTmpInvalRect;
9966                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9967                p.invalidateChild(this, tmpr);
9968            }
9969        }
9970    }
9971
9972    /**
9973     * Invalidate the whole view. If the view is visible,
9974     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9975     * the future. This must be called from a UI thread. To call from a non-UI thread,
9976     * call {@link #postInvalidate()}.
9977     */
9978    public void invalidate() {
9979        invalidate(true);
9980    }
9981
9982    /**
9983     * This is where the invalidate() work actually happens. A full invalidate()
9984     * causes the drawing cache to be invalidated, but this function can be called with
9985     * invalidateCache set to false to skip that invalidation step for cases that do not
9986     * need it (for example, a component that remains at the same dimensions with the same
9987     * content).
9988     *
9989     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9990     * well. This is usually true for a full invalidate, but may be set to false if the
9991     * View's contents or dimensions have not changed.
9992     */
9993    void invalidate(boolean invalidateCache) {
9994        if (skipInvalidate()) {
9995            return;
9996        }
9997        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9998                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9999                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10000            mLastIsOpaque = isOpaque();
10001            mPrivateFlags &= ~DRAWN;
10002            mPrivateFlags |= DIRTY;
10003            if (invalidateCache) {
10004                mPrivateFlags |= INVALIDATED;
10005                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10006            }
10007            final AttachInfo ai = mAttachInfo;
10008            final ViewParent p = mParent;
10009            //noinspection PointlessBooleanExpression,ConstantConditions
10010            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10011                if (p != null && ai != null && ai.mHardwareAccelerated) {
10012                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10013                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10014                    p.invalidateChild(this, null);
10015                    return;
10016                }
10017            }
10018
10019            if (p != null && ai != null) {
10020                final Rect r = ai.mTmpInvalRect;
10021                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10022                // Don't call invalidate -- we don't want to internally scroll
10023                // our own bounds
10024                p.invalidateChild(this, r);
10025            }
10026        }
10027    }
10028
10029    /**
10030     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10031     * set any flags or handle all of the cases handled by the default invalidation methods.
10032     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10033     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10034     * walk up the hierarchy, transforming the dirty rect as necessary.
10035     *
10036     * The method also handles normal invalidation logic if display list properties are not
10037     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10038     * backup approach, to handle these cases used in the various property-setting methods.
10039     *
10040     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10041     * are not being used in this view
10042     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10043     * list properties are not being used in this view
10044     */
10045    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10046        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10047            if (invalidateParent) {
10048                invalidateParentCaches();
10049            }
10050            if (forceRedraw) {
10051                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10052            }
10053            invalidate(false);
10054        } else {
10055            final AttachInfo ai = mAttachInfo;
10056            final ViewParent p = mParent;
10057            if (p != null && ai != null) {
10058                final Rect r = ai.mTmpInvalRect;
10059                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10060                if (mParent instanceof ViewGroup) {
10061                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10062                } else {
10063                    mParent.invalidateChild(this, r);
10064                }
10065            }
10066        }
10067    }
10068
10069    /**
10070     * Utility method to transform a given Rect by the current matrix of this view.
10071     */
10072    void transformRect(final Rect rect) {
10073        if (!getMatrix().isIdentity()) {
10074            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10075            boundingRect.set(rect);
10076            getMatrix().mapRect(boundingRect);
10077            rect.set((int) (boundingRect.left - 0.5f),
10078                    (int) (boundingRect.top - 0.5f),
10079                    (int) (boundingRect.right + 0.5f),
10080                    (int) (boundingRect.bottom + 0.5f));
10081        }
10082    }
10083
10084    /**
10085     * Used to indicate that the parent of this view should clear its caches. This functionality
10086     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10087     * which is necessary when various parent-managed properties of the view change, such as
10088     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10089     * clears the parent caches and does not causes an invalidate event.
10090     *
10091     * @hide
10092     */
10093    protected void invalidateParentCaches() {
10094        if (mParent instanceof View) {
10095            ((View) mParent).mPrivateFlags |= INVALIDATED;
10096        }
10097    }
10098
10099    /**
10100     * Used to indicate that the parent of this view should be invalidated. This functionality
10101     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10102     * which is necessary when various parent-managed properties of the view change, such as
10103     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10104     * an invalidation event to the parent.
10105     *
10106     * @hide
10107     */
10108    protected void invalidateParentIfNeeded() {
10109        if (isHardwareAccelerated() && mParent instanceof View) {
10110            ((View) mParent).invalidate(true);
10111        }
10112    }
10113
10114    /**
10115     * Indicates whether this View is opaque. An opaque View guarantees that it will
10116     * draw all the pixels overlapping its bounds using a fully opaque color.
10117     *
10118     * Subclasses of View should override this method whenever possible to indicate
10119     * whether an instance is opaque. Opaque Views are treated in a special way by
10120     * the View hierarchy, possibly allowing it to perform optimizations during
10121     * invalidate/draw passes.
10122     *
10123     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10124     */
10125    @ViewDebug.ExportedProperty(category = "drawing")
10126    public boolean isOpaque() {
10127        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10128                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10129                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10130    }
10131
10132    /**
10133     * @hide
10134     */
10135    protected void computeOpaqueFlags() {
10136        // Opaque if:
10137        //   - Has a background
10138        //   - Background is opaque
10139        //   - Doesn't have scrollbars or scrollbars are inside overlay
10140
10141        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10142            mPrivateFlags |= OPAQUE_BACKGROUND;
10143        } else {
10144            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10145        }
10146
10147        final int flags = mViewFlags;
10148        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10149                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10150            mPrivateFlags |= OPAQUE_SCROLLBARS;
10151        } else {
10152            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10153        }
10154    }
10155
10156    /**
10157     * @hide
10158     */
10159    protected boolean hasOpaqueScrollbars() {
10160        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10161    }
10162
10163    /**
10164     * @return A handler associated with the thread running the View. This
10165     * handler can be used to pump events in the UI events queue.
10166     */
10167    public Handler getHandler() {
10168        if (mAttachInfo != null) {
10169            return mAttachInfo.mHandler;
10170        }
10171        return null;
10172    }
10173
10174    /**
10175     * Gets the view root associated with the View.
10176     * @return The view root, or null if none.
10177     * @hide
10178     */
10179    public ViewRootImpl getViewRootImpl() {
10180        if (mAttachInfo != null) {
10181            return mAttachInfo.mViewRootImpl;
10182        }
10183        return null;
10184    }
10185
10186    /**
10187     * <p>Causes the Runnable to be added to the message queue.
10188     * The runnable will be run on the user interface thread.</p>
10189     *
10190     * <p>This method can be invoked from outside of the UI thread
10191     * only when this View is attached to a window.</p>
10192     *
10193     * @param action The Runnable that will be executed.
10194     *
10195     * @return Returns true if the Runnable was successfully placed in to the
10196     *         message queue.  Returns false on failure, usually because the
10197     *         looper processing the message queue is exiting.
10198     *
10199     * @see #postDelayed
10200     * @see #removeCallbacks
10201     */
10202    public boolean post(Runnable action) {
10203        final AttachInfo attachInfo = mAttachInfo;
10204        if (attachInfo != null) {
10205            return attachInfo.mHandler.post(action);
10206        }
10207        // Assume that post will succeed later
10208        ViewRootImpl.getRunQueue().post(action);
10209        return true;
10210    }
10211
10212    /**
10213     * <p>Causes the Runnable to be added to the message queue, to be run
10214     * after the specified amount of time elapses.
10215     * The runnable will be run on the user interface thread.</p>
10216     *
10217     * <p>This method can be invoked from outside of the UI thread
10218     * only when this View is attached to a window.</p>
10219     *
10220     * @param action The Runnable that will be executed.
10221     * @param delayMillis The delay (in milliseconds) until the Runnable
10222     *        will be executed.
10223     *
10224     * @return true if the Runnable was successfully placed in to the
10225     *         message queue.  Returns false on failure, usually because the
10226     *         looper processing the message queue is exiting.  Note that a
10227     *         result of true does not mean the Runnable will be processed --
10228     *         if the looper is quit before the delivery time of the message
10229     *         occurs then the message will be dropped.
10230     *
10231     * @see #post
10232     * @see #removeCallbacks
10233     */
10234    public boolean postDelayed(Runnable action, long delayMillis) {
10235        final AttachInfo attachInfo = mAttachInfo;
10236        if (attachInfo != null) {
10237            return attachInfo.mHandler.postDelayed(action, delayMillis);
10238        }
10239        // Assume that post will succeed later
10240        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10241        return true;
10242    }
10243
10244    /**
10245     * <p>Causes the Runnable to execute on the next animation time step.
10246     * The runnable will be run on the user interface thread.</p>
10247     *
10248     * <p>This method can be invoked from outside of the UI thread
10249     * only when this View is attached to a window.</p>
10250     *
10251     * @param action The Runnable that will be executed.
10252     *
10253     * @see #postOnAnimationDelayed
10254     * @see #removeCallbacks
10255     */
10256    public void postOnAnimation(Runnable action) {
10257        final AttachInfo attachInfo = mAttachInfo;
10258        if (attachInfo != null) {
10259            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10260                    Choreographer.CALLBACK_ANIMATION, action, null);
10261        } else {
10262            // Assume that post will succeed later
10263            ViewRootImpl.getRunQueue().post(action);
10264        }
10265    }
10266
10267    /**
10268     * <p>Causes the Runnable to execute on the next animation time step,
10269     * after the specified amount of time elapses.
10270     * The runnable will be run on the user interface thread.</p>
10271     *
10272     * <p>This method can be invoked from outside of the UI thread
10273     * only when this View is attached to a window.</p>
10274     *
10275     * @param action The Runnable that will be executed.
10276     * @param delayMillis The delay (in milliseconds) until the Runnable
10277     *        will be executed.
10278     *
10279     * @see #postOnAnimation
10280     * @see #removeCallbacks
10281     */
10282    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10283        final AttachInfo attachInfo = mAttachInfo;
10284        if (attachInfo != null) {
10285            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10286                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10287        } else {
10288            // Assume that post will succeed later
10289            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10290        }
10291    }
10292
10293    /**
10294     * <p>Removes the specified Runnable from the message queue.</p>
10295     *
10296     * <p>This method can be invoked from outside of the UI thread
10297     * only when this View is attached to a window.</p>
10298     *
10299     * @param action The Runnable to remove from the message handling queue
10300     *
10301     * @return true if this view could ask the Handler to remove the Runnable,
10302     *         false otherwise. When the returned value is true, the Runnable
10303     *         may or may not have been actually removed from the message queue
10304     *         (for instance, if the Runnable was not in the queue already.)
10305     *
10306     * @see #post
10307     * @see #postDelayed
10308     * @see #postOnAnimation
10309     * @see #postOnAnimationDelayed
10310     */
10311    public boolean removeCallbacks(Runnable action) {
10312        if (action != null) {
10313            final AttachInfo attachInfo = mAttachInfo;
10314            if (attachInfo != null) {
10315                attachInfo.mHandler.removeCallbacks(action);
10316                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10317                        Choreographer.CALLBACK_ANIMATION, action, null);
10318            } else {
10319                // Assume that post will succeed later
10320                ViewRootImpl.getRunQueue().removeCallbacks(action);
10321            }
10322        }
10323        return true;
10324    }
10325
10326    /**
10327     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10328     * Use this to invalidate the View from a non-UI thread.</p>
10329     *
10330     * <p>This method can be invoked from outside of the UI thread
10331     * only when this View is attached to a window.</p>
10332     *
10333     * @see #invalidate()
10334     * @see #postInvalidateDelayed(long)
10335     */
10336    public void postInvalidate() {
10337        postInvalidateDelayed(0);
10338    }
10339
10340    /**
10341     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10342     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10343     *
10344     * <p>This method can be invoked from outside of the UI thread
10345     * only when this View is attached to a window.</p>
10346     *
10347     * @param left The left coordinate of the rectangle to invalidate.
10348     * @param top The top coordinate of the rectangle to invalidate.
10349     * @param right The right coordinate of the rectangle to invalidate.
10350     * @param bottom The bottom coordinate of the rectangle to invalidate.
10351     *
10352     * @see #invalidate(int, int, int, int)
10353     * @see #invalidate(Rect)
10354     * @see #postInvalidateDelayed(long, int, int, int, int)
10355     */
10356    public void postInvalidate(int left, int top, int right, int bottom) {
10357        postInvalidateDelayed(0, left, top, right, bottom);
10358    }
10359
10360    /**
10361     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10362     * loop. Waits for the specified amount of time.</p>
10363     *
10364     * <p>This method can be invoked from outside of the UI thread
10365     * only when this View is attached to a window.</p>
10366     *
10367     * @param delayMilliseconds the duration in milliseconds to delay the
10368     *         invalidation by
10369     *
10370     * @see #invalidate()
10371     * @see #postInvalidate()
10372     */
10373    public void postInvalidateDelayed(long delayMilliseconds) {
10374        // We try only with the AttachInfo because there's no point in invalidating
10375        // if we are not attached to our window
10376        final AttachInfo attachInfo = mAttachInfo;
10377        if (attachInfo != null) {
10378            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10379        }
10380    }
10381
10382    /**
10383     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10384     * through the event loop. Waits for the specified amount of time.</p>
10385     *
10386     * <p>This method can be invoked from outside of the UI thread
10387     * only when this View is attached to a window.</p>
10388     *
10389     * @param delayMilliseconds the duration in milliseconds to delay the
10390     *         invalidation by
10391     * @param left The left coordinate of the rectangle to invalidate.
10392     * @param top The top coordinate of the rectangle to invalidate.
10393     * @param right The right coordinate of the rectangle to invalidate.
10394     * @param bottom The bottom coordinate of the rectangle to invalidate.
10395     *
10396     * @see #invalidate(int, int, int, int)
10397     * @see #invalidate(Rect)
10398     * @see #postInvalidate(int, int, int, int)
10399     */
10400    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10401            int right, int bottom) {
10402
10403        // We try only with the AttachInfo because there's no point in invalidating
10404        // if we are not attached to our window
10405        final AttachInfo attachInfo = mAttachInfo;
10406        if (attachInfo != null) {
10407            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10408            info.target = this;
10409            info.left = left;
10410            info.top = top;
10411            info.right = right;
10412            info.bottom = bottom;
10413
10414            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10415        }
10416    }
10417
10418    /**
10419     * <p>Cause an invalidate to happen on the next animation time step, typically the
10420     * next display frame.</p>
10421     *
10422     * <p>This method can be invoked from outside of the UI thread
10423     * only when this View is attached to a window.</p>
10424     *
10425     * @see #invalidate()
10426     */
10427    public void postInvalidateOnAnimation() {
10428        // We try only with the AttachInfo because there's no point in invalidating
10429        // if we are not attached to our window
10430        final AttachInfo attachInfo = mAttachInfo;
10431        if (attachInfo != null) {
10432            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10433        }
10434    }
10435
10436    /**
10437     * <p>Cause an invalidate of the specified area to happen on the next animation
10438     * time step, typically the next display frame.</p>
10439     *
10440     * <p>This method can be invoked from outside of the UI thread
10441     * only when this View is attached to a window.</p>
10442     *
10443     * @param left The left coordinate of the rectangle to invalidate.
10444     * @param top The top coordinate of the rectangle to invalidate.
10445     * @param right The right coordinate of the rectangle to invalidate.
10446     * @param bottom The bottom coordinate of the rectangle to invalidate.
10447     *
10448     * @see #invalidate(int, int, int, int)
10449     * @see #invalidate(Rect)
10450     */
10451    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10452        // We try only with the AttachInfo because there's no point in invalidating
10453        // if we are not attached to our window
10454        final AttachInfo attachInfo = mAttachInfo;
10455        if (attachInfo != null) {
10456            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10457            info.target = this;
10458            info.left = left;
10459            info.top = top;
10460            info.right = right;
10461            info.bottom = bottom;
10462
10463            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10464        }
10465    }
10466
10467    /**
10468     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10469     * This event is sent at most once every
10470     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10471     */
10472    private void postSendViewScrolledAccessibilityEventCallback() {
10473        if (mSendViewScrolledAccessibilityEvent == null) {
10474            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10475        }
10476        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10477            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10478            postDelayed(mSendViewScrolledAccessibilityEvent,
10479                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10480        }
10481    }
10482
10483    /**
10484     * Called by a parent to request that a child update its values for mScrollX
10485     * and mScrollY if necessary. This will typically be done if the child is
10486     * animating a scroll using a {@link android.widget.Scroller Scroller}
10487     * object.
10488     */
10489    public void computeScroll() {
10490    }
10491
10492    /**
10493     * <p>Indicate whether the horizontal edges are faded when the view is
10494     * scrolled horizontally.</p>
10495     *
10496     * @return true if the horizontal edges should are faded on scroll, false
10497     *         otherwise
10498     *
10499     * @see #setHorizontalFadingEdgeEnabled(boolean)
10500     *
10501     * @attr ref android.R.styleable#View_requiresFadingEdge
10502     */
10503    public boolean isHorizontalFadingEdgeEnabled() {
10504        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10505    }
10506
10507    /**
10508     * <p>Define whether the horizontal edges should be faded when this view
10509     * is scrolled horizontally.</p>
10510     *
10511     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10512     *                                    be faded when the view is scrolled
10513     *                                    horizontally
10514     *
10515     * @see #isHorizontalFadingEdgeEnabled()
10516     *
10517     * @attr ref android.R.styleable#View_requiresFadingEdge
10518     */
10519    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10520        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10521            if (horizontalFadingEdgeEnabled) {
10522                initScrollCache();
10523            }
10524
10525            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10526        }
10527    }
10528
10529    /**
10530     * <p>Indicate whether the vertical edges are faded when the view is
10531     * scrolled horizontally.</p>
10532     *
10533     * @return true if the vertical edges should are faded on scroll, false
10534     *         otherwise
10535     *
10536     * @see #setVerticalFadingEdgeEnabled(boolean)
10537     *
10538     * @attr ref android.R.styleable#View_requiresFadingEdge
10539     */
10540    public boolean isVerticalFadingEdgeEnabled() {
10541        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10542    }
10543
10544    /**
10545     * <p>Define whether the vertical edges should be faded when this view
10546     * is scrolled vertically.</p>
10547     *
10548     * @param verticalFadingEdgeEnabled true if the vertical edges should
10549     *                                  be faded when the view is scrolled
10550     *                                  vertically
10551     *
10552     * @see #isVerticalFadingEdgeEnabled()
10553     *
10554     * @attr ref android.R.styleable#View_requiresFadingEdge
10555     */
10556    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10557        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10558            if (verticalFadingEdgeEnabled) {
10559                initScrollCache();
10560            }
10561
10562            mViewFlags ^= FADING_EDGE_VERTICAL;
10563        }
10564    }
10565
10566    /**
10567     * Returns the strength, or intensity, of the top faded edge. The strength is
10568     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10569     * returns 0.0 or 1.0 but no value in between.
10570     *
10571     * Subclasses should override this method to provide a smoother fade transition
10572     * when scrolling occurs.
10573     *
10574     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10575     */
10576    protected float getTopFadingEdgeStrength() {
10577        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10578    }
10579
10580    /**
10581     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10582     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10583     * returns 0.0 or 1.0 but no value in between.
10584     *
10585     * Subclasses should override this method to provide a smoother fade transition
10586     * when scrolling occurs.
10587     *
10588     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10589     */
10590    protected float getBottomFadingEdgeStrength() {
10591        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10592                computeVerticalScrollRange() ? 1.0f : 0.0f;
10593    }
10594
10595    /**
10596     * Returns the strength, or intensity, of the left faded edge. The strength is
10597     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10598     * returns 0.0 or 1.0 but no value in between.
10599     *
10600     * Subclasses should override this method to provide a smoother fade transition
10601     * when scrolling occurs.
10602     *
10603     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10604     */
10605    protected float getLeftFadingEdgeStrength() {
10606        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10607    }
10608
10609    /**
10610     * Returns the strength, or intensity, of the right faded edge. The strength is
10611     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10612     * returns 0.0 or 1.0 but no value in between.
10613     *
10614     * Subclasses should override this method to provide a smoother fade transition
10615     * when scrolling occurs.
10616     *
10617     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10618     */
10619    protected float getRightFadingEdgeStrength() {
10620        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10621                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10622    }
10623
10624    /**
10625     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10626     * scrollbar is not drawn by default.</p>
10627     *
10628     * @return true if the horizontal scrollbar should be painted, false
10629     *         otherwise
10630     *
10631     * @see #setHorizontalScrollBarEnabled(boolean)
10632     */
10633    public boolean isHorizontalScrollBarEnabled() {
10634        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10635    }
10636
10637    /**
10638     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10639     * scrollbar is not drawn by default.</p>
10640     *
10641     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10642     *                                   be painted
10643     *
10644     * @see #isHorizontalScrollBarEnabled()
10645     */
10646    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10647        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10648            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10649            computeOpaqueFlags();
10650            resolvePadding();
10651        }
10652    }
10653
10654    /**
10655     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10656     * scrollbar is not drawn by default.</p>
10657     *
10658     * @return true if the vertical scrollbar should be painted, false
10659     *         otherwise
10660     *
10661     * @see #setVerticalScrollBarEnabled(boolean)
10662     */
10663    public boolean isVerticalScrollBarEnabled() {
10664        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10665    }
10666
10667    /**
10668     * <p>Define whether the vertical scrollbar should be drawn or not. The
10669     * scrollbar is not drawn by default.</p>
10670     *
10671     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10672     *                                 be painted
10673     *
10674     * @see #isVerticalScrollBarEnabled()
10675     */
10676    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10677        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10678            mViewFlags ^= SCROLLBARS_VERTICAL;
10679            computeOpaqueFlags();
10680            resolvePadding();
10681        }
10682    }
10683
10684    /**
10685     * @hide
10686     */
10687    protected void recomputePadding() {
10688        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10689    }
10690
10691    /**
10692     * Define whether scrollbars will fade when the view is not scrolling.
10693     *
10694     * @param fadeScrollbars wheter to enable fading
10695     *
10696     * @attr ref android.R.styleable#View_fadeScrollbars
10697     */
10698    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10699        initScrollCache();
10700        final ScrollabilityCache scrollabilityCache = mScrollCache;
10701        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10702        if (fadeScrollbars) {
10703            scrollabilityCache.state = ScrollabilityCache.OFF;
10704        } else {
10705            scrollabilityCache.state = ScrollabilityCache.ON;
10706        }
10707    }
10708
10709    /**
10710     *
10711     * Returns true if scrollbars will fade when this view is not scrolling
10712     *
10713     * @return true if scrollbar fading is enabled
10714     *
10715     * @attr ref android.R.styleable#View_fadeScrollbars
10716     */
10717    public boolean isScrollbarFadingEnabled() {
10718        return mScrollCache != null && mScrollCache.fadeScrollBars;
10719    }
10720
10721    /**
10722     *
10723     * Returns the delay before scrollbars fade.
10724     *
10725     * @return the delay before scrollbars fade
10726     *
10727     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10728     */
10729    public int getScrollBarDefaultDelayBeforeFade() {
10730        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10731                mScrollCache.scrollBarDefaultDelayBeforeFade;
10732    }
10733
10734    /**
10735     * Define the delay before scrollbars fade.
10736     *
10737     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10738     *
10739     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10740     */
10741    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10742        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10743    }
10744
10745    /**
10746     *
10747     * Returns the scrollbar fade duration.
10748     *
10749     * @return the scrollbar fade duration
10750     *
10751     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10752     */
10753    public int getScrollBarFadeDuration() {
10754        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10755                mScrollCache.scrollBarFadeDuration;
10756    }
10757
10758    /**
10759     * Define the scrollbar fade duration.
10760     *
10761     * @param scrollBarFadeDuration - the scrollbar fade duration
10762     *
10763     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10764     */
10765    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10766        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10767    }
10768
10769    /**
10770     *
10771     * Returns the scrollbar size.
10772     *
10773     * @return the scrollbar size
10774     *
10775     * @attr ref android.R.styleable#View_scrollbarSize
10776     */
10777    public int getScrollBarSize() {
10778        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10779                mScrollCache.scrollBarSize;
10780    }
10781
10782    /**
10783     * Define the scrollbar size.
10784     *
10785     * @param scrollBarSize - the scrollbar size
10786     *
10787     * @attr ref android.R.styleable#View_scrollbarSize
10788     */
10789    public void setScrollBarSize(int scrollBarSize) {
10790        getScrollCache().scrollBarSize = scrollBarSize;
10791    }
10792
10793    /**
10794     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10795     * inset. When inset, they add to the padding of the view. And the scrollbars
10796     * can be drawn inside the padding area or on the edge of the view. For example,
10797     * if a view has a background drawable and you want to draw the scrollbars
10798     * inside the padding specified by the drawable, you can use
10799     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10800     * appear at the edge of the view, ignoring the padding, then you can use
10801     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10802     * @param style the style of the scrollbars. Should be one of
10803     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10804     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10805     * @see #SCROLLBARS_INSIDE_OVERLAY
10806     * @see #SCROLLBARS_INSIDE_INSET
10807     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10808     * @see #SCROLLBARS_OUTSIDE_INSET
10809     *
10810     * @attr ref android.R.styleable#View_scrollbarStyle
10811     */
10812    public void setScrollBarStyle(int style) {
10813        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10814            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10815            computeOpaqueFlags();
10816            resolvePadding();
10817        }
10818    }
10819
10820    /**
10821     * <p>Returns the current scrollbar style.</p>
10822     * @return the current scrollbar style
10823     * @see #SCROLLBARS_INSIDE_OVERLAY
10824     * @see #SCROLLBARS_INSIDE_INSET
10825     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10826     * @see #SCROLLBARS_OUTSIDE_INSET
10827     *
10828     * @attr ref android.R.styleable#View_scrollbarStyle
10829     */
10830    @ViewDebug.ExportedProperty(mapping = {
10831            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10832            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10833            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10834            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10835    })
10836    public int getScrollBarStyle() {
10837        return mViewFlags & SCROLLBARS_STYLE_MASK;
10838    }
10839
10840    /**
10841     * <p>Compute the horizontal range that the horizontal scrollbar
10842     * represents.</p>
10843     *
10844     * <p>The range is expressed in arbitrary units that must be the same as the
10845     * units used by {@link #computeHorizontalScrollExtent()} and
10846     * {@link #computeHorizontalScrollOffset()}.</p>
10847     *
10848     * <p>The default range is the drawing width of this view.</p>
10849     *
10850     * @return the total horizontal range represented by the horizontal
10851     *         scrollbar
10852     *
10853     * @see #computeHorizontalScrollExtent()
10854     * @see #computeHorizontalScrollOffset()
10855     * @see android.widget.ScrollBarDrawable
10856     */
10857    protected int computeHorizontalScrollRange() {
10858        return getWidth();
10859    }
10860
10861    /**
10862     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10863     * within the horizontal range. This value is used to compute the position
10864     * of the thumb within the scrollbar's track.</p>
10865     *
10866     * <p>The range is expressed in arbitrary units that must be the same as the
10867     * units used by {@link #computeHorizontalScrollRange()} and
10868     * {@link #computeHorizontalScrollExtent()}.</p>
10869     *
10870     * <p>The default offset is the scroll offset of this view.</p>
10871     *
10872     * @return the horizontal offset of the scrollbar's thumb
10873     *
10874     * @see #computeHorizontalScrollRange()
10875     * @see #computeHorizontalScrollExtent()
10876     * @see android.widget.ScrollBarDrawable
10877     */
10878    protected int computeHorizontalScrollOffset() {
10879        return mScrollX;
10880    }
10881
10882    /**
10883     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10884     * within the horizontal range. This value is used to compute the length
10885     * of the thumb within the scrollbar's track.</p>
10886     *
10887     * <p>The range is expressed in arbitrary units that must be the same as the
10888     * units used by {@link #computeHorizontalScrollRange()} and
10889     * {@link #computeHorizontalScrollOffset()}.</p>
10890     *
10891     * <p>The default extent is the drawing width of this view.</p>
10892     *
10893     * @return the horizontal extent of the scrollbar's thumb
10894     *
10895     * @see #computeHorizontalScrollRange()
10896     * @see #computeHorizontalScrollOffset()
10897     * @see android.widget.ScrollBarDrawable
10898     */
10899    protected int computeHorizontalScrollExtent() {
10900        return getWidth();
10901    }
10902
10903    /**
10904     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10905     *
10906     * <p>The range is expressed in arbitrary units that must be the same as the
10907     * units used by {@link #computeVerticalScrollExtent()} and
10908     * {@link #computeVerticalScrollOffset()}.</p>
10909     *
10910     * @return the total vertical range represented by the vertical scrollbar
10911     *
10912     * <p>The default range is the drawing height of this view.</p>
10913     *
10914     * @see #computeVerticalScrollExtent()
10915     * @see #computeVerticalScrollOffset()
10916     * @see android.widget.ScrollBarDrawable
10917     */
10918    protected int computeVerticalScrollRange() {
10919        return getHeight();
10920    }
10921
10922    /**
10923     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10924     * within the horizontal range. This value is used to compute the position
10925     * of the thumb within the scrollbar's track.</p>
10926     *
10927     * <p>The range is expressed in arbitrary units that must be the same as the
10928     * units used by {@link #computeVerticalScrollRange()} and
10929     * {@link #computeVerticalScrollExtent()}.</p>
10930     *
10931     * <p>The default offset is the scroll offset of this view.</p>
10932     *
10933     * @return the vertical offset of the scrollbar's thumb
10934     *
10935     * @see #computeVerticalScrollRange()
10936     * @see #computeVerticalScrollExtent()
10937     * @see android.widget.ScrollBarDrawable
10938     */
10939    protected int computeVerticalScrollOffset() {
10940        return mScrollY;
10941    }
10942
10943    /**
10944     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10945     * within the vertical range. This value is used to compute the length
10946     * of the thumb within the scrollbar's track.</p>
10947     *
10948     * <p>The range is expressed in arbitrary units that must be the same as the
10949     * units used by {@link #computeVerticalScrollRange()} and
10950     * {@link #computeVerticalScrollOffset()}.</p>
10951     *
10952     * <p>The default extent is the drawing height of this view.</p>
10953     *
10954     * @return the vertical extent of the scrollbar's thumb
10955     *
10956     * @see #computeVerticalScrollRange()
10957     * @see #computeVerticalScrollOffset()
10958     * @see android.widget.ScrollBarDrawable
10959     */
10960    protected int computeVerticalScrollExtent() {
10961        return getHeight();
10962    }
10963
10964    /**
10965     * Check if this view can be scrolled horizontally in a certain direction.
10966     *
10967     * @param direction Negative to check scrolling left, positive to check scrolling right.
10968     * @return true if this view can be scrolled in the specified direction, false otherwise.
10969     */
10970    public boolean canScrollHorizontally(int direction) {
10971        final int offset = computeHorizontalScrollOffset();
10972        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10973        if (range == 0) return false;
10974        if (direction < 0) {
10975            return offset > 0;
10976        } else {
10977            return offset < range - 1;
10978        }
10979    }
10980
10981    /**
10982     * Check if this view can be scrolled vertically in a certain direction.
10983     *
10984     * @param direction Negative to check scrolling up, positive to check scrolling down.
10985     * @return true if this view can be scrolled in the specified direction, false otherwise.
10986     */
10987    public boolean canScrollVertically(int direction) {
10988        final int offset = computeVerticalScrollOffset();
10989        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10990        if (range == 0) return false;
10991        if (direction < 0) {
10992            return offset > 0;
10993        } else {
10994            return offset < range - 1;
10995        }
10996    }
10997
10998    /**
10999     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11000     * scrollbars are painted only if they have been awakened first.</p>
11001     *
11002     * @param canvas the canvas on which to draw the scrollbars
11003     *
11004     * @see #awakenScrollBars(int)
11005     */
11006    protected final void onDrawScrollBars(Canvas canvas) {
11007        // scrollbars are drawn only when the animation is running
11008        final ScrollabilityCache cache = mScrollCache;
11009        if (cache != null) {
11010
11011            int state = cache.state;
11012
11013            if (state == ScrollabilityCache.OFF) {
11014                return;
11015            }
11016
11017            boolean invalidate = false;
11018
11019            if (state == ScrollabilityCache.FADING) {
11020                // We're fading -- get our fade interpolation
11021                if (cache.interpolatorValues == null) {
11022                    cache.interpolatorValues = new float[1];
11023                }
11024
11025                float[] values = cache.interpolatorValues;
11026
11027                // Stops the animation if we're done
11028                if (cache.scrollBarInterpolator.timeToValues(values) ==
11029                        Interpolator.Result.FREEZE_END) {
11030                    cache.state = ScrollabilityCache.OFF;
11031                } else {
11032                    cache.scrollBar.setAlpha(Math.round(values[0]));
11033                }
11034
11035                // This will make the scroll bars inval themselves after
11036                // drawing. We only want this when we're fading so that
11037                // we prevent excessive redraws
11038                invalidate = true;
11039            } else {
11040                // We're just on -- but we may have been fading before so
11041                // reset alpha
11042                cache.scrollBar.setAlpha(255);
11043            }
11044
11045
11046            final int viewFlags = mViewFlags;
11047
11048            final boolean drawHorizontalScrollBar =
11049                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11050            final boolean drawVerticalScrollBar =
11051                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11052                && !isVerticalScrollBarHidden();
11053
11054            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11055                final int width = mRight - mLeft;
11056                final int height = mBottom - mTop;
11057
11058                final ScrollBarDrawable scrollBar = cache.scrollBar;
11059
11060                final int scrollX = mScrollX;
11061                final int scrollY = mScrollY;
11062                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11063
11064                int left, top, right, bottom;
11065
11066                if (drawHorizontalScrollBar) {
11067                    int size = scrollBar.getSize(false);
11068                    if (size <= 0) {
11069                        size = cache.scrollBarSize;
11070                    }
11071
11072                    scrollBar.setParameters(computeHorizontalScrollRange(),
11073                                            computeHorizontalScrollOffset(),
11074                                            computeHorizontalScrollExtent(), false);
11075                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11076                            getVerticalScrollbarWidth() : 0;
11077                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11078                    left = scrollX + (mPaddingLeft & inside);
11079                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11080                    bottom = top + size;
11081                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11082                    if (invalidate) {
11083                        invalidate(left, top, right, bottom);
11084                    }
11085                }
11086
11087                if (drawVerticalScrollBar) {
11088                    int size = scrollBar.getSize(true);
11089                    if (size <= 0) {
11090                        size = cache.scrollBarSize;
11091                    }
11092
11093                    scrollBar.setParameters(computeVerticalScrollRange(),
11094                                            computeVerticalScrollOffset(),
11095                                            computeVerticalScrollExtent(), true);
11096                    switch (mVerticalScrollbarPosition) {
11097                        default:
11098                        case SCROLLBAR_POSITION_DEFAULT:
11099                        case SCROLLBAR_POSITION_RIGHT:
11100                            left = scrollX + width - size - (mUserPaddingRight & inside);
11101                            break;
11102                        case SCROLLBAR_POSITION_LEFT:
11103                            left = scrollX + (mUserPaddingLeft & inside);
11104                            break;
11105                    }
11106                    top = scrollY + (mPaddingTop & inside);
11107                    right = left + size;
11108                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11109                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11110                    if (invalidate) {
11111                        invalidate(left, top, right, bottom);
11112                    }
11113                }
11114            }
11115        }
11116    }
11117
11118    /**
11119     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11120     * FastScroller is visible.
11121     * @return whether to temporarily hide the vertical scrollbar
11122     * @hide
11123     */
11124    protected boolean isVerticalScrollBarHidden() {
11125        return false;
11126    }
11127
11128    /**
11129     * <p>Draw the horizontal scrollbar if
11130     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11131     *
11132     * @param canvas the canvas on which to draw the scrollbar
11133     * @param scrollBar the scrollbar's drawable
11134     *
11135     * @see #isHorizontalScrollBarEnabled()
11136     * @see #computeHorizontalScrollRange()
11137     * @see #computeHorizontalScrollExtent()
11138     * @see #computeHorizontalScrollOffset()
11139     * @see android.widget.ScrollBarDrawable
11140     * @hide
11141     */
11142    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11143            int l, int t, int r, int b) {
11144        scrollBar.setBounds(l, t, r, b);
11145        scrollBar.draw(canvas);
11146    }
11147
11148    /**
11149     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11150     * returns true.</p>
11151     *
11152     * @param canvas the canvas on which to draw the scrollbar
11153     * @param scrollBar the scrollbar's drawable
11154     *
11155     * @see #isVerticalScrollBarEnabled()
11156     * @see #computeVerticalScrollRange()
11157     * @see #computeVerticalScrollExtent()
11158     * @see #computeVerticalScrollOffset()
11159     * @see android.widget.ScrollBarDrawable
11160     * @hide
11161     */
11162    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11163            int l, int t, int r, int b) {
11164        scrollBar.setBounds(l, t, r, b);
11165        scrollBar.draw(canvas);
11166    }
11167
11168    /**
11169     * Implement this to do your drawing.
11170     *
11171     * @param canvas the canvas on which the background will be drawn
11172     */
11173    protected void onDraw(Canvas canvas) {
11174    }
11175
11176    /*
11177     * Caller is responsible for calling requestLayout if necessary.
11178     * (This allows addViewInLayout to not request a new layout.)
11179     */
11180    void assignParent(ViewParent parent) {
11181        if (mParent == null) {
11182            mParent = parent;
11183        } else if (parent == null) {
11184            mParent = null;
11185        } else {
11186            throw new RuntimeException("view " + this + " being added, but"
11187                    + " it already has a parent");
11188        }
11189    }
11190
11191    /**
11192     * This is called when the view is attached to a window.  At this point it
11193     * has a Surface and will start drawing.  Note that this function is
11194     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11195     * however it may be called any time before the first onDraw -- including
11196     * before or after {@link #onMeasure(int, int)}.
11197     *
11198     * @see #onDetachedFromWindow()
11199     */
11200    protected void onAttachedToWindow() {
11201        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11202            mParent.requestTransparentRegion(this);
11203        }
11204
11205        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11206            initialAwakenScrollBars();
11207            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11208        }
11209
11210        jumpDrawablesToCurrentState();
11211
11212        // Order is important here: LayoutDirection MUST be resolved before Padding
11213        // and TextDirection
11214        resolveLayoutDirection();
11215        resolvePadding();
11216        resolveTextDirection();
11217        resolveTextAlignment();
11218
11219        clearAccessibilityFocus();
11220        if (isFocused()) {
11221            InputMethodManager imm = InputMethodManager.peekInstance();
11222            imm.focusIn(this);
11223        }
11224
11225        if (mAttachInfo != null && mDisplayList != null) {
11226            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11227        }
11228    }
11229
11230    /**
11231     * @see #onScreenStateChanged(int)
11232     */
11233    void dispatchScreenStateChanged(int screenState) {
11234        onScreenStateChanged(screenState);
11235    }
11236
11237    /**
11238     * This method is called whenever the state of the screen this view is
11239     * attached to changes. A state change will usually occurs when the screen
11240     * turns on or off (whether it happens automatically or the user does it
11241     * manually.)
11242     *
11243     * @param screenState The new state of the screen. Can be either
11244     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11245     */
11246    public void onScreenStateChanged(int screenState) {
11247    }
11248
11249    /**
11250     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11251     */
11252    private boolean hasRtlSupport() {
11253        return mContext.getApplicationInfo().hasRtlSupport();
11254    }
11255
11256    /**
11257     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11258     * that the parent directionality can and will be resolved before its children.
11259     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11260     */
11261    public void resolveLayoutDirection() {
11262        // Clear any previous layout direction resolution
11263        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11264
11265        if (hasRtlSupport()) {
11266            // Set resolved depending on layout direction
11267            switch (getLayoutDirection()) {
11268                case LAYOUT_DIRECTION_INHERIT:
11269                    // If this is root view, no need to look at parent's layout dir.
11270                    if (canResolveLayoutDirection()) {
11271                        ViewGroup viewGroup = ((ViewGroup) mParent);
11272
11273                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11274                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11275                        }
11276                    } else {
11277                        // Nothing to do, LTR by default
11278                    }
11279                    break;
11280                case LAYOUT_DIRECTION_RTL:
11281                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11282                    break;
11283                case LAYOUT_DIRECTION_LOCALE:
11284                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11285                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11286                    }
11287                    break;
11288                default:
11289                    // Nothing to do, LTR by default
11290            }
11291        }
11292
11293        // Set to resolved
11294        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11295        onResolvedLayoutDirectionChanged();
11296        // Resolve padding
11297        resolvePadding();
11298    }
11299
11300    /**
11301     * Called when layout direction has been resolved.
11302     *
11303     * The default implementation does nothing.
11304     */
11305    public void onResolvedLayoutDirectionChanged() {
11306    }
11307
11308    /**
11309     * Resolve padding depending on layout direction.
11310     */
11311    public void resolvePadding() {
11312        // If the user specified the absolute padding (either with android:padding or
11313        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11314        // use the default padding or the padding from the background drawable
11315        // (stored at this point in mPadding*)
11316        int resolvedLayoutDirection = getResolvedLayoutDirection();
11317        switch (resolvedLayoutDirection) {
11318            case LAYOUT_DIRECTION_RTL:
11319                // Start user padding override Right user padding. Otherwise, if Right user
11320                // padding is not defined, use the default Right padding. If Right user padding
11321                // is defined, just use it.
11322                if (mUserPaddingStart >= 0) {
11323                    mUserPaddingRight = mUserPaddingStart;
11324                } else if (mUserPaddingRight < 0) {
11325                    mUserPaddingRight = mPaddingRight;
11326                }
11327                if (mUserPaddingEnd >= 0) {
11328                    mUserPaddingLeft = mUserPaddingEnd;
11329                } else if (mUserPaddingLeft < 0) {
11330                    mUserPaddingLeft = mPaddingLeft;
11331                }
11332                break;
11333            case LAYOUT_DIRECTION_LTR:
11334            default:
11335                // Start user padding override Left user padding. Otherwise, if Left user
11336                // padding is not defined, use the default left padding. If Left user padding
11337                // is defined, just use it.
11338                if (mUserPaddingStart >= 0) {
11339                    mUserPaddingLeft = mUserPaddingStart;
11340                } else if (mUserPaddingLeft < 0) {
11341                    mUserPaddingLeft = mPaddingLeft;
11342                }
11343                if (mUserPaddingEnd >= 0) {
11344                    mUserPaddingRight = mUserPaddingEnd;
11345                } else if (mUserPaddingRight < 0) {
11346                    mUserPaddingRight = mPaddingRight;
11347                }
11348        }
11349
11350        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11351
11352        if(isPaddingRelative()) {
11353            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11354        } else {
11355            recomputePadding();
11356        }
11357        onPaddingChanged(resolvedLayoutDirection);
11358    }
11359
11360    /**
11361     * Resolve padding depending on the layout direction. Subclasses that care about
11362     * padding resolution should override this method. The default implementation does
11363     * nothing.
11364     *
11365     * @param layoutDirection the direction of the layout
11366     *
11367     * @see {@link #LAYOUT_DIRECTION_LTR}
11368     * @see {@link #LAYOUT_DIRECTION_RTL}
11369     */
11370    public void onPaddingChanged(int layoutDirection) {
11371    }
11372
11373    /**
11374     * Check if layout direction resolution can be done.
11375     *
11376     * @return true if layout direction resolution can be done otherwise return false.
11377     */
11378    public boolean canResolveLayoutDirection() {
11379        switch (getLayoutDirection()) {
11380            case LAYOUT_DIRECTION_INHERIT:
11381                return (mParent != null) && (mParent instanceof ViewGroup);
11382            default:
11383                return true;
11384        }
11385    }
11386
11387    /**
11388     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11389     * when reset is done.
11390     */
11391    public void resetResolvedLayoutDirection() {
11392        // Reset the current resolved bits
11393        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11394        onResolvedLayoutDirectionReset();
11395        // Reset also the text direction
11396        resetResolvedTextDirection();
11397    }
11398
11399    /**
11400     * Called during reset of resolved layout direction.
11401     *
11402     * Subclasses need to override this method to clear cached information that depends on the
11403     * resolved layout direction, or to inform child views that inherit their layout direction.
11404     *
11405     * The default implementation does nothing.
11406     */
11407    public void onResolvedLayoutDirectionReset() {
11408    }
11409
11410    /**
11411     * Check if a Locale uses an RTL script.
11412     *
11413     * @param locale Locale to check
11414     * @return true if the Locale uses an RTL script.
11415     */
11416    protected static boolean isLayoutDirectionRtl(Locale locale) {
11417        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11418    }
11419
11420    /**
11421     * This is called when the view is detached from a window.  At this point it
11422     * no longer has a surface for drawing.
11423     *
11424     * @see #onAttachedToWindow()
11425     */
11426    protected void onDetachedFromWindow() {
11427        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11428
11429        removeUnsetPressCallback();
11430        removeLongPressCallback();
11431        removePerformClickCallback();
11432        removeSendViewScrolledAccessibilityEventCallback();
11433
11434        destroyDrawingCache();
11435
11436        destroyLayer(false);
11437
11438        if (mAttachInfo != null) {
11439            if (mDisplayList != null) {
11440                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11441            }
11442            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11443        } else {
11444            // Should never happen
11445            clearDisplayList();
11446        }
11447
11448        mCurrentAnimation = null;
11449
11450        resetResolvedLayoutDirection();
11451        resetResolvedTextAlignment();
11452        resetAccessibilityStateChanged();
11453    }
11454
11455    /**
11456     * @return The number of times this view has been attached to a window
11457     */
11458    protected int getWindowAttachCount() {
11459        return mWindowAttachCount;
11460    }
11461
11462    /**
11463     * Retrieve a unique token identifying the window this view is attached to.
11464     * @return Return the window's token for use in
11465     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11466     */
11467    public IBinder getWindowToken() {
11468        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11469    }
11470
11471    /**
11472     * Retrieve a unique token identifying the top-level "real" window of
11473     * the window that this view is attached to.  That is, this is like
11474     * {@link #getWindowToken}, except if the window this view in is a panel
11475     * window (attached to another containing window), then the token of
11476     * the containing window is returned instead.
11477     *
11478     * @return Returns the associated window token, either
11479     * {@link #getWindowToken()} or the containing window's token.
11480     */
11481    public IBinder getApplicationWindowToken() {
11482        AttachInfo ai = mAttachInfo;
11483        if (ai != null) {
11484            IBinder appWindowToken = ai.mPanelParentWindowToken;
11485            if (appWindowToken == null) {
11486                appWindowToken = ai.mWindowToken;
11487            }
11488            return appWindowToken;
11489        }
11490        return null;
11491    }
11492
11493    /**
11494     * Retrieve private session object this view hierarchy is using to
11495     * communicate with the window manager.
11496     * @return the session object to communicate with the window manager
11497     */
11498    /*package*/ IWindowSession getWindowSession() {
11499        return mAttachInfo != null ? mAttachInfo.mSession : null;
11500    }
11501
11502    /**
11503     * @param info the {@link android.view.View.AttachInfo} to associated with
11504     *        this view
11505     */
11506    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11507        //System.out.println("Attached! " + this);
11508        mAttachInfo = info;
11509        mWindowAttachCount++;
11510        // We will need to evaluate the drawable state at least once.
11511        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11512        if (mFloatingTreeObserver != null) {
11513            info.mTreeObserver.merge(mFloatingTreeObserver);
11514            mFloatingTreeObserver = null;
11515        }
11516        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11517            mAttachInfo.mScrollContainers.add(this);
11518            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11519        }
11520        performCollectViewAttributes(mAttachInfo, visibility);
11521        onAttachedToWindow();
11522
11523        ListenerInfo li = mListenerInfo;
11524        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11525                li != null ? li.mOnAttachStateChangeListeners : null;
11526        if (listeners != null && listeners.size() > 0) {
11527            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11528            // perform the dispatching. The iterator is a safe guard against listeners that
11529            // could mutate the list by calling the various add/remove methods. This prevents
11530            // the array from being modified while we iterate it.
11531            for (OnAttachStateChangeListener listener : listeners) {
11532                listener.onViewAttachedToWindow(this);
11533            }
11534        }
11535
11536        int vis = info.mWindowVisibility;
11537        if (vis != GONE) {
11538            onWindowVisibilityChanged(vis);
11539        }
11540        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11541            // If nobody has evaluated the drawable state yet, then do it now.
11542            refreshDrawableState();
11543        }
11544    }
11545
11546    void dispatchDetachedFromWindow() {
11547        AttachInfo info = mAttachInfo;
11548        if (info != null) {
11549            int vis = info.mWindowVisibility;
11550            if (vis != GONE) {
11551                onWindowVisibilityChanged(GONE);
11552            }
11553        }
11554
11555        onDetachedFromWindow();
11556
11557        ListenerInfo li = mListenerInfo;
11558        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11559                li != null ? li.mOnAttachStateChangeListeners : null;
11560        if (listeners != null && listeners.size() > 0) {
11561            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11562            // perform the dispatching. The iterator is a safe guard against listeners that
11563            // could mutate the list by calling the various add/remove methods. This prevents
11564            // the array from being modified while we iterate it.
11565            for (OnAttachStateChangeListener listener : listeners) {
11566                listener.onViewDetachedFromWindow(this);
11567            }
11568        }
11569
11570        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11571            mAttachInfo.mScrollContainers.remove(this);
11572            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11573        }
11574
11575        mAttachInfo = null;
11576    }
11577
11578    /**
11579     * Store this view hierarchy's frozen state into the given container.
11580     *
11581     * @param container The SparseArray in which to save the view's state.
11582     *
11583     * @see #restoreHierarchyState(android.util.SparseArray)
11584     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11585     * @see #onSaveInstanceState()
11586     */
11587    public void saveHierarchyState(SparseArray<Parcelable> container) {
11588        dispatchSaveInstanceState(container);
11589    }
11590
11591    /**
11592     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11593     * this view and its children. May be overridden to modify how freezing happens to a
11594     * view's children; for example, some views may want to not store state for their children.
11595     *
11596     * @param container The SparseArray in which to save the view's state.
11597     *
11598     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11599     * @see #saveHierarchyState(android.util.SparseArray)
11600     * @see #onSaveInstanceState()
11601     */
11602    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11603        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11604            mPrivateFlags &= ~SAVE_STATE_CALLED;
11605            Parcelable state = onSaveInstanceState();
11606            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11607                throw new IllegalStateException(
11608                        "Derived class did not call super.onSaveInstanceState()");
11609            }
11610            if (state != null) {
11611                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11612                // + ": " + state);
11613                container.put(mID, state);
11614            }
11615        }
11616    }
11617
11618    /**
11619     * Hook allowing a view to generate a representation of its internal state
11620     * that can later be used to create a new instance with that same state.
11621     * This state should only contain information that is not persistent or can
11622     * not be reconstructed later. For example, you will never store your
11623     * current position on screen because that will be computed again when a
11624     * new instance of the view is placed in its view hierarchy.
11625     * <p>
11626     * Some examples of things you may store here: the current cursor position
11627     * in a text view (but usually not the text itself since that is stored in a
11628     * content provider or other persistent storage), the currently selected
11629     * item in a list view.
11630     *
11631     * @return Returns a Parcelable object containing the view's current dynamic
11632     *         state, or null if there is nothing interesting to save. The
11633     *         default implementation returns null.
11634     * @see #onRestoreInstanceState(android.os.Parcelable)
11635     * @see #saveHierarchyState(android.util.SparseArray)
11636     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11637     * @see #setSaveEnabled(boolean)
11638     */
11639    protected Parcelable onSaveInstanceState() {
11640        mPrivateFlags |= SAVE_STATE_CALLED;
11641        return BaseSavedState.EMPTY_STATE;
11642    }
11643
11644    /**
11645     * Restore this view hierarchy's frozen state from the given container.
11646     *
11647     * @param container The SparseArray which holds previously frozen states.
11648     *
11649     * @see #saveHierarchyState(android.util.SparseArray)
11650     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11651     * @see #onRestoreInstanceState(android.os.Parcelable)
11652     */
11653    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11654        dispatchRestoreInstanceState(container);
11655    }
11656
11657    /**
11658     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11659     * state for this view and its children. May be overridden to modify how restoring
11660     * happens to a view's children; for example, some views may want to not store state
11661     * for their children.
11662     *
11663     * @param container The SparseArray which holds previously saved state.
11664     *
11665     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11666     * @see #restoreHierarchyState(android.util.SparseArray)
11667     * @see #onRestoreInstanceState(android.os.Parcelable)
11668     */
11669    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11670        if (mID != NO_ID) {
11671            Parcelable state = container.get(mID);
11672            if (state != null) {
11673                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11674                // + ": " + state);
11675                mPrivateFlags &= ~SAVE_STATE_CALLED;
11676                onRestoreInstanceState(state);
11677                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11678                    throw new IllegalStateException(
11679                            "Derived class did not call super.onRestoreInstanceState()");
11680                }
11681            }
11682        }
11683    }
11684
11685    /**
11686     * Hook allowing a view to re-apply a representation of its internal state that had previously
11687     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11688     * null state.
11689     *
11690     * @param state The frozen state that had previously been returned by
11691     *        {@link #onSaveInstanceState}.
11692     *
11693     * @see #onSaveInstanceState()
11694     * @see #restoreHierarchyState(android.util.SparseArray)
11695     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11696     */
11697    protected void onRestoreInstanceState(Parcelable state) {
11698        mPrivateFlags |= SAVE_STATE_CALLED;
11699        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11700            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11701                    + "received " + state.getClass().toString() + " instead. This usually happens "
11702                    + "when two views of different type have the same id in the same hierarchy. "
11703                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11704                    + "other views do not use the same id.");
11705        }
11706    }
11707
11708    /**
11709     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11710     *
11711     * @return the drawing start time in milliseconds
11712     */
11713    public long getDrawingTime() {
11714        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11715    }
11716
11717    /**
11718     * <p>Enables or disables the duplication of the parent's state into this view. When
11719     * duplication is enabled, this view gets its drawable state from its parent rather
11720     * than from its own internal properties.</p>
11721     *
11722     * <p>Note: in the current implementation, setting this property to true after the
11723     * view was added to a ViewGroup might have no effect at all. This property should
11724     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11725     *
11726     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11727     * property is enabled, an exception will be thrown.</p>
11728     *
11729     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11730     * parent, these states should not be affected by this method.</p>
11731     *
11732     * @param enabled True to enable duplication of the parent's drawable state, false
11733     *                to disable it.
11734     *
11735     * @see #getDrawableState()
11736     * @see #isDuplicateParentStateEnabled()
11737     */
11738    public void setDuplicateParentStateEnabled(boolean enabled) {
11739        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11740    }
11741
11742    /**
11743     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11744     *
11745     * @return True if this view's drawable state is duplicated from the parent,
11746     *         false otherwise
11747     *
11748     * @see #getDrawableState()
11749     * @see #setDuplicateParentStateEnabled(boolean)
11750     */
11751    public boolean isDuplicateParentStateEnabled() {
11752        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11753    }
11754
11755    /**
11756     * <p>Specifies the type of layer backing this view. The layer can be
11757     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11758     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11759     *
11760     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11761     * instance that controls how the layer is composed on screen. The following
11762     * properties of the paint are taken into account when composing the layer:</p>
11763     * <ul>
11764     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11765     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11766     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11767     * </ul>
11768     *
11769     * <p>If this view has an alpha value set to < 1.0 by calling
11770     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11771     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11772     * equivalent to setting a hardware layer on this view and providing a paint with
11773     * the desired alpha value.<p>
11774     *
11775     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11776     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11777     * for more information on when and how to use layers.</p>
11778     *
11779     * @param layerType The ype of layer to use with this view, must be one of
11780     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11781     *        {@link #LAYER_TYPE_HARDWARE}
11782     * @param paint The paint used to compose the layer. This argument is optional
11783     *        and can be null. It is ignored when the layer type is
11784     *        {@link #LAYER_TYPE_NONE}
11785     *
11786     * @see #getLayerType()
11787     * @see #LAYER_TYPE_NONE
11788     * @see #LAYER_TYPE_SOFTWARE
11789     * @see #LAYER_TYPE_HARDWARE
11790     * @see #setAlpha(float)
11791     *
11792     * @attr ref android.R.styleable#View_layerType
11793     */
11794    public void setLayerType(int layerType, Paint paint) {
11795        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11796            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11797                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11798        }
11799
11800        if (layerType == mLayerType) {
11801            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11802                mLayerPaint = paint == null ? new Paint() : paint;
11803                invalidateParentCaches();
11804                invalidate(true);
11805            }
11806            return;
11807        }
11808
11809        // Destroy any previous software drawing cache if needed
11810        switch (mLayerType) {
11811            case LAYER_TYPE_HARDWARE:
11812                destroyLayer(false);
11813                // fall through - non-accelerated views may use software layer mechanism instead
11814            case LAYER_TYPE_SOFTWARE:
11815                destroyDrawingCache();
11816                break;
11817            default:
11818                break;
11819        }
11820
11821        mLayerType = layerType;
11822        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11823        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11824        mLocalDirtyRect = layerDisabled ? null : new Rect();
11825
11826        invalidateParentCaches();
11827        invalidate(true);
11828    }
11829
11830    /**
11831     * Indicates whether this view has a static layer. A view with layer type
11832     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11833     * dynamic.
11834     */
11835    boolean hasStaticLayer() {
11836        return true;
11837    }
11838
11839    /**
11840     * Indicates what type of layer is currently associated with this view. By default
11841     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11842     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11843     * for more information on the different types of layers.
11844     *
11845     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11846     *         {@link #LAYER_TYPE_HARDWARE}
11847     *
11848     * @see #setLayerType(int, android.graphics.Paint)
11849     * @see #buildLayer()
11850     * @see #LAYER_TYPE_NONE
11851     * @see #LAYER_TYPE_SOFTWARE
11852     * @see #LAYER_TYPE_HARDWARE
11853     */
11854    public int getLayerType() {
11855        return mLayerType;
11856    }
11857
11858    /**
11859     * Forces this view's layer to be created and this view to be rendered
11860     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11861     * invoking this method will have no effect.
11862     *
11863     * This method can for instance be used to render a view into its layer before
11864     * starting an animation. If this view is complex, rendering into the layer
11865     * before starting the animation will avoid skipping frames.
11866     *
11867     * @throws IllegalStateException If this view is not attached to a window
11868     *
11869     * @see #setLayerType(int, android.graphics.Paint)
11870     */
11871    public void buildLayer() {
11872        if (mLayerType == LAYER_TYPE_NONE) return;
11873
11874        if (mAttachInfo == null) {
11875            throw new IllegalStateException("This view must be attached to a window first");
11876        }
11877
11878        switch (mLayerType) {
11879            case LAYER_TYPE_HARDWARE:
11880                if (mAttachInfo.mHardwareRenderer != null &&
11881                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11882                        mAttachInfo.mHardwareRenderer.validate()) {
11883                    getHardwareLayer();
11884                }
11885                break;
11886            case LAYER_TYPE_SOFTWARE:
11887                buildDrawingCache(true);
11888                break;
11889        }
11890    }
11891
11892    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11893    void flushLayer() {
11894        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11895            mHardwareLayer.flush();
11896        }
11897    }
11898
11899    /**
11900     * <p>Returns a hardware layer that can be used to draw this view again
11901     * without executing its draw method.</p>
11902     *
11903     * @return A HardwareLayer ready to render, or null if an error occurred.
11904     */
11905    HardwareLayer getHardwareLayer() {
11906        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11907                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11908            return null;
11909        }
11910
11911        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11912
11913        final int width = mRight - mLeft;
11914        final int height = mBottom - mTop;
11915
11916        if (width == 0 || height == 0) {
11917            return null;
11918        }
11919
11920        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11921            if (mHardwareLayer == null) {
11922                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11923                        width, height, isOpaque());
11924                mLocalDirtyRect.set(0, 0, width, height);
11925            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11926                mHardwareLayer.resize(width, height);
11927                mLocalDirtyRect.set(0, 0, width, height);
11928            }
11929
11930            // The layer is not valid if the underlying GPU resources cannot be allocated
11931            if (!mHardwareLayer.isValid()) {
11932                return null;
11933            }
11934
11935            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11936            mLocalDirtyRect.setEmpty();
11937        }
11938
11939        return mHardwareLayer;
11940    }
11941
11942    /**
11943     * Destroys this View's hardware layer if possible.
11944     *
11945     * @return True if the layer was destroyed, false otherwise.
11946     *
11947     * @see #setLayerType(int, android.graphics.Paint)
11948     * @see #LAYER_TYPE_HARDWARE
11949     */
11950    boolean destroyLayer(boolean valid) {
11951        if (mHardwareLayer != null) {
11952            AttachInfo info = mAttachInfo;
11953            if (info != null && info.mHardwareRenderer != null &&
11954                    info.mHardwareRenderer.isEnabled() &&
11955                    (valid || info.mHardwareRenderer.validate())) {
11956                mHardwareLayer.destroy();
11957                mHardwareLayer = null;
11958
11959                invalidate(true);
11960                invalidateParentCaches();
11961            }
11962            return true;
11963        }
11964        return false;
11965    }
11966
11967    /**
11968     * Destroys all hardware rendering resources. This method is invoked
11969     * when the system needs to reclaim resources. Upon execution of this
11970     * method, you should free any OpenGL resources created by the view.
11971     *
11972     * Note: you <strong>must</strong> call
11973     * <code>super.destroyHardwareResources()</code> when overriding
11974     * this method.
11975     *
11976     * @hide
11977     */
11978    protected void destroyHardwareResources() {
11979        destroyLayer(true);
11980    }
11981
11982    /**
11983     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11984     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11985     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11986     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11987     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11988     * null.</p>
11989     *
11990     * <p>Enabling the drawing cache is similar to
11991     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11992     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11993     * drawing cache has no effect on rendering because the system uses a different mechanism
11994     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11995     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11996     * for information on how to enable software and hardware layers.</p>
11997     *
11998     * <p>This API can be used to manually generate
11999     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12000     * {@link #getDrawingCache()}.</p>
12001     *
12002     * @param enabled true to enable the drawing cache, false otherwise
12003     *
12004     * @see #isDrawingCacheEnabled()
12005     * @see #getDrawingCache()
12006     * @see #buildDrawingCache()
12007     * @see #setLayerType(int, android.graphics.Paint)
12008     */
12009    public void setDrawingCacheEnabled(boolean enabled) {
12010        mCachingFailed = false;
12011        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12012    }
12013
12014    /**
12015     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12016     *
12017     * @return true if the drawing cache is enabled
12018     *
12019     * @see #setDrawingCacheEnabled(boolean)
12020     * @see #getDrawingCache()
12021     */
12022    @ViewDebug.ExportedProperty(category = "drawing")
12023    public boolean isDrawingCacheEnabled() {
12024        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12025    }
12026
12027    /**
12028     * Debugging utility which recursively outputs the dirty state of a view and its
12029     * descendants.
12030     *
12031     * @hide
12032     */
12033    @SuppressWarnings({"UnusedDeclaration"})
12034    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12035        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12036                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12037                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12038                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12039        if (clear) {
12040            mPrivateFlags &= clearMask;
12041        }
12042        if (this instanceof ViewGroup) {
12043            ViewGroup parent = (ViewGroup) this;
12044            final int count = parent.getChildCount();
12045            for (int i = 0; i < count; i++) {
12046                final View child = parent.getChildAt(i);
12047                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12048            }
12049        }
12050    }
12051
12052    /**
12053     * This method is used by ViewGroup to cause its children to restore or recreate their
12054     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12055     * to recreate its own display list, which would happen if it went through the normal
12056     * draw/dispatchDraw mechanisms.
12057     *
12058     * @hide
12059     */
12060    protected void dispatchGetDisplayList() {}
12061
12062    /**
12063     * A view that is not attached or hardware accelerated cannot create a display list.
12064     * This method checks these conditions and returns the appropriate result.
12065     *
12066     * @return true if view has the ability to create a display list, false otherwise.
12067     *
12068     * @hide
12069     */
12070    public boolean canHaveDisplayList() {
12071        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12072    }
12073
12074    /**
12075     * @return The HardwareRenderer associated with that view or null if hardware rendering
12076     * is not supported or this this has not been attached to a window.
12077     *
12078     * @hide
12079     */
12080    public HardwareRenderer getHardwareRenderer() {
12081        if (mAttachInfo != null) {
12082            return mAttachInfo.mHardwareRenderer;
12083        }
12084        return null;
12085    }
12086
12087    /**
12088     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12089     * Otherwise, the same display list will be returned (after having been rendered into
12090     * along the way, depending on the invalidation state of the view).
12091     *
12092     * @param displayList The previous version of this displayList, could be null.
12093     * @param isLayer Whether the requester of the display list is a layer. If so,
12094     * the view will avoid creating a layer inside the resulting display list.
12095     * @return A new or reused DisplayList object.
12096     */
12097    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12098        if (!canHaveDisplayList()) {
12099            return null;
12100        }
12101
12102        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12103                displayList == null || !displayList.isValid() ||
12104                (!isLayer && mRecreateDisplayList))) {
12105            // Don't need to recreate the display list, just need to tell our
12106            // children to restore/recreate theirs
12107            if (displayList != null && displayList.isValid() &&
12108                    !isLayer && !mRecreateDisplayList) {
12109                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12110                mPrivateFlags &= ~DIRTY_MASK;
12111                dispatchGetDisplayList();
12112
12113                return displayList;
12114            }
12115
12116            if (!isLayer) {
12117                // If we got here, we're recreating it. Mark it as such to ensure that
12118                // we copy in child display lists into ours in drawChild()
12119                mRecreateDisplayList = true;
12120            }
12121            if (displayList == null) {
12122                final String name = getClass().getSimpleName();
12123                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12124                // If we're creating a new display list, make sure our parent gets invalidated
12125                // since they will need to recreate their display list to account for this
12126                // new child display list.
12127                invalidateParentCaches();
12128            }
12129
12130            boolean caching = false;
12131            final HardwareCanvas canvas = displayList.start();
12132            int width = mRight - mLeft;
12133            int height = mBottom - mTop;
12134
12135            try {
12136                canvas.setViewport(width, height);
12137                // The dirty rect should always be null for a display list
12138                canvas.onPreDraw(null);
12139                int layerType = getLayerType();
12140                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12141                    if (layerType == LAYER_TYPE_HARDWARE) {
12142                        final HardwareLayer layer = getHardwareLayer();
12143                        if (layer != null && layer.isValid()) {
12144                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12145                        } else {
12146                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12147                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12148                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12149                        }
12150                        caching = true;
12151                    } else {
12152                        buildDrawingCache(true);
12153                        Bitmap cache = getDrawingCache(true);
12154                        if (cache != null) {
12155                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12156                            caching = true;
12157                        }
12158                    }
12159                } else {
12160
12161                    computeScroll();
12162
12163                    canvas.translate(-mScrollX, -mScrollY);
12164                    if (!isLayer) {
12165                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12166                        mPrivateFlags &= ~DIRTY_MASK;
12167                    }
12168
12169                    // Fast path for layouts with no backgrounds
12170                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12171                        dispatchDraw(canvas);
12172                    } else {
12173                        draw(canvas);
12174                    }
12175                }
12176            } finally {
12177                canvas.onPostDraw();
12178
12179                displayList.end();
12180                displayList.setCaching(caching);
12181                if (isLayer) {
12182                    displayList.setLeftTopRightBottom(0, 0, width, height);
12183                } else {
12184                    setDisplayListProperties(displayList);
12185                }
12186            }
12187        } else if (!isLayer) {
12188            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12189            mPrivateFlags &= ~DIRTY_MASK;
12190        }
12191
12192        return displayList;
12193    }
12194
12195    /**
12196     * Get the DisplayList for the HardwareLayer
12197     *
12198     * @param layer The HardwareLayer whose DisplayList we want
12199     * @return A DisplayList fopr the specified HardwareLayer
12200     */
12201    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12202        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12203        layer.setDisplayList(displayList);
12204        return displayList;
12205    }
12206
12207
12208    /**
12209     * <p>Returns a display list that can be used to draw this view again
12210     * without executing its draw method.</p>
12211     *
12212     * @return A DisplayList ready to replay, or null if caching is not enabled.
12213     *
12214     * @hide
12215     */
12216    public DisplayList getDisplayList() {
12217        mDisplayList = getDisplayList(mDisplayList, false);
12218        return mDisplayList;
12219    }
12220
12221    private void clearDisplayList() {
12222        if (mDisplayList != null) {
12223            mDisplayList.invalidate();
12224            mDisplayList.clear();
12225        }
12226    }
12227
12228    /**
12229     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12230     *
12231     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12232     *
12233     * @see #getDrawingCache(boolean)
12234     */
12235    public Bitmap getDrawingCache() {
12236        return getDrawingCache(false);
12237    }
12238
12239    /**
12240     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12241     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12242     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12243     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12244     * request the drawing cache by calling this method and draw it on screen if the
12245     * returned bitmap is not null.</p>
12246     *
12247     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12248     * this method will create a bitmap of the same size as this view. Because this bitmap
12249     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12250     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12251     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12252     * size than the view. This implies that your application must be able to handle this
12253     * size.</p>
12254     *
12255     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12256     *        the current density of the screen when the application is in compatibility
12257     *        mode.
12258     *
12259     * @return A bitmap representing this view or null if cache is disabled.
12260     *
12261     * @see #setDrawingCacheEnabled(boolean)
12262     * @see #isDrawingCacheEnabled()
12263     * @see #buildDrawingCache(boolean)
12264     * @see #destroyDrawingCache()
12265     */
12266    public Bitmap getDrawingCache(boolean autoScale) {
12267        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12268            return null;
12269        }
12270        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12271            buildDrawingCache(autoScale);
12272        }
12273        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12274    }
12275
12276    /**
12277     * <p>Frees the resources used by the drawing cache. If you call
12278     * {@link #buildDrawingCache()} manually without calling
12279     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12280     * should cleanup the cache with this method afterwards.</p>
12281     *
12282     * @see #setDrawingCacheEnabled(boolean)
12283     * @see #buildDrawingCache()
12284     * @see #getDrawingCache()
12285     */
12286    public void destroyDrawingCache() {
12287        if (mDrawingCache != null) {
12288            mDrawingCache.recycle();
12289            mDrawingCache = null;
12290        }
12291        if (mUnscaledDrawingCache != null) {
12292            mUnscaledDrawingCache.recycle();
12293            mUnscaledDrawingCache = null;
12294        }
12295    }
12296
12297    /**
12298     * Setting a solid background color for the drawing cache's bitmaps will improve
12299     * performance and memory usage. Note, though that this should only be used if this
12300     * view will always be drawn on top of a solid color.
12301     *
12302     * @param color The background color to use for the drawing cache's bitmap
12303     *
12304     * @see #setDrawingCacheEnabled(boolean)
12305     * @see #buildDrawingCache()
12306     * @see #getDrawingCache()
12307     */
12308    public void setDrawingCacheBackgroundColor(int color) {
12309        if (color != mDrawingCacheBackgroundColor) {
12310            mDrawingCacheBackgroundColor = color;
12311            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12312        }
12313    }
12314
12315    /**
12316     * @see #setDrawingCacheBackgroundColor(int)
12317     *
12318     * @return The background color to used for the drawing cache's bitmap
12319     */
12320    public int getDrawingCacheBackgroundColor() {
12321        return mDrawingCacheBackgroundColor;
12322    }
12323
12324    /**
12325     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12326     *
12327     * @see #buildDrawingCache(boolean)
12328     */
12329    public void buildDrawingCache() {
12330        buildDrawingCache(false);
12331    }
12332
12333    /**
12334     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12335     *
12336     * <p>If you call {@link #buildDrawingCache()} manually without calling
12337     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12338     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12339     *
12340     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12341     * this method will create a bitmap of the same size as this view. Because this bitmap
12342     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12343     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12344     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12345     * size than the view. This implies that your application must be able to handle this
12346     * size.</p>
12347     *
12348     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12349     * you do not need the drawing cache bitmap, calling this method will increase memory
12350     * usage and cause the view to be rendered in software once, thus negatively impacting
12351     * performance.</p>
12352     *
12353     * @see #getDrawingCache()
12354     * @see #destroyDrawingCache()
12355     */
12356    public void buildDrawingCache(boolean autoScale) {
12357        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12358                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12359            mCachingFailed = false;
12360
12361            int width = mRight - mLeft;
12362            int height = mBottom - mTop;
12363
12364            final AttachInfo attachInfo = mAttachInfo;
12365            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12366
12367            if (autoScale && scalingRequired) {
12368                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12369                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12370            }
12371
12372            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12373            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12374            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12375
12376            if (width <= 0 || height <= 0 ||
12377                     // Projected bitmap size in bytes
12378                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12379                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12380                destroyDrawingCache();
12381                mCachingFailed = true;
12382                return;
12383            }
12384
12385            boolean clear = true;
12386            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12387
12388            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12389                Bitmap.Config quality;
12390                if (!opaque) {
12391                    // Never pick ARGB_4444 because it looks awful
12392                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12393                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12394                        case DRAWING_CACHE_QUALITY_AUTO:
12395                            quality = Bitmap.Config.ARGB_8888;
12396                            break;
12397                        case DRAWING_CACHE_QUALITY_LOW:
12398                            quality = Bitmap.Config.ARGB_8888;
12399                            break;
12400                        case DRAWING_CACHE_QUALITY_HIGH:
12401                            quality = Bitmap.Config.ARGB_8888;
12402                            break;
12403                        default:
12404                            quality = Bitmap.Config.ARGB_8888;
12405                            break;
12406                    }
12407                } else {
12408                    // Optimization for translucent windows
12409                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12410                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12411                }
12412
12413                // Try to cleanup memory
12414                if (bitmap != null) bitmap.recycle();
12415
12416                try {
12417                    bitmap = Bitmap.createBitmap(width, height, quality);
12418                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12419                    if (autoScale) {
12420                        mDrawingCache = bitmap;
12421                    } else {
12422                        mUnscaledDrawingCache = bitmap;
12423                    }
12424                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12425                } catch (OutOfMemoryError e) {
12426                    // If there is not enough memory to create the bitmap cache, just
12427                    // ignore the issue as bitmap caches are not required to draw the
12428                    // view hierarchy
12429                    if (autoScale) {
12430                        mDrawingCache = null;
12431                    } else {
12432                        mUnscaledDrawingCache = null;
12433                    }
12434                    mCachingFailed = true;
12435                    return;
12436                }
12437
12438                clear = drawingCacheBackgroundColor != 0;
12439            }
12440
12441            Canvas canvas;
12442            if (attachInfo != null) {
12443                canvas = attachInfo.mCanvas;
12444                if (canvas == null) {
12445                    canvas = new Canvas();
12446                }
12447                canvas.setBitmap(bitmap);
12448                // Temporarily clobber the cached Canvas in case one of our children
12449                // is also using a drawing cache. Without this, the children would
12450                // steal the canvas by attaching their own bitmap to it and bad, bad
12451                // thing would happen (invisible views, corrupted drawings, etc.)
12452                attachInfo.mCanvas = null;
12453            } else {
12454                // This case should hopefully never or seldom happen
12455                canvas = new Canvas(bitmap);
12456            }
12457
12458            if (clear) {
12459                bitmap.eraseColor(drawingCacheBackgroundColor);
12460            }
12461
12462            computeScroll();
12463            final int restoreCount = canvas.save();
12464
12465            if (autoScale && scalingRequired) {
12466                final float scale = attachInfo.mApplicationScale;
12467                canvas.scale(scale, scale);
12468            }
12469
12470            canvas.translate(-mScrollX, -mScrollY);
12471
12472            mPrivateFlags |= DRAWN;
12473            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12474                    mLayerType != LAYER_TYPE_NONE) {
12475                mPrivateFlags |= DRAWING_CACHE_VALID;
12476            }
12477
12478            // Fast path for layouts with no backgrounds
12479            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12480                mPrivateFlags &= ~DIRTY_MASK;
12481                dispatchDraw(canvas);
12482            } else {
12483                draw(canvas);
12484            }
12485
12486            canvas.restoreToCount(restoreCount);
12487            canvas.setBitmap(null);
12488
12489            if (attachInfo != null) {
12490                // Restore the cached Canvas for our siblings
12491                attachInfo.mCanvas = canvas;
12492            }
12493        }
12494    }
12495
12496    /**
12497     * Create a snapshot of the view into a bitmap.  We should probably make
12498     * some form of this public, but should think about the API.
12499     */
12500    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12501        int width = mRight - mLeft;
12502        int height = mBottom - mTop;
12503
12504        final AttachInfo attachInfo = mAttachInfo;
12505        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12506        width = (int) ((width * scale) + 0.5f);
12507        height = (int) ((height * scale) + 0.5f);
12508
12509        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12510        if (bitmap == null) {
12511            throw new OutOfMemoryError();
12512        }
12513
12514        Resources resources = getResources();
12515        if (resources != null) {
12516            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12517        }
12518
12519        Canvas canvas;
12520        if (attachInfo != null) {
12521            canvas = attachInfo.mCanvas;
12522            if (canvas == null) {
12523                canvas = new Canvas();
12524            }
12525            canvas.setBitmap(bitmap);
12526            // Temporarily clobber the cached Canvas in case one of our children
12527            // is also using a drawing cache. Without this, the children would
12528            // steal the canvas by attaching their own bitmap to it and bad, bad
12529            // things would happen (invisible views, corrupted drawings, etc.)
12530            attachInfo.mCanvas = null;
12531        } else {
12532            // This case should hopefully never or seldom happen
12533            canvas = new Canvas(bitmap);
12534        }
12535
12536        if ((backgroundColor & 0xff000000) != 0) {
12537            bitmap.eraseColor(backgroundColor);
12538        }
12539
12540        computeScroll();
12541        final int restoreCount = canvas.save();
12542        canvas.scale(scale, scale);
12543        canvas.translate(-mScrollX, -mScrollY);
12544
12545        // Temporarily remove the dirty mask
12546        int flags = mPrivateFlags;
12547        mPrivateFlags &= ~DIRTY_MASK;
12548
12549        // Fast path for layouts with no backgrounds
12550        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12551            dispatchDraw(canvas);
12552        } else {
12553            draw(canvas);
12554        }
12555
12556        mPrivateFlags = flags;
12557
12558        canvas.restoreToCount(restoreCount);
12559        canvas.setBitmap(null);
12560
12561        if (attachInfo != null) {
12562            // Restore the cached Canvas for our siblings
12563            attachInfo.mCanvas = canvas;
12564        }
12565
12566        return bitmap;
12567    }
12568
12569    /**
12570     * Indicates whether this View is currently in edit mode. A View is usually
12571     * in edit mode when displayed within a developer tool. For instance, if
12572     * this View is being drawn by a visual user interface builder, this method
12573     * should return true.
12574     *
12575     * Subclasses should check the return value of this method to provide
12576     * different behaviors if their normal behavior might interfere with the
12577     * host environment. For instance: the class spawns a thread in its
12578     * constructor, the drawing code relies on device-specific features, etc.
12579     *
12580     * This method is usually checked in the drawing code of custom widgets.
12581     *
12582     * @return True if this View is in edit mode, false otherwise.
12583     */
12584    public boolean isInEditMode() {
12585        return false;
12586    }
12587
12588    /**
12589     * If the View draws content inside its padding and enables fading edges,
12590     * it needs to support padding offsets. Padding offsets are added to the
12591     * fading edges to extend the length of the fade so that it covers pixels
12592     * drawn inside the padding.
12593     *
12594     * Subclasses of this class should override this method if they need
12595     * to draw content inside the padding.
12596     *
12597     * @return True if padding offset must be applied, false otherwise.
12598     *
12599     * @see #getLeftPaddingOffset()
12600     * @see #getRightPaddingOffset()
12601     * @see #getTopPaddingOffset()
12602     * @see #getBottomPaddingOffset()
12603     *
12604     * @since CURRENT
12605     */
12606    protected boolean isPaddingOffsetRequired() {
12607        return false;
12608    }
12609
12610    /**
12611     * Amount by which to extend the left fading region. Called only when
12612     * {@link #isPaddingOffsetRequired()} returns true.
12613     *
12614     * @return The left padding offset in pixels.
12615     *
12616     * @see #isPaddingOffsetRequired()
12617     *
12618     * @since CURRENT
12619     */
12620    protected int getLeftPaddingOffset() {
12621        return 0;
12622    }
12623
12624    /**
12625     * Amount by which to extend the right fading region. Called only when
12626     * {@link #isPaddingOffsetRequired()} returns true.
12627     *
12628     * @return The right padding offset in pixels.
12629     *
12630     * @see #isPaddingOffsetRequired()
12631     *
12632     * @since CURRENT
12633     */
12634    protected int getRightPaddingOffset() {
12635        return 0;
12636    }
12637
12638    /**
12639     * Amount by which to extend the top fading region. Called only when
12640     * {@link #isPaddingOffsetRequired()} returns true.
12641     *
12642     * @return The top padding offset in pixels.
12643     *
12644     * @see #isPaddingOffsetRequired()
12645     *
12646     * @since CURRENT
12647     */
12648    protected int getTopPaddingOffset() {
12649        return 0;
12650    }
12651
12652    /**
12653     * Amount by which to extend the bottom fading region. Called only when
12654     * {@link #isPaddingOffsetRequired()} returns true.
12655     *
12656     * @return The bottom padding offset in pixels.
12657     *
12658     * @see #isPaddingOffsetRequired()
12659     *
12660     * @since CURRENT
12661     */
12662    protected int getBottomPaddingOffset() {
12663        return 0;
12664    }
12665
12666    /**
12667     * @hide
12668     * @param offsetRequired
12669     */
12670    protected int getFadeTop(boolean offsetRequired) {
12671        int top = mPaddingTop;
12672        if (offsetRequired) top += getTopPaddingOffset();
12673        return top;
12674    }
12675
12676    /**
12677     * @hide
12678     * @param offsetRequired
12679     */
12680    protected int getFadeHeight(boolean offsetRequired) {
12681        int padding = mPaddingTop;
12682        if (offsetRequired) padding += getTopPaddingOffset();
12683        return mBottom - mTop - mPaddingBottom - padding;
12684    }
12685
12686    /**
12687     * <p>Indicates whether this view is attached to a hardware accelerated
12688     * window or not.</p>
12689     *
12690     * <p>Even if this method returns true, it does not mean that every call
12691     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12692     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12693     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12694     * window is hardware accelerated,
12695     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12696     * return false, and this method will return true.</p>
12697     *
12698     * @return True if the view is attached to a window and the window is
12699     *         hardware accelerated; false in any other case.
12700     */
12701    public boolean isHardwareAccelerated() {
12702        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12703    }
12704
12705    /**
12706     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12707     * case of an active Animation being run on the view.
12708     */
12709    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12710            Animation a, boolean scalingRequired) {
12711        Transformation invalidationTransform;
12712        final int flags = parent.mGroupFlags;
12713        final boolean initialized = a.isInitialized();
12714        if (!initialized) {
12715            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12716            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12717            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12718            onAnimationStart();
12719        }
12720
12721        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12722        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12723            if (parent.mInvalidationTransformation == null) {
12724                parent.mInvalidationTransformation = new Transformation();
12725            }
12726            invalidationTransform = parent.mInvalidationTransformation;
12727            a.getTransformation(drawingTime, invalidationTransform, 1f);
12728        } else {
12729            invalidationTransform = parent.mChildTransformation;
12730        }
12731
12732        if (more) {
12733            if (!a.willChangeBounds()) {
12734                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12735                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12736                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12737                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12738                    // The child need to draw an animation, potentially offscreen, so
12739                    // make sure we do not cancel invalidate requests
12740                    parent.mPrivateFlags |= DRAW_ANIMATION;
12741                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12742                }
12743            } else {
12744                if (parent.mInvalidateRegion == null) {
12745                    parent.mInvalidateRegion = new RectF();
12746                }
12747                final RectF region = parent.mInvalidateRegion;
12748                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12749                        invalidationTransform);
12750
12751                // The child need to draw an animation, potentially offscreen, so
12752                // make sure we do not cancel invalidate requests
12753                parent.mPrivateFlags |= DRAW_ANIMATION;
12754
12755                final int left = mLeft + (int) region.left;
12756                final int top = mTop + (int) region.top;
12757                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12758                        top + (int) (region.height() + .5f));
12759            }
12760        }
12761        return more;
12762    }
12763
12764    /**
12765     * This method is called by getDisplayList() when a display list is created or re-rendered.
12766     * It sets or resets the current value of all properties on that display list (resetting is
12767     * necessary when a display list is being re-created, because we need to make sure that
12768     * previously-set transform values
12769     */
12770    void setDisplayListProperties(DisplayList displayList) {
12771        if (displayList != null) {
12772            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12773            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12774            if (mParent instanceof ViewGroup) {
12775                displayList.setClipChildren(
12776                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12777            }
12778            float alpha = 1;
12779            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12780                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12781                ViewGroup parentVG = (ViewGroup) mParent;
12782                final boolean hasTransform =
12783                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12784                if (hasTransform) {
12785                    Transformation transform = parentVG.mChildTransformation;
12786                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12787                    if (transformType != Transformation.TYPE_IDENTITY) {
12788                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12789                            alpha = transform.getAlpha();
12790                        }
12791                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12792                            displayList.setStaticMatrix(transform.getMatrix());
12793                        }
12794                    }
12795                }
12796            }
12797            if (mTransformationInfo != null) {
12798                alpha *= mTransformationInfo.mAlpha;
12799                if (alpha < 1) {
12800                    final int multipliedAlpha = (int) (255 * alpha);
12801                    if (onSetAlpha(multipliedAlpha)) {
12802                        alpha = 1;
12803                    }
12804                }
12805                displayList.setTransformationInfo(alpha,
12806                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12807                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12808                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12809                        mTransformationInfo.mScaleY);
12810                if (mTransformationInfo.mCamera == null) {
12811                    mTransformationInfo.mCamera = new Camera();
12812                    mTransformationInfo.matrix3D = new Matrix();
12813                }
12814                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12815                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12816                    displayList.setPivotX(getPivotX());
12817                    displayList.setPivotY(getPivotY());
12818                }
12819            } else if (alpha < 1) {
12820                displayList.setAlpha(alpha);
12821            }
12822        }
12823    }
12824
12825    /**
12826     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12827     * This draw() method is an implementation detail and is not intended to be overridden or
12828     * to be called from anywhere else other than ViewGroup.drawChild().
12829     */
12830    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12831        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12832        boolean more = false;
12833        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12834        final int flags = parent.mGroupFlags;
12835
12836        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12837            parent.mChildTransformation.clear();
12838            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12839        }
12840
12841        Transformation transformToApply = null;
12842        boolean concatMatrix = false;
12843
12844        boolean scalingRequired = false;
12845        boolean caching;
12846        int layerType = getLayerType();
12847
12848        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12849        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12850                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12851            caching = true;
12852            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12853            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12854        } else {
12855            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12856        }
12857
12858        final Animation a = getAnimation();
12859        if (a != null) {
12860            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12861            concatMatrix = a.willChangeTransformationMatrix();
12862            if (concatMatrix) {
12863                mPrivateFlags3 |= VIEW_IS_ANIMATING_TRANSFORM;
12864            }
12865            transformToApply = parent.mChildTransformation;
12866        } else {
12867            if ((mPrivateFlags3 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12868                    mDisplayList != null) {
12869                // No longer animating: clear out old animation matrix
12870                mDisplayList.setAnimationMatrix(null);
12871                mPrivateFlags3 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12872            }
12873            if (!useDisplayListProperties &&
12874                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12875                final boolean hasTransform =
12876                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12877                if (hasTransform) {
12878                    final int transformType = parent.mChildTransformation.getTransformationType();
12879                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12880                            parent.mChildTransformation : null;
12881                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12882                }
12883            }
12884        }
12885
12886        concatMatrix |= !childHasIdentityMatrix;
12887
12888        // Sets the flag as early as possible to allow draw() implementations
12889        // to call invalidate() successfully when doing animations
12890        mPrivateFlags |= DRAWN;
12891
12892        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12893                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12894            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12895            return more;
12896        }
12897        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12898
12899        if (hardwareAccelerated) {
12900            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12901            // retain the flag's value temporarily in the mRecreateDisplayList flag
12902            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12903            mPrivateFlags &= ~INVALIDATED;
12904        }
12905
12906        computeScroll();
12907
12908        final int sx = mScrollX;
12909        final int sy = mScrollY;
12910
12911        DisplayList displayList = null;
12912        Bitmap cache = null;
12913        boolean hasDisplayList = false;
12914        if (caching) {
12915            if (!hardwareAccelerated) {
12916                if (layerType != LAYER_TYPE_NONE) {
12917                    layerType = LAYER_TYPE_SOFTWARE;
12918                    buildDrawingCache(true);
12919                }
12920                cache = getDrawingCache(true);
12921            } else {
12922                switch (layerType) {
12923                    case LAYER_TYPE_SOFTWARE:
12924                        if (useDisplayListProperties) {
12925                            hasDisplayList = canHaveDisplayList();
12926                        } else {
12927                            buildDrawingCache(true);
12928                            cache = getDrawingCache(true);
12929                        }
12930                        break;
12931                    case LAYER_TYPE_HARDWARE:
12932                        if (useDisplayListProperties) {
12933                            hasDisplayList = canHaveDisplayList();
12934                        }
12935                        break;
12936                    case LAYER_TYPE_NONE:
12937                        // Delay getting the display list until animation-driven alpha values are
12938                        // set up and possibly passed on to the view
12939                        hasDisplayList = canHaveDisplayList();
12940                        break;
12941                }
12942            }
12943        }
12944        useDisplayListProperties &= hasDisplayList;
12945        if (useDisplayListProperties) {
12946            displayList = getDisplayList();
12947            if (!displayList.isValid()) {
12948                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12949                // to getDisplayList(), the display list will be marked invalid and we should not
12950                // try to use it again.
12951                displayList = null;
12952                hasDisplayList = false;
12953                useDisplayListProperties = false;
12954            }
12955        }
12956
12957        final boolean hasNoCache = cache == null || hasDisplayList;
12958        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12959                layerType != LAYER_TYPE_HARDWARE;
12960
12961        int restoreTo = -1;
12962        if (!useDisplayListProperties || transformToApply != null) {
12963            restoreTo = canvas.save();
12964        }
12965        if (offsetForScroll) {
12966            canvas.translate(mLeft - sx, mTop - sy);
12967        } else {
12968            if (!useDisplayListProperties) {
12969                canvas.translate(mLeft, mTop);
12970            }
12971            if (scalingRequired) {
12972                if (useDisplayListProperties) {
12973                    // TODO: Might not need this if we put everything inside the DL
12974                    restoreTo = canvas.save();
12975                }
12976                // mAttachInfo cannot be null, otherwise scalingRequired == false
12977                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12978                canvas.scale(scale, scale);
12979            }
12980        }
12981
12982        float alpha = useDisplayListProperties ? 1 : getAlpha();
12983        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
12984                (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
12985            if (transformToApply != null || !childHasIdentityMatrix) {
12986                int transX = 0;
12987                int transY = 0;
12988
12989                if (offsetForScroll) {
12990                    transX = -sx;
12991                    transY = -sy;
12992                }
12993
12994                if (transformToApply != null) {
12995                    if (concatMatrix) {
12996                        if (useDisplayListProperties) {
12997                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12998                        } else {
12999                            // Undo the scroll translation, apply the transformation matrix,
13000                            // then redo the scroll translate to get the correct result.
13001                            canvas.translate(-transX, -transY);
13002                            canvas.concat(transformToApply.getMatrix());
13003                            canvas.translate(transX, transY);
13004                        }
13005                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13006                    }
13007
13008                    float transformAlpha = transformToApply.getAlpha();
13009                    if (transformAlpha < 1) {
13010                        alpha *= transformAlpha;
13011                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13012                    }
13013                }
13014
13015                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13016                    canvas.translate(-transX, -transY);
13017                    canvas.concat(getMatrix());
13018                    canvas.translate(transX, transY);
13019                }
13020            }
13021
13022            // Deal with alpha if it is or used to be <1
13023            if (alpha < 1 ||
13024                    (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
13025                if (alpha < 1) {
13026                    mPrivateFlags3 |= VIEW_IS_ANIMATING_ALPHA;
13027                } else {
13028                    mPrivateFlags3 &= ~VIEW_IS_ANIMATING_ALPHA;
13029                }
13030                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13031                if (hasNoCache) {
13032                    final int multipliedAlpha = (int) (255 * alpha);
13033                    if (!onSetAlpha(multipliedAlpha)) {
13034                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13035                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13036                                layerType != LAYER_TYPE_NONE) {
13037                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13038                        }
13039                        if (useDisplayListProperties) {
13040                            displayList.setAlpha(alpha * getAlpha());
13041                        } else  if (layerType == LAYER_TYPE_NONE) {
13042                            final int scrollX = hasDisplayList ? 0 : sx;
13043                            final int scrollY = hasDisplayList ? 0 : sy;
13044                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13045                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13046                        }
13047                    } else {
13048                        // Alpha is handled by the child directly, clobber the layer's alpha
13049                        mPrivateFlags |= ALPHA_SET;
13050                    }
13051                }
13052            }
13053        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13054            onSetAlpha(255);
13055            mPrivateFlags &= ~ALPHA_SET;
13056        }
13057
13058        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13059                !useDisplayListProperties) {
13060            if (offsetForScroll) {
13061                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13062            } else {
13063                if (!scalingRequired || cache == null) {
13064                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13065                } else {
13066                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13067                }
13068            }
13069        }
13070
13071        if (!useDisplayListProperties && hasDisplayList) {
13072            displayList = getDisplayList();
13073            if (!displayList.isValid()) {
13074                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13075                // to getDisplayList(), the display list will be marked invalid and we should not
13076                // try to use it again.
13077                displayList = null;
13078                hasDisplayList = false;
13079            }
13080        }
13081
13082        if (hasNoCache) {
13083            boolean layerRendered = false;
13084            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13085                final HardwareLayer layer = getHardwareLayer();
13086                if (layer != null && layer.isValid()) {
13087                    mLayerPaint.setAlpha((int) (alpha * 255));
13088                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13089                    layerRendered = true;
13090                } else {
13091                    final int scrollX = hasDisplayList ? 0 : sx;
13092                    final int scrollY = hasDisplayList ? 0 : sy;
13093                    canvas.saveLayer(scrollX, scrollY,
13094                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13095                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13096                }
13097            }
13098
13099            if (!layerRendered) {
13100                if (!hasDisplayList) {
13101                    // Fast path for layouts with no backgrounds
13102                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13103                        mPrivateFlags &= ~DIRTY_MASK;
13104                        dispatchDraw(canvas);
13105                    } else {
13106                        draw(canvas);
13107                    }
13108                } else {
13109                    mPrivateFlags &= ~DIRTY_MASK;
13110                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13111                }
13112            }
13113        } else if (cache != null) {
13114            mPrivateFlags &= ~DIRTY_MASK;
13115            Paint cachePaint;
13116
13117            if (layerType == LAYER_TYPE_NONE) {
13118                cachePaint = parent.mCachePaint;
13119                if (cachePaint == null) {
13120                    cachePaint = new Paint();
13121                    cachePaint.setDither(false);
13122                    parent.mCachePaint = cachePaint;
13123                }
13124                if (alpha < 1) {
13125                    cachePaint.setAlpha((int) (alpha * 255));
13126                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13127                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13128                    cachePaint.setAlpha(255);
13129                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13130                }
13131            } else {
13132                cachePaint = mLayerPaint;
13133                cachePaint.setAlpha((int) (alpha * 255));
13134            }
13135            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13136        }
13137
13138        if (restoreTo >= 0) {
13139            canvas.restoreToCount(restoreTo);
13140        }
13141
13142        if (a != null && !more) {
13143            if (!hardwareAccelerated && !a.getFillAfter()) {
13144                onSetAlpha(255);
13145            }
13146            parent.finishAnimatingView(this, a);
13147        }
13148
13149        if (more && hardwareAccelerated) {
13150            // invalidation is the trigger to recreate display lists, so if we're using
13151            // display lists to render, force an invalidate to allow the animation to
13152            // continue drawing another frame
13153            parent.invalidate(true);
13154            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13155                // alpha animations should cause the child to recreate its display list
13156                invalidate(true);
13157            }
13158        }
13159
13160        mRecreateDisplayList = false;
13161
13162        return more;
13163    }
13164
13165    /**
13166     * Manually render this view (and all of its children) to the given Canvas.
13167     * The view must have already done a full layout before this function is
13168     * called.  When implementing a view, implement
13169     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13170     * If you do need to override this method, call the superclass version.
13171     *
13172     * @param canvas The Canvas to which the View is rendered.
13173     */
13174    public void draw(Canvas canvas) {
13175        final int privateFlags = mPrivateFlags;
13176        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13177                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13178        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13179
13180        /*
13181         * Draw traversal performs several drawing steps which must be executed
13182         * in the appropriate order:
13183         *
13184         *      1. Draw the background
13185         *      2. If necessary, save the canvas' layers to prepare for fading
13186         *      3. Draw view's content
13187         *      4. Draw children
13188         *      5. If necessary, draw the fading edges and restore layers
13189         *      6. Draw decorations (scrollbars for instance)
13190         */
13191
13192        // Step 1, draw the background, if needed
13193        int saveCount;
13194
13195        if (!dirtyOpaque) {
13196            final Drawable background = mBackground;
13197            if (background != null) {
13198                final int scrollX = mScrollX;
13199                final int scrollY = mScrollY;
13200
13201                if (mBackgroundSizeChanged) {
13202                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13203                    mBackgroundSizeChanged = false;
13204                }
13205
13206                if ((scrollX | scrollY) == 0) {
13207                    background.draw(canvas);
13208                } else {
13209                    canvas.translate(scrollX, scrollY);
13210                    background.draw(canvas);
13211                    canvas.translate(-scrollX, -scrollY);
13212                }
13213            }
13214        }
13215
13216        // skip step 2 & 5 if possible (common case)
13217        final int viewFlags = mViewFlags;
13218        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13219        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13220        if (!verticalEdges && !horizontalEdges) {
13221            // Step 3, draw the content
13222            if (!dirtyOpaque) onDraw(canvas);
13223
13224            // Step 4, draw the children
13225            dispatchDraw(canvas);
13226
13227            // Step 6, draw decorations (scrollbars)
13228            onDrawScrollBars(canvas);
13229
13230            // we're done...
13231            return;
13232        }
13233
13234        /*
13235         * Here we do the full fledged routine...
13236         * (this is an uncommon case where speed matters less,
13237         * this is why we repeat some of the tests that have been
13238         * done above)
13239         */
13240
13241        boolean drawTop = false;
13242        boolean drawBottom = false;
13243        boolean drawLeft = false;
13244        boolean drawRight = false;
13245
13246        float topFadeStrength = 0.0f;
13247        float bottomFadeStrength = 0.0f;
13248        float leftFadeStrength = 0.0f;
13249        float rightFadeStrength = 0.0f;
13250
13251        // Step 2, save the canvas' layers
13252        int paddingLeft = mPaddingLeft;
13253
13254        final boolean offsetRequired = isPaddingOffsetRequired();
13255        if (offsetRequired) {
13256            paddingLeft += getLeftPaddingOffset();
13257        }
13258
13259        int left = mScrollX + paddingLeft;
13260        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13261        int top = mScrollY + getFadeTop(offsetRequired);
13262        int bottom = top + getFadeHeight(offsetRequired);
13263
13264        if (offsetRequired) {
13265            right += getRightPaddingOffset();
13266            bottom += getBottomPaddingOffset();
13267        }
13268
13269        final ScrollabilityCache scrollabilityCache = mScrollCache;
13270        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13271        int length = (int) fadeHeight;
13272
13273        // clip the fade length if top and bottom fades overlap
13274        // overlapping fades produce odd-looking artifacts
13275        if (verticalEdges && (top + length > bottom - length)) {
13276            length = (bottom - top) / 2;
13277        }
13278
13279        // also clip horizontal fades if necessary
13280        if (horizontalEdges && (left + length > right - length)) {
13281            length = (right - left) / 2;
13282        }
13283
13284        if (verticalEdges) {
13285            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13286            drawTop = topFadeStrength * fadeHeight > 1.0f;
13287            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13288            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13289        }
13290
13291        if (horizontalEdges) {
13292            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13293            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13294            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13295            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13296        }
13297
13298        saveCount = canvas.getSaveCount();
13299
13300        int solidColor = getSolidColor();
13301        if (solidColor == 0) {
13302            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13303
13304            if (drawTop) {
13305                canvas.saveLayer(left, top, right, top + length, null, flags);
13306            }
13307
13308            if (drawBottom) {
13309                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13310            }
13311
13312            if (drawLeft) {
13313                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13314            }
13315
13316            if (drawRight) {
13317                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13318            }
13319        } else {
13320            scrollabilityCache.setFadeColor(solidColor);
13321        }
13322
13323        // Step 3, draw the content
13324        if (!dirtyOpaque) onDraw(canvas);
13325
13326        // Step 4, draw the children
13327        dispatchDraw(canvas);
13328
13329        // Step 5, draw the fade effect and restore layers
13330        final Paint p = scrollabilityCache.paint;
13331        final Matrix matrix = scrollabilityCache.matrix;
13332        final Shader fade = scrollabilityCache.shader;
13333
13334        if (drawTop) {
13335            matrix.setScale(1, fadeHeight * topFadeStrength);
13336            matrix.postTranslate(left, top);
13337            fade.setLocalMatrix(matrix);
13338            canvas.drawRect(left, top, right, top + length, p);
13339        }
13340
13341        if (drawBottom) {
13342            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13343            matrix.postRotate(180);
13344            matrix.postTranslate(left, bottom);
13345            fade.setLocalMatrix(matrix);
13346            canvas.drawRect(left, bottom - length, right, bottom, p);
13347        }
13348
13349        if (drawLeft) {
13350            matrix.setScale(1, fadeHeight * leftFadeStrength);
13351            matrix.postRotate(-90);
13352            matrix.postTranslate(left, top);
13353            fade.setLocalMatrix(matrix);
13354            canvas.drawRect(left, top, left + length, bottom, p);
13355        }
13356
13357        if (drawRight) {
13358            matrix.setScale(1, fadeHeight * rightFadeStrength);
13359            matrix.postRotate(90);
13360            matrix.postTranslate(right, top);
13361            fade.setLocalMatrix(matrix);
13362            canvas.drawRect(right - length, top, right, bottom, p);
13363        }
13364
13365        canvas.restoreToCount(saveCount);
13366
13367        // Step 6, draw decorations (scrollbars)
13368        onDrawScrollBars(canvas);
13369    }
13370
13371    /**
13372     * Override this if your view is known to always be drawn on top of a solid color background,
13373     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13374     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13375     * should be set to 0xFF.
13376     *
13377     * @see #setVerticalFadingEdgeEnabled(boolean)
13378     * @see #setHorizontalFadingEdgeEnabled(boolean)
13379     *
13380     * @return The known solid color background for this view, or 0 if the color may vary
13381     */
13382    @ViewDebug.ExportedProperty(category = "drawing")
13383    public int getSolidColor() {
13384        return 0;
13385    }
13386
13387    /**
13388     * Build a human readable string representation of the specified view flags.
13389     *
13390     * @param flags the view flags to convert to a string
13391     * @return a String representing the supplied flags
13392     */
13393    private static String printFlags(int flags) {
13394        String output = "";
13395        int numFlags = 0;
13396        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13397            output += "TAKES_FOCUS";
13398            numFlags++;
13399        }
13400
13401        switch (flags & VISIBILITY_MASK) {
13402        case INVISIBLE:
13403            if (numFlags > 0) {
13404                output += " ";
13405            }
13406            output += "INVISIBLE";
13407            // USELESS HERE numFlags++;
13408            break;
13409        case GONE:
13410            if (numFlags > 0) {
13411                output += " ";
13412            }
13413            output += "GONE";
13414            // USELESS HERE numFlags++;
13415            break;
13416        default:
13417            break;
13418        }
13419        return output;
13420    }
13421
13422    /**
13423     * Build a human readable string representation of the specified private
13424     * view flags.
13425     *
13426     * @param privateFlags the private view flags to convert to a string
13427     * @return a String representing the supplied flags
13428     */
13429    private static String printPrivateFlags(int privateFlags) {
13430        String output = "";
13431        int numFlags = 0;
13432
13433        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13434            output += "WANTS_FOCUS";
13435            numFlags++;
13436        }
13437
13438        if ((privateFlags & FOCUSED) == FOCUSED) {
13439            if (numFlags > 0) {
13440                output += " ";
13441            }
13442            output += "FOCUSED";
13443            numFlags++;
13444        }
13445
13446        if ((privateFlags & SELECTED) == SELECTED) {
13447            if (numFlags > 0) {
13448                output += " ";
13449            }
13450            output += "SELECTED";
13451            numFlags++;
13452        }
13453
13454        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13455            if (numFlags > 0) {
13456                output += " ";
13457            }
13458            output += "IS_ROOT_NAMESPACE";
13459            numFlags++;
13460        }
13461
13462        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13463            if (numFlags > 0) {
13464                output += " ";
13465            }
13466            output += "HAS_BOUNDS";
13467            numFlags++;
13468        }
13469
13470        if ((privateFlags & DRAWN) == DRAWN) {
13471            if (numFlags > 0) {
13472                output += " ";
13473            }
13474            output += "DRAWN";
13475            // USELESS HERE numFlags++;
13476        }
13477        return output;
13478    }
13479
13480    /**
13481     * <p>Indicates whether or not this view's layout will be requested during
13482     * the next hierarchy layout pass.</p>
13483     *
13484     * @return true if the layout will be forced during next layout pass
13485     */
13486    public boolean isLayoutRequested() {
13487        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13488    }
13489
13490    /**
13491     * Assign a size and position to a view and all of its
13492     * descendants
13493     *
13494     * <p>This is the second phase of the layout mechanism.
13495     * (The first is measuring). In this phase, each parent calls
13496     * layout on all of its children to position them.
13497     * This is typically done using the child measurements
13498     * that were stored in the measure pass().</p>
13499     *
13500     * <p>Derived classes should not override this method.
13501     * Derived classes with children should override
13502     * onLayout. In that method, they should
13503     * call layout on each of their children.</p>
13504     *
13505     * @param l Left position, relative to parent
13506     * @param t Top position, relative to parent
13507     * @param r Right position, relative to parent
13508     * @param b Bottom position, relative to parent
13509     */
13510    @SuppressWarnings({"unchecked"})
13511    public void layout(int l, int t, int r, int b) {
13512        int oldL = mLeft;
13513        int oldT = mTop;
13514        int oldB = mBottom;
13515        int oldR = mRight;
13516        boolean changed = setFrame(l, t, r, b);
13517        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13518            onLayout(changed, l, t, r, b);
13519            mPrivateFlags &= ~LAYOUT_REQUIRED;
13520
13521            ListenerInfo li = mListenerInfo;
13522            if (li != null && li.mOnLayoutChangeListeners != null) {
13523                ArrayList<OnLayoutChangeListener> listenersCopy =
13524                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13525                int numListeners = listenersCopy.size();
13526                for (int i = 0; i < numListeners; ++i) {
13527                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13528                }
13529            }
13530        }
13531        mPrivateFlags &= ~FORCE_LAYOUT;
13532    }
13533
13534    /**
13535     * Called from layout when this view should
13536     * assign a size and position to each of its children.
13537     *
13538     * Derived classes with children should override
13539     * this method and call layout on each of
13540     * their children.
13541     * @param changed This is a new size or position for this view
13542     * @param left Left position, relative to parent
13543     * @param top Top position, relative to parent
13544     * @param right Right position, relative to parent
13545     * @param bottom Bottom position, relative to parent
13546     */
13547    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13548    }
13549
13550    /**
13551     * Assign a size and position to this view.
13552     *
13553     * This is called from layout.
13554     *
13555     * @param left Left position, relative to parent
13556     * @param top Top position, relative to parent
13557     * @param right Right position, relative to parent
13558     * @param bottom Bottom position, relative to parent
13559     * @return true if the new size and position are different than the
13560     *         previous ones
13561     * {@hide}
13562     */
13563    protected boolean setFrame(int left, int top, int right, int bottom) {
13564        boolean changed = false;
13565
13566        if (DBG) {
13567            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13568                    + right + "," + bottom + ")");
13569        }
13570
13571        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13572            changed = true;
13573
13574            // Remember our drawn bit
13575            int drawn = mPrivateFlags & DRAWN;
13576
13577            int oldWidth = mRight - mLeft;
13578            int oldHeight = mBottom - mTop;
13579            int newWidth = right - left;
13580            int newHeight = bottom - top;
13581            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13582
13583            // Invalidate our old position
13584            invalidate(sizeChanged);
13585
13586            mLeft = left;
13587            mTop = top;
13588            mRight = right;
13589            mBottom = bottom;
13590            if (mDisplayList != null) {
13591                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13592            }
13593
13594            mPrivateFlags |= HAS_BOUNDS;
13595
13596
13597            if (sizeChanged) {
13598                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13599                    // A change in dimension means an auto-centered pivot point changes, too
13600                    if (mTransformationInfo != null) {
13601                        mTransformationInfo.mMatrixDirty = true;
13602                    }
13603                }
13604                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13605            }
13606
13607            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13608                // If we are visible, force the DRAWN bit to on so that
13609                // this invalidate will go through (at least to our parent).
13610                // This is because someone may have invalidated this view
13611                // before this call to setFrame came in, thereby clearing
13612                // the DRAWN bit.
13613                mPrivateFlags |= DRAWN;
13614                invalidate(sizeChanged);
13615                // parent display list may need to be recreated based on a change in the bounds
13616                // of any child
13617                invalidateParentCaches();
13618            }
13619
13620            // Reset drawn bit to original value (invalidate turns it off)
13621            mPrivateFlags |= drawn;
13622
13623            mBackgroundSizeChanged = true;
13624        }
13625        return changed;
13626    }
13627
13628    /**
13629     * Finalize inflating a view from XML.  This is called as the last phase
13630     * of inflation, after all child views have been added.
13631     *
13632     * <p>Even if the subclass overrides onFinishInflate, they should always be
13633     * sure to call the super method, so that we get called.
13634     */
13635    protected void onFinishInflate() {
13636    }
13637
13638    /**
13639     * Returns the resources associated with this view.
13640     *
13641     * @return Resources object.
13642     */
13643    public Resources getResources() {
13644        return mResources;
13645    }
13646
13647    /**
13648     * Invalidates the specified Drawable.
13649     *
13650     * @param drawable the drawable to invalidate
13651     */
13652    public void invalidateDrawable(Drawable drawable) {
13653        if (verifyDrawable(drawable)) {
13654            final Rect dirty = drawable.getBounds();
13655            final int scrollX = mScrollX;
13656            final int scrollY = mScrollY;
13657
13658            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13659                    dirty.right + scrollX, dirty.bottom + scrollY);
13660        }
13661    }
13662
13663    /**
13664     * Schedules an action on a drawable to occur at a specified time.
13665     *
13666     * @param who the recipient of the action
13667     * @param what the action to run on the drawable
13668     * @param when the time at which the action must occur. Uses the
13669     *        {@link SystemClock#uptimeMillis} timebase.
13670     */
13671    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13672        if (verifyDrawable(who) && what != null) {
13673            final long delay = when - SystemClock.uptimeMillis();
13674            if (mAttachInfo != null) {
13675                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13676                        Choreographer.CALLBACK_ANIMATION, what, who,
13677                        Choreographer.subtractFrameDelay(delay));
13678            } else {
13679                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13680            }
13681        }
13682    }
13683
13684    /**
13685     * Cancels a scheduled action on a drawable.
13686     *
13687     * @param who the recipient of the action
13688     * @param what the action to cancel
13689     */
13690    public void unscheduleDrawable(Drawable who, Runnable what) {
13691        if (verifyDrawable(who) && what != null) {
13692            if (mAttachInfo != null) {
13693                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13694                        Choreographer.CALLBACK_ANIMATION, what, who);
13695            } else {
13696                ViewRootImpl.getRunQueue().removeCallbacks(what);
13697            }
13698        }
13699    }
13700
13701    /**
13702     * Unschedule any events associated with the given Drawable.  This can be
13703     * used when selecting a new Drawable into a view, so that the previous
13704     * one is completely unscheduled.
13705     *
13706     * @param who The Drawable to unschedule.
13707     *
13708     * @see #drawableStateChanged
13709     */
13710    public void unscheduleDrawable(Drawable who) {
13711        if (mAttachInfo != null && who != null) {
13712            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13713                    Choreographer.CALLBACK_ANIMATION, null, who);
13714        }
13715    }
13716
13717    /**
13718     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
13719     * that the View directionality can and will be resolved before its Drawables.
13720     *
13721     * Will call {@link View#onResolveDrawables} when resolution is done.
13722     */
13723    public void resolveDrawables() {
13724        if (mBackground != null) {
13725            mBackground.setLayoutDirection(getResolvedLayoutDirection());
13726        }
13727        onResolveDrawables(getResolvedLayoutDirection());
13728    }
13729
13730    /**
13731     * Called when layout direction has been resolved.
13732     *
13733     * The default implementation does nothing.
13734     *
13735     * @param layoutDirection The resolved layout direction.
13736     *
13737     * @see {@link #LAYOUT_DIRECTION_LTR}
13738     * @see {@link #LAYOUT_DIRECTION_RTL}
13739     */
13740    public void onResolveDrawables(int layoutDirection) {
13741    }
13742
13743    /**
13744     * If your view subclass is displaying its own Drawable objects, it should
13745     * override this function and return true for any Drawable it is
13746     * displaying.  This allows animations for those drawables to be
13747     * scheduled.
13748     *
13749     * <p>Be sure to call through to the super class when overriding this
13750     * function.
13751     *
13752     * @param who The Drawable to verify.  Return true if it is one you are
13753     *            displaying, else return the result of calling through to the
13754     *            super class.
13755     *
13756     * @return boolean If true than the Drawable is being displayed in the
13757     *         view; else false and it is not allowed to animate.
13758     *
13759     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13760     * @see #drawableStateChanged()
13761     */
13762    protected boolean verifyDrawable(Drawable who) {
13763        return who == mBackground;
13764    }
13765
13766    /**
13767     * This function is called whenever the state of the view changes in such
13768     * a way that it impacts the state of drawables being shown.
13769     *
13770     * <p>Be sure to call through to the superclass when overriding this
13771     * function.
13772     *
13773     * @see Drawable#setState(int[])
13774     */
13775    protected void drawableStateChanged() {
13776        Drawable d = mBackground;
13777        if (d != null && d.isStateful()) {
13778            d.setState(getDrawableState());
13779        }
13780    }
13781
13782    /**
13783     * Call this to force a view to update its drawable state. This will cause
13784     * drawableStateChanged to be called on this view. Views that are interested
13785     * in the new state should call getDrawableState.
13786     *
13787     * @see #drawableStateChanged
13788     * @see #getDrawableState
13789     */
13790    public void refreshDrawableState() {
13791        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13792        drawableStateChanged();
13793
13794        ViewParent parent = mParent;
13795        if (parent != null) {
13796            parent.childDrawableStateChanged(this);
13797        }
13798    }
13799
13800    /**
13801     * Return an array of resource IDs of the drawable states representing the
13802     * current state of the view.
13803     *
13804     * @return The current drawable state
13805     *
13806     * @see Drawable#setState(int[])
13807     * @see #drawableStateChanged()
13808     * @see #onCreateDrawableState(int)
13809     */
13810    public final int[] getDrawableState() {
13811        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13812            return mDrawableState;
13813        } else {
13814            mDrawableState = onCreateDrawableState(0);
13815            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13816            return mDrawableState;
13817        }
13818    }
13819
13820    /**
13821     * Generate the new {@link android.graphics.drawable.Drawable} state for
13822     * this view. This is called by the view
13823     * system when the cached Drawable state is determined to be invalid.  To
13824     * retrieve the current state, you should use {@link #getDrawableState}.
13825     *
13826     * @param extraSpace if non-zero, this is the number of extra entries you
13827     * would like in the returned array in which you can place your own
13828     * states.
13829     *
13830     * @return Returns an array holding the current {@link Drawable} state of
13831     * the view.
13832     *
13833     * @see #mergeDrawableStates(int[], int[])
13834     */
13835    protected int[] onCreateDrawableState(int extraSpace) {
13836        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13837                mParent instanceof View) {
13838            return ((View) mParent).onCreateDrawableState(extraSpace);
13839        }
13840
13841        int[] drawableState;
13842
13843        int privateFlags = mPrivateFlags;
13844
13845        int viewStateIndex = 0;
13846        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13847        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13848        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13849        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13850        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13851        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13852        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13853                HardwareRenderer.isAvailable()) {
13854            // This is set if HW acceleration is requested, even if the current
13855            // process doesn't allow it.  This is just to allow app preview
13856            // windows to better match their app.
13857            viewStateIndex |= VIEW_STATE_ACCELERATED;
13858        }
13859        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13860
13861        final int privateFlags2 = mPrivateFlags2;
13862        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13863        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13864
13865        drawableState = VIEW_STATE_SETS[viewStateIndex];
13866
13867        //noinspection ConstantIfStatement
13868        if (false) {
13869            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13870            Log.i("View", toString()
13871                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13872                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13873                    + " fo=" + hasFocus()
13874                    + " sl=" + ((privateFlags & SELECTED) != 0)
13875                    + " wf=" + hasWindowFocus()
13876                    + ": " + Arrays.toString(drawableState));
13877        }
13878
13879        if (extraSpace == 0) {
13880            return drawableState;
13881        }
13882
13883        final int[] fullState;
13884        if (drawableState != null) {
13885            fullState = new int[drawableState.length + extraSpace];
13886            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13887        } else {
13888            fullState = new int[extraSpace];
13889        }
13890
13891        return fullState;
13892    }
13893
13894    /**
13895     * Merge your own state values in <var>additionalState</var> into the base
13896     * state values <var>baseState</var> that were returned by
13897     * {@link #onCreateDrawableState(int)}.
13898     *
13899     * @param baseState The base state values returned by
13900     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13901     * own additional state values.
13902     *
13903     * @param additionalState The additional state values you would like
13904     * added to <var>baseState</var>; this array is not modified.
13905     *
13906     * @return As a convenience, the <var>baseState</var> array you originally
13907     * passed into the function is returned.
13908     *
13909     * @see #onCreateDrawableState(int)
13910     */
13911    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13912        final int N = baseState.length;
13913        int i = N - 1;
13914        while (i >= 0 && baseState[i] == 0) {
13915            i--;
13916        }
13917        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13918        return baseState;
13919    }
13920
13921    /**
13922     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13923     * on all Drawable objects associated with this view.
13924     */
13925    public void jumpDrawablesToCurrentState() {
13926        if (mBackground != null) {
13927            mBackground.jumpToCurrentState();
13928        }
13929    }
13930
13931    /**
13932     * Sets the background color for this view.
13933     * @param color the color of the background
13934     */
13935    @RemotableViewMethod
13936    public void setBackgroundColor(int color) {
13937        if (mBackground instanceof ColorDrawable) {
13938            ((ColorDrawable) mBackground).setColor(color);
13939        } else {
13940            setBackground(new ColorDrawable(color));
13941        }
13942    }
13943
13944    /**
13945     * Set the background to a given resource. The resource should refer to
13946     * a Drawable object or 0 to remove the background.
13947     * @param resid The identifier of the resource.
13948     *
13949     * @attr ref android.R.styleable#View_background
13950     */
13951    @RemotableViewMethod
13952    public void setBackgroundResource(int resid) {
13953        if (resid != 0 && resid == mBackgroundResource) {
13954            return;
13955        }
13956
13957        Drawable d= null;
13958        if (resid != 0) {
13959            d = mResources.getDrawable(resid);
13960        }
13961        setBackground(d);
13962
13963        mBackgroundResource = resid;
13964    }
13965
13966    /**
13967     * Set the background to a given Drawable, or remove the background. If the
13968     * background has padding, this View's padding is set to the background's
13969     * padding. However, when a background is removed, this View's padding isn't
13970     * touched. If setting the padding is desired, please use
13971     * {@link #setPadding(int, int, int, int)}.
13972     *
13973     * @param background The Drawable to use as the background, or null to remove the
13974     *        background
13975     */
13976    public void setBackground(Drawable background) {
13977        //noinspection deprecation
13978        setBackgroundDrawable(background);
13979    }
13980
13981    /**
13982     * @deprecated use {@link #setBackground(Drawable)} instead
13983     */
13984    @Deprecated
13985    public void setBackgroundDrawable(Drawable background) {
13986        if (background == mBackground) {
13987            return;
13988        }
13989
13990        boolean requestLayout = false;
13991
13992        mBackgroundResource = 0;
13993
13994        /*
13995         * Regardless of whether we're setting a new background or not, we want
13996         * to clear the previous drawable.
13997         */
13998        if (mBackground != null) {
13999            mBackground.setCallback(null);
14000            unscheduleDrawable(mBackground);
14001        }
14002
14003        if (background != null) {
14004            Rect padding = sThreadLocal.get();
14005            if (padding == null) {
14006                padding = new Rect();
14007                sThreadLocal.set(padding);
14008            }
14009            background.setLayoutDirection(getResolvedLayoutDirection());
14010            if (background.getPadding(padding)) {
14011                switch (background.getLayoutDirection()) {
14012                    case LAYOUT_DIRECTION_RTL:
14013                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14014                        break;
14015                    case LAYOUT_DIRECTION_LTR:
14016                    default:
14017                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14018                }
14019            }
14020
14021            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14022            // if it has a different minimum size, we should layout again
14023            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14024                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14025                requestLayout = true;
14026            }
14027
14028            background.setCallback(this);
14029            if (background.isStateful()) {
14030                background.setState(getDrawableState());
14031            }
14032            background.setVisible(getVisibility() == VISIBLE, false);
14033            mBackground = background;
14034
14035            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14036                mPrivateFlags &= ~SKIP_DRAW;
14037                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14038                requestLayout = true;
14039            }
14040        } else {
14041            /* Remove the background */
14042            mBackground = null;
14043
14044            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14045                /*
14046                 * This view ONLY drew the background before and we're removing
14047                 * the background, so now it won't draw anything
14048                 * (hence we SKIP_DRAW)
14049                 */
14050                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14051                mPrivateFlags |= SKIP_DRAW;
14052            }
14053
14054            /*
14055             * When the background is set, we try to apply its padding to this
14056             * View. When the background is removed, we don't touch this View's
14057             * padding. This is noted in the Javadocs. Hence, we don't need to
14058             * requestLayout(), the invalidate() below is sufficient.
14059             */
14060
14061            // The old background's minimum size could have affected this
14062            // View's layout, so let's requestLayout
14063            requestLayout = true;
14064        }
14065
14066        computeOpaqueFlags();
14067
14068        if (requestLayout) {
14069            requestLayout();
14070        }
14071
14072        mBackgroundSizeChanged = true;
14073        invalidate(true);
14074    }
14075
14076    /**
14077     * Gets the background drawable
14078     *
14079     * @return The drawable used as the background for this view, if any.
14080     *
14081     * @see #setBackground(Drawable)
14082     *
14083     * @attr ref android.R.styleable#View_background
14084     */
14085    public Drawable getBackground() {
14086        return mBackground;
14087    }
14088
14089    /**
14090     * Sets the padding. The view may add on the space required to display
14091     * the scrollbars, depending on the style and visibility of the scrollbars.
14092     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14093     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14094     * from the values set in this call.
14095     *
14096     * @attr ref android.R.styleable#View_padding
14097     * @attr ref android.R.styleable#View_paddingBottom
14098     * @attr ref android.R.styleable#View_paddingLeft
14099     * @attr ref android.R.styleable#View_paddingRight
14100     * @attr ref android.R.styleable#View_paddingTop
14101     * @param left the left padding in pixels
14102     * @param top the top padding in pixels
14103     * @param right the right padding in pixels
14104     * @param bottom the bottom padding in pixels
14105     */
14106    public void setPadding(int left, int top, int right, int bottom) {
14107        mUserPaddingStart = -1;
14108        mUserPaddingEnd = -1;
14109        mUserPaddingRelative = false;
14110
14111        internalSetPadding(left, top, right, bottom);
14112    }
14113
14114    private void internalSetPadding(int left, int top, int right, int bottom) {
14115        mUserPaddingLeft = left;
14116        mUserPaddingRight = right;
14117        mUserPaddingBottom = bottom;
14118
14119        final int viewFlags = mViewFlags;
14120        boolean changed = false;
14121
14122        // Common case is there are no scroll bars.
14123        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14124            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14125                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14126                        ? 0 : getVerticalScrollbarWidth();
14127                switch (mVerticalScrollbarPosition) {
14128                    case SCROLLBAR_POSITION_DEFAULT:
14129                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14130                            left += offset;
14131                        } else {
14132                            right += offset;
14133                        }
14134                        break;
14135                    case SCROLLBAR_POSITION_RIGHT:
14136                        right += offset;
14137                        break;
14138                    case SCROLLBAR_POSITION_LEFT:
14139                        left += offset;
14140                        break;
14141                }
14142            }
14143            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14144                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14145                        ? 0 : getHorizontalScrollbarHeight();
14146            }
14147        }
14148
14149        if (mPaddingLeft != left) {
14150            changed = true;
14151            mPaddingLeft = left;
14152        }
14153        if (mPaddingTop != top) {
14154            changed = true;
14155            mPaddingTop = top;
14156        }
14157        if (mPaddingRight != right) {
14158            changed = true;
14159            mPaddingRight = right;
14160        }
14161        if (mPaddingBottom != bottom) {
14162            changed = true;
14163            mPaddingBottom = bottom;
14164        }
14165
14166        if (changed) {
14167            requestLayout();
14168        }
14169    }
14170
14171    /**
14172     * Sets the relative padding. The view may add on the space required to display
14173     * the scrollbars, depending on the style and visibility of the scrollbars.
14174     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14175     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14176     * from the values set in this call.
14177     *
14178     * @attr ref android.R.styleable#View_padding
14179     * @attr ref android.R.styleable#View_paddingBottom
14180     * @attr ref android.R.styleable#View_paddingStart
14181     * @attr ref android.R.styleable#View_paddingEnd
14182     * @attr ref android.R.styleable#View_paddingTop
14183     * @param start the start padding in pixels
14184     * @param top the top padding in pixels
14185     * @param end the end padding in pixels
14186     * @param bottom the bottom padding in pixels
14187     */
14188    public void setPaddingRelative(int start, int top, int end, int bottom) {
14189        mUserPaddingStart = start;
14190        mUserPaddingEnd = end;
14191        mUserPaddingRelative = true;
14192
14193        switch(getResolvedLayoutDirection()) {
14194            case LAYOUT_DIRECTION_RTL:
14195                internalSetPadding(end, top, start, bottom);
14196                break;
14197            case LAYOUT_DIRECTION_LTR:
14198            default:
14199                internalSetPadding(start, top, end, bottom);
14200        }
14201    }
14202
14203    /**
14204     * Returns the top padding of this view.
14205     *
14206     * @return the top padding in pixels
14207     */
14208    public int getPaddingTop() {
14209        return mPaddingTop;
14210    }
14211
14212    /**
14213     * Returns the bottom padding of this view. If there are inset and enabled
14214     * scrollbars, this value may include the space required to display the
14215     * scrollbars as well.
14216     *
14217     * @return the bottom padding in pixels
14218     */
14219    public int getPaddingBottom() {
14220        return mPaddingBottom;
14221    }
14222
14223    /**
14224     * Returns the left padding of this view. If there are inset and enabled
14225     * scrollbars, this value may include the space required to display the
14226     * scrollbars as well.
14227     *
14228     * @return the left padding in pixels
14229     */
14230    public int getPaddingLeft() {
14231        return mPaddingLeft;
14232    }
14233
14234    /**
14235     * Returns the start padding of this view depending on its resolved layout direction.
14236     * If there are inset and enabled scrollbars, this value may include the space
14237     * required to display the scrollbars as well.
14238     *
14239     * @return the start padding in pixels
14240     */
14241    public int getPaddingStart() {
14242        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14243                mPaddingRight : mPaddingLeft;
14244    }
14245
14246    /**
14247     * Returns the right padding of this view. If there are inset and enabled
14248     * scrollbars, this value may include the space required to display the
14249     * scrollbars as well.
14250     *
14251     * @return the right padding in pixels
14252     */
14253    public int getPaddingRight() {
14254        return mPaddingRight;
14255    }
14256
14257    /**
14258     * Returns the end padding of this view depending on its resolved layout direction.
14259     * If there are inset and enabled scrollbars, this value may include the space
14260     * required to display the scrollbars as well.
14261     *
14262     * @return the end padding in pixels
14263     */
14264    public int getPaddingEnd() {
14265        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14266                mPaddingLeft : mPaddingRight;
14267    }
14268
14269    /**
14270     * Return if the padding as been set thru relative values
14271     * {@link #setPaddingRelative(int, int, int, int)} or thru
14272     * @attr ref android.R.styleable#View_paddingStart or
14273     * @attr ref android.R.styleable#View_paddingEnd
14274     *
14275     * @return true if the padding is relative or false if it is not.
14276     */
14277    public boolean isPaddingRelative() {
14278        return mUserPaddingRelative;
14279    }
14280
14281    /**
14282     * @hide
14283     */
14284    public Insets getOpticalInsets() {
14285        if (mLayoutInsets == null) {
14286            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14287        }
14288        return mLayoutInsets;
14289    }
14290
14291    /**
14292     * @hide
14293     */
14294    public void setLayoutInsets(Insets layoutInsets) {
14295        mLayoutInsets = layoutInsets;
14296    }
14297
14298    /**
14299     * Changes the selection state of this view. A view can be selected or not.
14300     * Note that selection is not the same as focus. Views are typically
14301     * selected in the context of an AdapterView like ListView or GridView;
14302     * the selected view is the view that is highlighted.
14303     *
14304     * @param selected true if the view must be selected, false otherwise
14305     */
14306    public void setSelected(boolean selected) {
14307        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14308            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14309            if (!selected) resetPressedState();
14310            invalidate(true);
14311            refreshDrawableState();
14312            dispatchSetSelected(selected);
14313            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14314                notifyAccessibilityStateChanged();
14315            }
14316        }
14317    }
14318
14319    /**
14320     * Dispatch setSelected to all of this View's children.
14321     *
14322     * @see #setSelected(boolean)
14323     *
14324     * @param selected The new selected state
14325     */
14326    protected void dispatchSetSelected(boolean selected) {
14327    }
14328
14329    /**
14330     * Indicates the selection state of this view.
14331     *
14332     * @return true if the view is selected, false otherwise
14333     */
14334    @ViewDebug.ExportedProperty
14335    public boolean isSelected() {
14336        return (mPrivateFlags & SELECTED) != 0;
14337    }
14338
14339    /**
14340     * Changes the activated state of this view. A view can be activated or not.
14341     * Note that activation is not the same as selection.  Selection is
14342     * a transient property, representing the view (hierarchy) the user is
14343     * currently interacting with.  Activation is a longer-term state that the
14344     * user can move views in and out of.  For example, in a list view with
14345     * single or multiple selection enabled, the views in the current selection
14346     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14347     * here.)  The activated state is propagated down to children of the view it
14348     * is set on.
14349     *
14350     * @param activated true if the view must be activated, false otherwise
14351     */
14352    public void setActivated(boolean activated) {
14353        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14354            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14355            invalidate(true);
14356            refreshDrawableState();
14357            dispatchSetActivated(activated);
14358        }
14359    }
14360
14361    /**
14362     * Dispatch setActivated to all of this View's children.
14363     *
14364     * @see #setActivated(boolean)
14365     *
14366     * @param activated The new activated state
14367     */
14368    protected void dispatchSetActivated(boolean activated) {
14369    }
14370
14371    /**
14372     * Indicates the activation state of this view.
14373     *
14374     * @return true if the view is activated, false otherwise
14375     */
14376    @ViewDebug.ExportedProperty
14377    public boolean isActivated() {
14378        return (mPrivateFlags & ACTIVATED) != 0;
14379    }
14380
14381    /**
14382     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14383     * observer can be used to get notifications when global events, like
14384     * layout, happen.
14385     *
14386     * The returned ViewTreeObserver observer is not guaranteed to remain
14387     * valid for the lifetime of this View. If the caller of this method keeps
14388     * a long-lived reference to ViewTreeObserver, it should always check for
14389     * the return value of {@link ViewTreeObserver#isAlive()}.
14390     *
14391     * @return The ViewTreeObserver for this view's hierarchy.
14392     */
14393    public ViewTreeObserver getViewTreeObserver() {
14394        if (mAttachInfo != null) {
14395            return mAttachInfo.mTreeObserver;
14396        }
14397        if (mFloatingTreeObserver == null) {
14398            mFloatingTreeObserver = new ViewTreeObserver();
14399        }
14400        return mFloatingTreeObserver;
14401    }
14402
14403    /**
14404     * <p>Finds the topmost view in the current view hierarchy.</p>
14405     *
14406     * @return the topmost view containing this view
14407     */
14408    public View getRootView() {
14409        if (mAttachInfo != null) {
14410            final View v = mAttachInfo.mRootView;
14411            if (v != null) {
14412                return v;
14413            }
14414        }
14415
14416        View parent = this;
14417
14418        while (parent.mParent != null && parent.mParent instanceof View) {
14419            parent = (View) parent.mParent;
14420        }
14421
14422        return parent;
14423    }
14424
14425    /**
14426     * <p>Computes the coordinates of this view on the screen. The argument
14427     * must be an array of two integers. After the method returns, the array
14428     * contains the x and y location in that order.</p>
14429     *
14430     * @param location an array of two integers in which to hold the coordinates
14431     */
14432    public void getLocationOnScreen(int[] location) {
14433        getLocationInWindow(location);
14434
14435        final AttachInfo info = mAttachInfo;
14436        if (info != null) {
14437            location[0] += info.mWindowLeft;
14438            location[1] += info.mWindowTop;
14439        }
14440    }
14441
14442    /**
14443     * <p>Computes the coordinates of this view in its window. The argument
14444     * must be an array of two integers. After the method returns, the array
14445     * contains the x and y location in that order.</p>
14446     *
14447     * @param location an array of two integers in which to hold the coordinates
14448     */
14449    public void getLocationInWindow(int[] location) {
14450        if (location == null || location.length < 2) {
14451            throw new IllegalArgumentException("location must be an array of two integers");
14452        }
14453
14454        if (mAttachInfo == null) {
14455            // When the view is not attached to a window, this method does not make sense
14456            location[0] = location[1] = 0;
14457            return;
14458        }
14459
14460        float[] position = mAttachInfo.mTmpTransformLocation;
14461        position[0] = position[1] = 0.0f;
14462
14463        if (!hasIdentityMatrix()) {
14464            getMatrix().mapPoints(position);
14465        }
14466
14467        position[0] += mLeft;
14468        position[1] += mTop;
14469
14470        ViewParent viewParent = mParent;
14471        while (viewParent instanceof View) {
14472            final View view = (View) viewParent;
14473
14474            position[0] -= view.mScrollX;
14475            position[1] -= view.mScrollY;
14476
14477            if (!view.hasIdentityMatrix()) {
14478                view.getMatrix().mapPoints(position);
14479            }
14480
14481            position[0] += view.mLeft;
14482            position[1] += view.mTop;
14483
14484            viewParent = view.mParent;
14485         }
14486
14487        if (viewParent instanceof ViewRootImpl) {
14488            // *cough*
14489            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14490            position[1] -= vr.mCurScrollY;
14491        }
14492
14493        location[0] = (int) (position[0] + 0.5f);
14494        location[1] = (int) (position[1] + 0.5f);
14495    }
14496
14497    /**
14498     * {@hide}
14499     * @param id the id of the view to be found
14500     * @return the view of the specified id, null if cannot be found
14501     */
14502    protected View findViewTraversal(int id) {
14503        if (id == mID) {
14504            return this;
14505        }
14506        return null;
14507    }
14508
14509    /**
14510     * {@hide}
14511     * @param tag the tag of the view to be found
14512     * @return the view of specified tag, null if cannot be found
14513     */
14514    protected View findViewWithTagTraversal(Object tag) {
14515        if (tag != null && tag.equals(mTag)) {
14516            return this;
14517        }
14518        return null;
14519    }
14520
14521    /**
14522     * {@hide}
14523     * @param predicate The predicate to evaluate.
14524     * @param childToSkip If not null, ignores this child during the recursive traversal.
14525     * @return The first view that matches the predicate or null.
14526     */
14527    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14528        if (predicate.apply(this)) {
14529            return this;
14530        }
14531        return null;
14532    }
14533
14534    /**
14535     * Look for a child view with the given id.  If this view has the given
14536     * id, return this view.
14537     *
14538     * @param id The id to search for.
14539     * @return The view that has the given id in the hierarchy or null
14540     */
14541    public final View findViewById(int id) {
14542        if (id < 0) {
14543            return null;
14544        }
14545        return findViewTraversal(id);
14546    }
14547
14548    /**
14549     * Finds a view by its unuque and stable accessibility id.
14550     *
14551     * @param accessibilityId The searched accessibility id.
14552     * @return The found view.
14553     */
14554    final View findViewByAccessibilityId(int accessibilityId) {
14555        if (accessibilityId < 0) {
14556            return null;
14557        }
14558        return findViewByAccessibilityIdTraversal(accessibilityId);
14559    }
14560
14561    /**
14562     * Performs the traversal to find a view by its unuque and stable accessibility id.
14563     *
14564     * <strong>Note:</strong>This method does not stop at the root namespace
14565     * boundary since the user can touch the screen at an arbitrary location
14566     * potentially crossing the root namespace bounday which will send an
14567     * accessibility event to accessibility services and they should be able
14568     * to obtain the event source. Also accessibility ids are guaranteed to be
14569     * unique in the window.
14570     *
14571     * @param accessibilityId The accessibility id.
14572     * @return The found view.
14573     */
14574    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14575        if (getAccessibilityViewId() == accessibilityId) {
14576            return this;
14577        }
14578        return null;
14579    }
14580
14581    /**
14582     * Look for a child view with the given tag.  If this view has the given
14583     * tag, return this view.
14584     *
14585     * @param tag The tag to search for, using "tag.equals(getTag())".
14586     * @return The View that has the given tag in the hierarchy or null
14587     */
14588    public final View findViewWithTag(Object tag) {
14589        if (tag == null) {
14590            return null;
14591        }
14592        return findViewWithTagTraversal(tag);
14593    }
14594
14595    /**
14596     * {@hide}
14597     * Look for a child view that matches the specified predicate.
14598     * If this view matches the predicate, return this view.
14599     *
14600     * @param predicate The predicate to evaluate.
14601     * @return The first view that matches the predicate or null.
14602     */
14603    public final View findViewByPredicate(Predicate<View> predicate) {
14604        return findViewByPredicateTraversal(predicate, null);
14605    }
14606
14607    /**
14608     * {@hide}
14609     * Look for a child view that matches the specified predicate,
14610     * starting with the specified view and its descendents and then
14611     * recusively searching the ancestors and siblings of that view
14612     * until this view is reached.
14613     *
14614     * This method is useful in cases where the predicate does not match
14615     * a single unique view (perhaps multiple views use the same id)
14616     * and we are trying to find the view that is "closest" in scope to the
14617     * starting view.
14618     *
14619     * @param start The view to start from.
14620     * @param predicate The predicate to evaluate.
14621     * @return The first view that matches the predicate or null.
14622     */
14623    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14624        View childToSkip = null;
14625        for (;;) {
14626            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14627            if (view != null || start == this) {
14628                return view;
14629            }
14630
14631            ViewParent parent = start.getParent();
14632            if (parent == null || !(parent instanceof View)) {
14633                return null;
14634            }
14635
14636            childToSkip = start;
14637            start = (View) parent;
14638        }
14639    }
14640
14641    /**
14642     * Sets the identifier for this view. The identifier does not have to be
14643     * unique in this view's hierarchy. The identifier should be a positive
14644     * number.
14645     *
14646     * @see #NO_ID
14647     * @see #getId()
14648     * @see #findViewById(int)
14649     *
14650     * @param id a number used to identify the view
14651     *
14652     * @attr ref android.R.styleable#View_id
14653     */
14654    public void setId(int id) {
14655        mID = id;
14656    }
14657
14658    /**
14659     * {@hide}
14660     *
14661     * @param isRoot true if the view belongs to the root namespace, false
14662     *        otherwise
14663     */
14664    public void setIsRootNamespace(boolean isRoot) {
14665        if (isRoot) {
14666            mPrivateFlags |= IS_ROOT_NAMESPACE;
14667        } else {
14668            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14669        }
14670    }
14671
14672    /**
14673     * {@hide}
14674     *
14675     * @return true if the view belongs to the root namespace, false otherwise
14676     */
14677    public boolean isRootNamespace() {
14678        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14679    }
14680
14681    /**
14682     * Returns this view's identifier.
14683     *
14684     * @return a positive integer used to identify the view or {@link #NO_ID}
14685     *         if the view has no ID
14686     *
14687     * @see #setId(int)
14688     * @see #findViewById(int)
14689     * @attr ref android.R.styleable#View_id
14690     */
14691    @ViewDebug.CapturedViewProperty
14692    public int getId() {
14693        return mID;
14694    }
14695
14696    /**
14697     * Returns this view's tag.
14698     *
14699     * @return the Object stored in this view as a tag
14700     *
14701     * @see #setTag(Object)
14702     * @see #getTag(int)
14703     */
14704    @ViewDebug.ExportedProperty
14705    public Object getTag() {
14706        return mTag;
14707    }
14708
14709    /**
14710     * Sets the tag associated with this view. A tag can be used to mark
14711     * a view in its hierarchy and does not have to be unique within the
14712     * hierarchy. Tags can also be used to store data within a view without
14713     * resorting to another data structure.
14714     *
14715     * @param tag an Object to tag the view with
14716     *
14717     * @see #getTag()
14718     * @see #setTag(int, Object)
14719     */
14720    public void setTag(final Object tag) {
14721        mTag = tag;
14722    }
14723
14724    /**
14725     * Returns the tag associated with this view and the specified key.
14726     *
14727     * @param key The key identifying the tag
14728     *
14729     * @return the Object stored in this view as a tag
14730     *
14731     * @see #setTag(int, Object)
14732     * @see #getTag()
14733     */
14734    public Object getTag(int key) {
14735        if (mKeyedTags != null) return mKeyedTags.get(key);
14736        return null;
14737    }
14738
14739    /**
14740     * Sets a tag associated with this view and a key. A tag can be used
14741     * to mark a view in its hierarchy and does not have to be unique within
14742     * the hierarchy. Tags can also be used to store data within a view
14743     * without resorting to another data structure.
14744     *
14745     * The specified key should be an id declared in the resources of the
14746     * application to ensure it is unique (see the <a
14747     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14748     * Keys identified as belonging to
14749     * the Android framework or not associated with any package will cause
14750     * an {@link IllegalArgumentException} to be thrown.
14751     *
14752     * @param key The key identifying the tag
14753     * @param tag An Object to tag the view with
14754     *
14755     * @throws IllegalArgumentException If they specified key is not valid
14756     *
14757     * @see #setTag(Object)
14758     * @see #getTag(int)
14759     */
14760    public void setTag(int key, final Object tag) {
14761        // If the package id is 0x00 or 0x01, it's either an undefined package
14762        // or a framework id
14763        if ((key >>> 24) < 2) {
14764            throw new IllegalArgumentException("The key must be an application-specific "
14765                    + "resource id.");
14766        }
14767
14768        setKeyedTag(key, tag);
14769    }
14770
14771    /**
14772     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14773     * framework id.
14774     *
14775     * @hide
14776     */
14777    public void setTagInternal(int key, Object tag) {
14778        if ((key >>> 24) != 0x1) {
14779            throw new IllegalArgumentException("The key must be a framework-specific "
14780                    + "resource id.");
14781        }
14782
14783        setKeyedTag(key, tag);
14784    }
14785
14786    private void setKeyedTag(int key, Object tag) {
14787        if (mKeyedTags == null) {
14788            mKeyedTags = new SparseArray<Object>();
14789        }
14790
14791        mKeyedTags.put(key, tag);
14792    }
14793
14794    /**
14795     * Prints information about this view in the log output, with the tag
14796     * {@link #VIEW_LOG_TAG}.
14797     *
14798     * @hide
14799     */
14800    public void debug() {
14801        debug(0);
14802    }
14803
14804    /**
14805     * Prints information about this view in the log output, with the tag
14806     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14807     * indentation defined by the <code>depth</code>.
14808     *
14809     * @param depth the indentation level
14810     *
14811     * @hide
14812     */
14813    protected void debug(int depth) {
14814        String output = debugIndent(depth - 1);
14815
14816        output += "+ " + this;
14817        int id = getId();
14818        if (id != -1) {
14819            output += " (id=" + id + ")";
14820        }
14821        Object tag = getTag();
14822        if (tag != null) {
14823            output += " (tag=" + tag + ")";
14824        }
14825        Log.d(VIEW_LOG_TAG, output);
14826
14827        if ((mPrivateFlags & FOCUSED) != 0) {
14828            output = debugIndent(depth) + " FOCUSED";
14829            Log.d(VIEW_LOG_TAG, output);
14830        }
14831
14832        output = debugIndent(depth);
14833        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14834                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14835                + "} ";
14836        Log.d(VIEW_LOG_TAG, output);
14837
14838        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14839                || mPaddingBottom != 0) {
14840            output = debugIndent(depth);
14841            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14842                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14843            Log.d(VIEW_LOG_TAG, output);
14844        }
14845
14846        output = debugIndent(depth);
14847        output += "mMeasureWidth=" + mMeasuredWidth +
14848                " mMeasureHeight=" + mMeasuredHeight;
14849        Log.d(VIEW_LOG_TAG, output);
14850
14851        output = debugIndent(depth);
14852        if (mLayoutParams == null) {
14853            output += "BAD! no layout params";
14854        } else {
14855            output = mLayoutParams.debug(output);
14856        }
14857        Log.d(VIEW_LOG_TAG, output);
14858
14859        output = debugIndent(depth);
14860        output += "flags={";
14861        output += View.printFlags(mViewFlags);
14862        output += "}";
14863        Log.d(VIEW_LOG_TAG, output);
14864
14865        output = debugIndent(depth);
14866        output += "privateFlags={";
14867        output += View.printPrivateFlags(mPrivateFlags);
14868        output += "}";
14869        Log.d(VIEW_LOG_TAG, output);
14870    }
14871
14872    /**
14873     * Creates a string of whitespaces used for indentation.
14874     *
14875     * @param depth the indentation level
14876     * @return a String containing (depth * 2 + 3) * 2 white spaces
14877     *
14878     * @hide
14879     */
14880    protected static String debugIndent(int depth) {
14881        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14882        for (int i = 0; i < (depth * 2) + 3; i++) {
14883            spaces.append(' ').append(' ');
14884        }
14885        return spaces.toString();
14886    }
14887
14888    /**
14889     * <p>Return the offset of the widget's text baseline from the widget's top
14890     * boundary. If this widget does not support baseline alignment, this
14891     * method returns -1. </p>
14892     *
14893     * @return the offset of the baseline within the widget's bounds or -1
14894     *         if baseline alignment is not supported
14895     */
14896    @ViewDebug.ExportedProperty(category = "layout")
14897    public int getBaseline() {
14898        return -1;
14899    }
14900
14901    /**
14902     * Call this when something has changed which has invalidated the
14903     * layout of this view. This will schedule a layout pass of the view
14904     * tree.
14905     */
14906    public void requestLayout() {
14907        mPrivateFlags |= FORCE_LAYOUT;
14908        mPrivateFlags |= INVALIDATED;
14909
14910        if (mLayoutParams != null) {
14911            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14912        }
14913
14914        if (mParent != null && !mParent.isLayoutRequested()) {
14915            mParent.requestLayout();
14916        }
14917    }
14918
14919    /**
14920     * Forces this view to be laid out during the next layout pass.
14921     * This method does not call requestLayout() or forceLayout()
14922     * on the parent.
14923     */
14924    public void forceLayout() {
14925        mPrivateFlags |= FORCE_LAYOUT;
14926        mPrivateFlags |= INVALIDATED;
14927    }
14928
14929    /**
14930     * <p>
14931     * This is called to find out how big a view should be. The parent
14932     * supplies constraint information in the width and height parameters.
14933     * </p>
14934     *
14935     * <p>
14936     * The actual measurement work of a view is performed in
14937     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14938     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14939     * </p>
14940     *
14941     *
14942     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14943     *        parent
14944     * @param heightMeasureSpec Vertical space requirements as imposed by the
14945     *        parent
14946     *
14947     * @see #onMeasure(int, int)
14948     */
14949    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14950        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14951                widthMeasureSpec != mOldWidthMeasureSpec ||
14952                heightMeasureSpec != mOldHeightMeasureSpec) {
14953
14954            // first clears the measured dimension flag
14955            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14956
14957            // measure ourselves, this should set the measured dimension flag back
14958            onMeasure(widthMeasureSpec, heightMeasureSpec);
14959
14960            // flag not set, setMeasuredDimension() was not invoked, we raise
14961            // an exception to warn the developer
14962            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14963                throw new IllegalStateException("onMeasure() did not set the"
14964                        + " measured dimension by calling"
14965                        + " setMeasuredDimension()");
14966            }
14967
14968            mPrivateFlags |= LAYOUT_REQUIRED;
14969        }
14970
14971        mOldWidthMeasureSpec = widthMeasureSpec;
14972        mOldHeightMeasureSpec = heightMeasureSpec;
14973    }
14974
14975    /**
14976     * <p>
14977     * Measure the view and its content to determine the measured width and the
14978     * measured height. This method is invoked by {@link #measure(int, int)} and
14979     * should be overriden by subclasses to provide accurate and efficient
14980     * measurement of their contents.
14981     * </p>
14982     *
14983     * <p>
14984     * <strong>CONTRACT:</strong> When overriding this method, you
14985     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14986     * measured width and height of this view. Failure to do so will trigger an
14987     * <code>IllegalStateException</code>, thrown by
14988     * {@link #measure(int, int)}. Calling the superclass'
14989     * {@link #onMeasure(int, int)} is a valid use.
14990     * </p>
14991     *
14992     * <p>
14993     * The base class implementation of measure defaults to the background size,
14994     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14995     * override {@link #onMeasure(int, int)} to provide better measurements of
14996     * their content.
14997     * </p>
14998     *
14999     * <p>
15000     * If this method is overridden, it is the subclass's responsibility to make
15001     * sure the measured height and width are at least the view's minimum height
15002     * and width ({@link #getSuggestedMinimumHeight()} and
15003     * {@link #getSuggestedMinimumWidth()}).
15004     * </p>
15005     *
15006     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15007     *                         The requirements are encoded with
15008     *                         {@link android.view.View.MeasureSpec}.
15009     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15010     *                         The requirements are encoded with
15011     *                         {@link android.view.View.MeasureSpec}.
15012     *
15013     * @see #getMeasuredWidth()
15014     * @see #getMeasuredHeight()
15015     * @see #setMeasuredDimension(int, int)
15016     * @see #getSuggestedMinimumHeight()
15017     * @see #getSuggestedMinimumWidth()
15018     * @see android.view.View.MeasureSpec#getMode(int)
15019     * @see android.view.View.MeasureSpec#getSize(int)
15020     */
15021    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15022        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15023                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15024    }
15025
15026    /**
15027     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15028     * measured width and measured height. Failing to do so will trigger an
15029     * exception at measurement time.</p>
15030     *
15031     * @param measuredWidth The measured width of this view.  May be a complex
15032     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15033     * {@link #MEASURED_STATE_TOO_SMALL}.
15034     * @param measuredHeight The measured height of this view.  May be a complex
15035     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15036     * {@link #MEASURED_STATE_TOO_SMALL}.
15037     */
15038    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15039        mMeasuredWidth = measuredWidth;
15040        mMeasuredHeight = measuredHeight;
15041
15042        mPrivateFlags |= MEASURED_DIMENSION_SET;
15043    }
15044
15045    /**
15046     * Merge two states as returned by {@link #getMeasuredState()}.
15047     * @param curState The current state as returned from a view or the result
15048     * of combining multiple views.
15049     * @param newState The new view state to combine.
15050     * @return Returns a new integer reflecting the combination of the two
15051     * states.
15052     */
15053    public static int combineMeasuredStates(int curState, int newState) {
15054        return curState | newState;
15055    }
15056
15057    /**
15058     * Version of {@link #resolveSizeAndState(int, int, int)}
15059     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15060     */
15061    public static int resolveSize(int size, int measureSpec) {
15062        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15063    }
15064
15065    /**
15066     * Utility to reconcile a desired size and state, with constraints imposed
15067     * by a MeasureSpec.  Will take the desired size, unless a different size
15068     * is imposed by the constraints.  The returned value is a compound integer,
15069     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15070     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15071     * size is smaller than the size the view wants to be.
15072     *
15073     * @param size How big the view wants to be
15074     * @param measureSpec Constraints imposed by the parent
15075     * @return Size information bit mask as defined by
15076     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15077     */
15078    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15079        int result = size;
15080        int specMode = MeasureSpec.getMode(measureSpec);
15081        int specSize =  MeasureSpec.getSize(measureSpec);
15082        switch (specMode) {
15083        case MeasureSpec.UNSPECIFIED:
15084            result = size;
15085            break;
15086        case MeasureSpec.AT_MOST:
15087            if (specSize < size) {
15088                result = specSize | MEASURED_STATE_TOO_SMALL;
15089            } else {
15090                result = size;
15091            }
15092            break;
15093        case MeasureSpec.EXACTLY:
15094            result = specSize;
15095            break;
15096        }
15097        return result | (childMeasuredState&MEASURED_STATE_MASK);
15098    }
15099
15100    /**
15101     * Utility to return a default size. Uses the supplied size if the
15102     * MeasureSpec imposed no constraints. Will get larger if allowed
15103     * by the MeasureSpec.
15104     *
15105     * @param size Default size for this view
15106     * @param measureSpec Constraints imposed by the parent
15107     * @return The size this view should be.
15108     */
15109    public static int getDefaultSize(int size, int measureSpec) {
15110        int result = size;
15111        int specMode = MeasureSpec.getMode(measureSpec);
15112        int specSize = MeasureSpec.getSize(measureSpec);
15113
15114        switch (specMode) {
15115        case MeasureSpec.UNSPECIFIED:
15116            result = size;
15117            break;
15118        case MeasureSpec.AT_MOST:
15119        case MeasureSpec.EXACTLY:
15120            result = specSize;
15121            break;
15122        }
15123        return result;
15124    }
15125
15126    /**
15127     * Returns the suggested minimum height that the view should use. This
15128     * returns the maximum of the view's minimum height
15129     * and the background's minimum height
15130     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15131     * <p>
15132     * When being used in {@link #onMeasure(int, int)}, the caller should still
15133     * ensure the returned height is within the requirements of the parent.
15134     *
15135     * @return The suggested minimum height of the view.
15136     */
15137    protected int getSuggestedMinimumHeight() {
15138        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15139
15140    }
15141
15142    /**
15143     * Returns the suggested minimum width that the view should use. This
15144     * returns the maximum of the view's minimum width)
15145     * and the background's minimum width
15146     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15147     * <p>
15148     * When being used in {@link #onMeasure(int, int)}, the caller should still
15149     * ensure the returned width is within the requirements of the parent.
15150     *
15151     * @return The suggested minimum width of the view.
15152     */
15153    protected int getSuggestedMinimumWidth() {
15154        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15155    }
15156
15157    /**
15158     * Returns the minimum height of the view.
15159     *
15160     * @return the minimum height the view will try to be.
15161     *
15162     * @see #setMinimumHeight(int)
15163     *
15164     * @attr ref android.R.styleable#View_minHeight
15165     */
15166    public int getMinimumHeight() {
15167        return mMinHeight;
15168    }
15169
15170    /**
15171     * Sets the minimum height of the view. It is not guaranteed the view will
15172     * be able to achieve this minimum height (for example, if its parent layout
15173     * constrains it with less available height).
15174     *
15175     * @param minHeight The minimum height the view will try to be.
15176     *
15177     * @see #getMinimumHeight()
15178     *
15179     * @attr ref android.R.styleable#View_minHeight
15180     */
15181    public void setMinimumHeight(int minHeight) {
15182        mMinHeight = minHeight;
15183        requestLayout();
15184    }
15185
15186    /**
15187     * Returns the minimum width of the view.
15188     *
15189     * @return the minimum width the view will try to be.
15190     *
15191     * @see #setMinimumWidth(int)
15192     *
15193     * @attr ref android.R.styleable#View_minWidth
15194     */
15195    public int getMinimumWidth() {
15196        return mMinWidth;
15197    }
15198
15199    /**
15200     * Sets the minimum width of the view. It is not guaranteed the view will
15201     * be able to achieve this minimum width (for example, if its parent layout
15202     * constrains it with less available width).
15203     *
15204     * @param minWidth The minimum width the view will try to be.
15205     *
15206     * @see #getMinimumWidth()
15207     *
15208     * @attr ref android.R.styleable#View_minWidth
15209     */
15210    public void setMinimumWidth(int minWidth) {
15211        mMinWidth = minWidth;
15212        requestLayout();
15213
15214    }
15215
15216    /**
15217     * Get the animation currently associated with this view.
15218     *
15219     * @return The animation that is currently playing or
15220     *         scheduled to play for this view.
15221     */
15222    public Animation getAnimation() {
15223        return mCurrentAnimation;
15224    }
15225
15226    /**
15227     * Start the specified animation now.
15228     *
15229     * @param animation the animation to start now
15230     */
15231    public void startAnimation(Animation animation) {
15232        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15233        setAnimation(animation);
15234        invalidateParentCaches();
15235        invalidate(true);
15236    }
15237
15238    /**
15239     * Cancels any animations for this view.
15240     */
15241    public void clearAnimation() {
15242        if (mCurrentAnimation != null) {
15243            mCurrentAnimation.detach();
15244        }
15245        mCurrentAnimation = null;
15246        invalidateParentIfNeeded();
15247    }
15248
15249    /**
15250     * Sets the next animation to play for this view.
15251     * If you want the animation to play immediately, use
15252     * {@link #startAnimation(android.view.animation.Animation)} instead.
15253     * This method provides allows fine-grained
15254     * control over the start time and invalidation, but you
15255     * must make sure that 1) the animation has a start time set, and
15256     * 2) the view's parent (which controls animations on its children)
15257     * will be invalidated when the animation is supposed to
15258     * start.
15259     *
15260     * @param animation The next animation, or null.
15261     */
15262    public void setAnimation(Animation animation) {
15263        mCurrentAnimation = animation;
15264
15265        if (animation != null) {
15266            // If the screen is off assume the animation start time is now instead of
15267            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15268            // would cause the animation to start when the screen turns back on
15269            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15270                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15271                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15272            }
15273            animation.reset();
15274        }
15275    }
15276
15277    /**
15278     * Invoked by a parent ViewGroup to notify the start of the animation
15279     * currently associated with this view. If you override this method,
15280     * always call super.onAnimationStart();
15281     *
15282     * @see #setAnimation(android.view.animation.Animation)
15283     * @see #getAnimation()
15284     */
15285    protected void onAnimationStart() {
15286        mPrivateFlags |= ANIMATION_STARTED;
15287    }
15288
15289    /**
15290     * Invoked by a parent ViewGroup to notify the end of the animation
15291     * currently associated with this view. If you override this method,
15292     * always call super.onAnimationEnd();
15293     *
15294     * @see #setAnimation(android.view.animation.Animation)
15295     * @see #getAnimation()
15296     */
15297    protected void onAnimationEnd() {
15298        mPrivateFlags &= ~ANIMATION_STARTED;
15299    }
15300
15301    /**
15302     * Invoked if there is a Transform that involves alpha. Subclass that can
15303     * draw themselves with the specified alpha should return true, and then
15304     * respect that alpha when their onDraw() is called. If this returns false
15305     * then the view may be redirected to draw into an offscreen buffer to
15306     * fulfill the request, which will look fine, but may be slower than if the
15307     * subclass handles it internally. The default implementation returns false.
15308     *
15309     * @param alpha The alpha (0..255) to apply to the view's drawing
15310     * @return true if the view can draw with the specified alpha.
15311     */
15312    protected boolean onSetAlpha(int alpha) {
15313        return false;
15314    }
15315
15316    /**
15317     * This is used by the RootView to perform an optimization when
15318     * the view hierarchy contains one or several SurfaceView.
15319     * SurfaceView is always considered transparent, but its children are not,
15320     * therefore all View objects remove themselves from the global transparent
15321     * region (passed as a parameter to this function).
15322     *
15323     * @param region The transparent region for this ViewAncestor (window).
15324     *
15325     * @return Returns true if the effective visibility of the view at this
15326     * point is opaque, regardless of the transparent region; returns false
15327     * if it is possible for underlying windows to be seen behind the view.
15328     *
15329     * {@hide}
15330     */
15331    public boolean gatherTransparentRegion(Region region) {
15332        final AttachInfo attachInfo = mAttachInfo;
15333        if (region != null && attachInfo != null) {
15334            final int pflags = mPrivateFlags;
15335            if ((pflags & SKIP_DRAW) == 0) {
15336                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15337                // remove it from the transparent region.
15338                final int[] location = attachInfo.mTransparentLocation;
15339                getLocationInWindow(location);
15340                region.op(location[0], location[1], location[0] + mRight - mLeft,
15341                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15342            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15343                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15344                // exists, so we remove the background drawable's non-transparent
15345                // parts from this transparent region.
15346                applyDrawableToTransparentRegion(mBackground, region);
15347            }
15348        }
15349        return true;
15350    }
15351
15352    /**
15353     * Play a sound effect for this view.
15354     *
15355     * <p>The framework will play sound effects for some built in actions, such as
15356     * clicking, but you may wish to play these effects in your widget,
15357     * for instance, for internal navigation.
15358     *
15359     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15360     * {@link #isSoundEffectsEnabled()} is true.
15361     *
15362     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15363     */
15364    public void playSoundEffect(int soundConstant) {
15365        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15366            return;
15367        }
15368        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15369    }
15370
15371    /**
15372     * BZZZTT!!1!
15373     *
15374     * <p>Provide haptic feedback to the user for this view.
15375     *
15376     * <p>The framework will provide haptic feedback for some built in actions,
15377     * such as long presses, but you may wish to provide feedback for your
15378     * own widget.
15379     *
15380     * <p>The feedback will only be performed if
15381     * {@link #isHapticFeedbackEnabled()} is true.
15382     *
15383     * @param feedbackConstant One of the constants defined in
15384     * {@link HapticFeedbackConstants}
15385     */
15386    public boolean performHapticFeedback(int feedbackConstant) {
15387        return performHapticFeedback(feedbackConstant, 0);
15388    }
15389
15390    /**
15391     * BZZZTT!!1!
15392     *
15393     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15394     *
15395     * @param feedbackConstant One of the constants defined in
15396     * {@link HapticFeedbackConstants}
15397     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15398     */
15399    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15400        if (mAttachInfo == null) {
15401            return false;
15402        }
15403        //noinspection SimplifiableIfStatement
15404        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15405                && !isHapticFeedbackEnabled()) {
15406            return false;
15407        }
15408        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15409                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15410    }
15411
15412    /**
15413     * Request that the visibility of the status bar or other screen/window
15414     * decorations be changed.
15415     *
15416     * <p>This method is used to put the over device UI into temporary modes
15417     * where the user's attention is focused more on the application content,
15418     * by dimming or hiding surrounding system affordances.  This is typically
15419     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15420     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15421     * to be placed behind the action bar (and with these flags other system
15422     * affordances) so that smooth transitions between hiding and showing them
15423     * can be done.
15424     *
15425     * <p>Two representative examples of the use of system UI visibility is
15426     * implementing a content browsing application (like a magazine reader)
15427     * and a video playing application.
15428     *
15429     * <p>The first code shows a typical implementation of a View in a content
15430     * browsing application.  In this implementation, the application goes
15431     * into a content-oriented mode by hiding the status bar and action bar,
15432     * and putting the navigation elements into lights out mode.  The user can
15433     * then interact with content while in this mode.  Such an application should
15434     * provide an easy way for the user to toggle out of the mode (such as to
15435     * check information in the status bar or access notifications).  In the
15436     * implementation here, this is done simply by tapping on the content.
15437     *
15438     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15439     *      content}
15440     *
15441     * <p>This second code sample shows a typical implementation of a View
15442     * in a video playing application.  In this situation, while the video is
15443     * playing the application would like to go into a complete full-screen mode,
15444     * to use as much of the display as possible for the video.  When in this state
15445     * the user can not interact with the application; the system intercepts
15446     * touching on the screen to pop the UI out of full screen mode.  See
15447     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15448     *
15449     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15450     *      content}
15451     *
15452     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15453     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15454     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15455     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15456     */
15457    public void setSystemUiVisibility(int visibility) {
15458        if (visibility != mSystemUiVisibility) {
15459            mSystemUiVisibility = visibility;
15460            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15461                mParent.recomputeViewAttributes(this);
15462            }
15463        }
15464    }
15465
15466    /**
15467     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15468     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15469     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15470     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15471     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15472     */
15473    public int getSystemUiVisibility() {
15474        return mSystemUiVisibility;
15475    }
15476
15477    /**
15478     * Returns the current system UI visibility that is currently set for
15479     * the entire window.  This is the combination of the
15480     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15481     * views in the window.
15482     */
15483    public int getWindowSystemUiVisibility() {
15484        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15485    }
15486
15487    /**
15488     * Override to find out when the window's requested system UI visibility
15489     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15490     * This is different from the callbacks recieved through
15491     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15492     * in that this is only telling you about the local request of the window,
15493     * not the actual values applied by the system.
15494     */
15495    public void onWindowSystemUiVisibilityChanged(int visible) {
15496    }
15497
15498    /**
15499     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15500     * the view hierarchy.
15501     */
15502    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15503        onWindowSystemUiVisibilityChanged(visible);
15504    }
15505
15506    /**
15507     * Set a listener to receive callbacks when the visibility of the system bar changes.
15508     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15509     */
15510    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15511        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15512        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15513            mParent.recomputeViewAttributes(this);
15514        }
15515    }
15516
15517    /**
15518     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15519     * the view hierarchy.
15520     */
15521    public void dispatchSystemUiVisibilityChanged(int visibility) {
15522        ListenerInfo li = mListenerInfo;
15523        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15524            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15525                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15526        }
15527    }
15528
15529    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15530        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15531        if (val != mSystemUiVisibility) {
15532            setSystemUiVisibility(val);
15533            return true;
15534        }
15535        return false;
15536    }
15537
15538    /** @hide */
15539    public void setDisabledSystemUiVisibility(int flags) {
15540        if (mAttachInfo != null) {
15541            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15542                mAttachInfo.mDisabledSystemUiVisibility = flags;
15543                if (mParent != null) {
15544                    mParent.recomputeViewAttributes(this);
15545                }
15546            }
15547        }
15548    }
15549
15550    /**
15551     * Creates an image that the system displays during the drag and drop
15552     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15553     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15554     * appearance as the given View. The default also positions the center of the drag shadow
15555     * directly under the touch point. If no View is provided (the constructor with no parameters
15556     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15557     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15558     * default is an invisible drag shadow.
15559     * <p>
15560     * You are not required to use the View you provide to the constructor as the basis of the
15561     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15562     * anything you want as the drag shadow.
15563     * </p>
15564     * <p>
15565     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15566     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15567     *  size and position of the drag shadow. It uses this data to construct a
15568     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15569     *  so that your application can draw the shadow image in the Canvas.
15570     * </p>
15571     *
15572     * <div class="special reference">
15573     * <h3>Developer Guides</h3>
15574     * <p>For a guide to implementing drag and drop features, read the
15575     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15576     * </div>
15577     */
15578    public static class DragShadowBuilder {
15579        private final WeakReference<View> mView;
15580
15581        /**
15582         * Constructs a shadow image builder based on a View. By default, the resulting drag
15583         * shadow will have the same appearance and dimensions as the View, with the touch point
15584         * over the center of the View.
15585         * @param view A View. Any View in scope can be used.
15586         */
15587        public DragShadowBuilder(View view) {
15588            mView = new WeakReference<View>(view);
15589        }
15590
15591        /**
15592         * Construct a shadow builder object with no associated View.  This
15593         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15594         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15595         * to supply the drag shadow's dimensions and appearance without
15596         * reference to any View object. If they are not overridden, then the result is an
15597         * invisible drag shadow.
15598         */
15599        public DragShadowBuilder() {
15600            mView = new WeakReference<View>(null);
15601        }
15602
15603        /**
15604         * Returns the View object that had been passed to the
15605         * {@link #View.DragShadowBuilder(View)}
15606         * constructor.  If that View parameter was {@code null} or if the
15607         * {@link #View.DragShadowBuilder()}
15608         * constructor was used to instantiate the builder object, this method will return
15609         * null.
15610         *
15611         * @return The View object associate with this builder object.
15612         */
15613        @SuppressWarnings({"JavadocReference"})
15614        final public View getView() {
15615            return mView.get();
15616        }
15617
15618        /**
15619         * Provides the metrics for the shadow image. These include the dimensions of
15620         * the shadow image, and the point within that shadow that should
15621         * be centered under the touch location while dragging.
15622         * <p>
15623         * The default implementation sets the dimensions of the shadow to be the
15624         * same as the dimensions of the View itself and centers the shadow under
15625         * the touch point.
15626         * </p>
15627         *
15628         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15629         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15630         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15631         * image.
15632         *
15633         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15634         * shadow image that should be underneath the touch point during the drag and drop
15635         * operation. Your application must set {@link android.graphics.Point#x} to the
15636         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15637         */
15638        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15639            final View view = mView.get();
15640            if (view != null) {
15641                shadowSize.set(view.getWidth(), view.getHeight());
15642                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15643            } else {
15644                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15645            }
15646        }
15647
15648        /**
15649         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15650         * based on the dimensions it received from the
15651         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15652         *
15653         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15654         */
15655        public void onDrawShadow(Canvas canvas) {
15656            final View view = mView.get();
15657            if (view != null) {
15658                view.draw(canvas);
15659            } else {
15660                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15661            }
15662        }
15663    }
15664
15665    /**
15666     * Starts a drag and drop operation. When your application calls this method, it passes a
15667     * {@link android.view.View.DragShadowBuilder} object to the system. The
15668     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15669     * to get metrics for the drag shadow, and then calls the object's
15670     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15671     * <p>
15672     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15673     *  drag events to all the View objects in your application that are currently visible. It does
15674     *  this either by calling the View object's drag listener (an implementation of
15675     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15676     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15677     *  Both are passed a {@link android.view.DragEvent} object that has a
15678     *  {@link android.view.DragEvent#getAction()} value of
15679     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15680     * </p>
15681     * <p>
15682     * Your application can invoke startDrag() on any attached View object. The View object does not
15683     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15684     * be related to the View the user selected for dragging.
15685     * </p>
15686     * @param data A {@link android.content.ClipData} object pointing to the data to be
15687     * transferred by the drag and drop operation.
15688     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15689     * drag shadow.
15690     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15691     * drop operation. This Object is put into every DragEvent object sent by the system during the
15692     * current drag.
15693     * <p>
15694     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15695     * to the target Views. For example, it can contain flags that differentiate between a
15696     * a copy operation and a move operation.
15697     * </p>
15698     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15699     * so the parameter should be set to 0.
15700     * @return {@code true} if the method completes successfully, or
15701     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15702     * do a drag, and so no drag operation is in progress.
15703     */
15704    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15705            Object myLocalState, int flags) {
15706        if (ViewDebug.DEBUG_DRAG) {
15707            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15708        }
15709        boolean okay = false;
15710
15711        Point shadowSize = new Point();
15712        Point shadowTouchPoint = new Point();
15713        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15714
15715        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15716                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15717            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15718        }
15719
15720        if (ViewDebug.DEBUG_DRAG) {
15721            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15722                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15723        }
15724        Surface surface = new Surface();
15725        try {
15726            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15727                    flags, shadowSize.x, shadowSize.y, surface);
15728            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15729                    + " surface=" + surface);
15730            if (token != null) {
15731                Canvas canvas = surface.lockCanvas(null);
15732                try {
15733                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15734                    shadowBuilder.onDrawShadow(canvas);
15735                } finally {
15736                    surface.unlockCanvasAndPost(canvas);
15737                }
15738
15739                final ViewRootImpl root = getViewRootImpl();
15740
15741                // Cache the local state object for delivery with DragEvents
15742                root.setLocalDragState(myLocalState);
15743
15744                // repurpose 'shadowSize' for the last touch point
15745                root.getLastTouchPoint(shadowSize);
15746
15747                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15748                        shadowSize.x, shadowSize.y,
15749                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15750                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15751
15752                // Off and running!  Release our local surface instance; the drag
15753                // shadow surface is now managed by the system process.
15754                surface.release();
15755            }
15756        } catch (Exception e) {
15757            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15758            surface.destroy();
15759        }
15760
15761        return okay;
15762    }
15763
15764    /**
15765     * Handles drag events sent by the system following a call to
15766     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15767     *<p>
15768     * When the system calls this method, it passes a
15769     * {@link android.view.DragEvent} object. A call to
15770     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15771     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15772     * operation.
15773     * @param event The {@link android.view.DragEvent} sent by the system.
15774     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15775     * in DragEvent, indicating the type of drag event represented by this object.
15776     * @return {@code true} if the method was successful, otherwise {@code false}.
15777     * <p>
15778     *  The method should return {@code true} in response to an action type of
15779     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15780     *  operation.
15781     * </p>
15782     * <p>
15783     *  The method should also return {@code true} in response to an action type of
15784     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15785     *  {@code false} if it didn't.
15786     * </p>
15787     */
15788    public boolean onDragEvent(DragEvent event) {
15789        return false;
15790    }
15791
15792    /**
15793     * Detects if this View is enabled and has a drag event listener.
15794     * If both are true, then it calls the drag event listener with the
15795     * {@link android.view.DragEvent} it received. If the drag event listener returns
15796     * {@code true}, then dispatchDragEvent() returns {@code true}.
15797     * <p>
15798     * For all other cases, the method calls the
15799     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15800     * method and returns its result.
15801     * </p>
15802     * <p>
15803     * This ensures that a drag event is always consumed, even if the View does not have a drag
15804     * event listener. However, if the View has a listener and the listener returns true, then
15805     * onDragEvent() is not called.
15806     * </p>
15807     */
15808    public boolean dispatchDragEvent(DragEvent event) {
15809        //noinspection SimplifiableIfStatement
15810        ListenerInfo li = mListenerInfo;
15811        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15812                && li.mOnDragListener.onDrag(this, event)) {
15813            return true;
15814        }
15815        return onDragEvent(event);
15816    }
15817
15818    boolean canAcceptDrag() {
15819        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15820    }
15821
15822    /**
15823     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15824     * it is ever exposed at all.
15825     * @hide
15826     */
15827    public void onCloseSystemDialogs(String reason) {
15828    }
15829
15830    /**
15831     * Given a Drawable whose bounds have been set to draw into this view,
15832     * update a Region being computed for
15833     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15834     * that any non-transparent parts of the Drawable are removed from the
15835     * given transparent region.
15836     *
15837     * @param dr The Drawable whose transparency is to be applied to the region.
15838     * @param region A Region holding the current transparency information,
15839     * where any parts of the region that are set are considered to be
15840     * transparent.  On return, this region will be modified to have the
15841     * transparency information reduced by the corresponding parts of the
15842     * Drawable that are not transparent.
15843     * {@hide}
15844     */
15845    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15846        if (DBG) {
15847            Log.i("View", "Getting transparent region for: " + this);
15848        }
15849        final Region r = dr.getTransparentRegion();
15850        final Rect db = dr.getBounds();
15851        final AttachInfo attachInfo = mAttachInfo;
15852        if (r != null && attachInfo != null) {
15853            final int w = getRight()-getLeft();
15854            final int h = getBottom()-getTop();
15855            if (db.left > 0) {
15856                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15857                r.op(0, 0, db.left, h, Region.Op.UNION);
15858            }
15859            if (db.right < w) {
15860                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15861                r.op(db.right, 0, w, h, Region.Op.UNION);
15862            }
15863            if (db.top > 0) {
15864                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15865                r.op(0, 0, w, db.top, Region.Op.UNION);
15866            }
15867            if (db.bottom < h) {
15868                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15869                r.op(0, db.bottom, w, h, Region.Op.UNION);
15870            }
15871            final int[] location = attachInfo.mTransparentLocation;
15872            getLocationInWindow(location);
15873            r.translate(location[0], location[1]);
15874            region.op(r, Region.Op.INTERSECT);
15875        } else {
15876            region.op(db, Region.Op.DIFFERENCE);
15877        }
15878    }
15879
15880    private void checkForLongClick(int delayOffset) {
15881        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15882            mHasPerformedLongPress = false;
15883
15884            if (mPendingCheckForLongPress == null) {
15885                mPendingCheckForLongPress = new CheckForLongPress();
15886            }
15887            mPendingCheckForLongPress.rememberWindowAttachCount();
15888            postDelayed(mPendingCheckForLongPress,
15889                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15890        }
15891    }
15892
15893    /**
15894     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15895     * LayoutInflater} class, which provides a full range of options for view inflation.
15896     *
15897     * @param context The Context object for your activity or application.
15898     * @param resource The resource ID to inflate
15899     * @param root A view group that will be the parent.  Used to properly inflate the
15900     * layout_* parameters.
15901     * @see LayoutInflater
15902     */
15903    public static View inflate(Context context, int resource, ViewGroup root) {
15904        LayoutInflater factory = LayoutInflater.from(context);
15905        return factory.inflate(resource, root);
15906    }
15907
15908    /**
15909     * Scroll the view with standard behavior for scrolling beyond the normal
15910     * content boundaries. Views that call this method should override
15911     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15912     * results of an over-scroll operation.
15913     *
15914     * Views can use this method to handle any touch or fling-based scrolling.
15915     *
15916     * @param deltaX Change in X in pixels
15917     * @param deltaY Change in Y in pixels
15918     * @param scrollX Current X scroll value in pixels before applying deltaX
15919     * @param scrollY Current Y scroll value in pixels before applying deltaY
15920     * @param scrollRangeX Maximum content scroll range along the X axis
15921     * @param scrollRangeY Maximum content scroll range along the Y axis
15922     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15923     *          along the X axis.
15924     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15925     *          along the Y axis.
15926     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15927     * @return true if scrolling was clamped to an over-scroll boundary along either
15928     *          axis, false otherwise.
15929     */
15930    @SuppressWarnings({"UnusedParameters"})
15931    protected boolean overScrollBy(int deltaX, int deltaY,
15932            int scrollX, int scrollY,
15933            int scrollRangeX, int scrollRangeY,
15934            int maxOverScrollX, int maxOverScrollY,
15935            boolean isTouchEvent) {
15936        final int overScrollMode = mOverScrollMode;
15937        final boolean canScrollHorizontal =
15938                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15939        final boolean canScrollVertical =
15940                computeVerticalScrollRange() > computeVerticalScrollExtent();
15941        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15942                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15943        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15944                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15945
15946        int newScrollX = scrollX + deltaX;
15947        if (!overScrollHorizontal) {
15948            maxOverScrollX = 0;
15949        }
15950
15951        int newScrollY = scrollY + deltaY;
15952        if (!overScrollVertical) {
15953            maxOverScrollY = 0;
15954        }
15955
15956        // Clamp values if at the limits and record
15957        final int left = -maxOverScrollX;
15958        final int right = maxOverScrollX + scrollRangeX;
15959        final int top = -maxOverScrollY;
15960        final int bottom = maxOverScrollY + scrollRangeY;
15961
15962        boolean clampedX = false;
15963        if (newScrollX > right) {
15964            newScrollX = right;
15965            clampedX = true;
15966        } else if (newScrollX < left) {
15967            newScrollX = left;
15968            clampedX = true;
15969        }
15970
15971        boolean clampedY = false;
15972        if (newScrollY > bottom) {
15973            newScrollY = bottom;
15974            clampedY = true;
15975        } else if (newScrollY < top) {
15976            newScrollY = top;
15977            clampedY = true;
15978        }
15979
15980        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15981
15982        return clampedX || clampedY;
15983    }
15984
15985    /**
15986     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15987     * respond to the results of an over-scroll operation.
15988     *
15989     * @param scrollX New X scroll value in pixels
15990     * @param scrollY New Y scroll value in pixels
15991     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15992     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15993     */
15994    protected void onOverScrolled(int scrollX, int scrollY,
15995            boolean clampedX, boolean clampedY) {
15996        // Intentionally empty.
15997    }
15998
15999    /**
16000     * Returns the over-scroll mode for this view. The result will be
16001     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16002     * (allow over-scrolling only if the view content is larger than the container),
16003     * or {@link #OVER_SCROLL_NEVER}.
16004     *
16005     * @return This view's over-scroll mode.
16006     */
16007    public int getOverScrollMode() {
16008        return mOverScrollMode;
16009    }
16010
16011    /**
16012     * Set the over-scroll mode for this view. Valid over-scroll modes are
16013     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16014     * (allow over-scrolling only if the view content is larger than the container),
16015     * or {@link #OVER_SCROLL_NEVER}.
16016     *
16017     * Setting the over-scroll mode of a view will have an effect only if the
16018     * view is capable of scrolling.
16019     *
16020     * @param overScrollMode The new over-scroll mode for this view.
16021     */
16022    public void setOverScrollMode(int overScrollMode) {
16023        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16024                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16025                overScrollMode != OVER_SCROLL_NEVER) {
16026            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16027        }
16028        mOverScrollMode = overScrollMode;
16029    }
16030
16031    /**
16032     * Gets a scale factor that determines the distance the view should scroll
16033     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16034     * @return The vertical scroll scale factor.
16035     * @hide
16036     */
16037    protected float getVerticalScrollFactor() {
16038        if (mVerticalScrollFactor == 0) {
16039            TypedValue outValue = new TypedValue();
16040            if (!mContext.getTheme().resolveAttribute(
16041                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16042                throw new IllegalStateException(
16043                        "Expected theme to define listPreferredItemHeight.");
16044            }
16045            mVerticalScrollFactor = outValue.getDimension(
16046                    mContext.getResources().getDisplayMetrics());
16047        }
16048        return mVerticalScrollFactor;
16049    }
16050
16051    /**
16052     * Gets a scale factor that determines the distance the view should scroll
16053     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16054     * @return The horizontal scroll scale factor.
16055     * @hide
16056     */
16057    protected float getHorizontalScrollFactor() {
16058        // TODO: Should use something else.
16059        return getVerticalScrollFactor();
16060    }
16061
16062    /**
16063     * Return the value specifying the text direction or policy that was set with
16064     * {@link #setTextDirection(int)}.
16065     *
16066     * @return the defined text direction. It can be one of:
16067     *
16068     * {@link #TEXT_DIRECTION_INHERIT},
16069     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16070     * {@link #TEXT_DIRECTION_ANY_RTL},
16071     * {@link #TEXT_DIRECTION_LTR},
16072     * {@link #TEXT_DIRECTION_RTL},
16073     * {@link #TEXT_DIRECTION_LOCALE}
16074     */
16075    @ViewDebug.ExportedProperty(category = "text", mapping = {
16076            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16077            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16078            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16079            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16080            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16081            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16082    })
16083    public int getTextDirection() {
16084        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16085    }
16086
16087    /**
16088     * Set the text direction.
16089     *
16090     * @param textDirection the direction to set. Should be one of:
16091     *
16092     * {@link #TEXT_DIRECTION_INHERIT},
16093     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16094     * {@link #TEXT_DIRECTION_ANY_RTL},
16095     * {@link #TEXT_DIRECTION_LTR},
16096     * {@link #TEXT_DIRECTION_RTL},
16097     * {@link #TEXT_DIRECTION_LOCALE}
16098     */
16099    public void setTextDirection(int textDirection) {
16100        if (getTextDirection() != textDirection) {
16101            // Reset the current text direction and the resolved one
16102            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16103            resetResolvedTextDirection();
16104            // Set the new text direction
16105            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16106            // Refresh
16107            requestLayout();
16108            invalidate(true);
16109        }
16110    }
16111
16112    /**
16113     * Return the resolved text direction.
16114     *
16115     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16116     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16117     * up the parent chain of the view. if there is no parent, then it will return the default
16118     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16119     *
16120     * @return the resolved text direction. Returns one of:
16121     *
16122     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16123     * {@link #TEXT_DIRECTION_ANY_RTL},
16124     * {@link #TEXT_DIRECTION_LTR},
16125     * {@link #TEXT_DIRECTION_RTL},
16126     * {@link #TEXT_DIRECTION_LOCALE}
16127     */
16128    public int getResolvedTextDirection() {
16129        // The text direction will be resolved only if needed
16130        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16131            resolveTextDirection();
16132        }
16133        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16134    }
16135
16136    /**
16137     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16138     * resolution is done.
16139     */
16140    public void resolveTextDirection() {
16141        // Reset any previous text direction resolution
16142        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16143
16144        if (hasRtlSupport()) {
16145            // Set resolved text direction flag depending on text direction flag
16146            final int textDirection = getTextDirection();
16147            switch(textDirection) {
16148                case TEXT_DIRECTION_INHERIT:
16149                    if (canResolveTextDirection()) {
16150                        ViewGroup viewGroup = ((ViewGroup) mParent);
16151
16152                        // Set current resolved direction to the same value as the parent's one
16153                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16154                        switch (parentResolvedDirection) {
16155                            case TEXT_DIRECTION_FIRST_STRONG:
16156                            case TEXT_DIRECTION_ANY_RTL:
16157                            case TEXT_DIRECTION_LTR:
16158                            case TEXT_DIRECTION_RTL:
16159                            case TEXT_DIRECTION_LOCALE:
16160                                mPrivateFlags2 |=
16161                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16162                                break;
16163                            default:
16164                                // Default resolved direction is "first strong" heuristic
16165                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16166                        }
16167                    } else {
16168                        // We cannot do the resolution if there is no parent, so use the default one
16169                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16170                    }
16171                    break;
16172                case TEXT_DIRECTION_FIRST_STRONG:
16173                case TEXT_DIRECTION_ANY_RTL:
16174                case TEXT_DIRECTION_LTR:
16175                case TEXT_DIRECTION_RTL:
16176                case TEXT_DIRECTION_LOCALE:
16177                    // Resolved direction is the same as text direction
16178                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16179                    break;
16180                default:
16181                    // Default resolved direction is "first strong" heuristic
16182                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16183            }
16184        } else {
16185            // Default resolved direction is "first strong" heuristic
16186            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16187        }
16188
16189        // Set to resolved
16190        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16191        onResolvedTextDirectionChanged();
16192    }
16193
16194    /**
16195     * Called when text direction has been resolved. Subclasses that care about text direction
16196     * resolution should override this method.
16197     *
16198     * The default implementation does nothing.
16199     */
16200    public void onResolvedTextDirectionChanged() {
16201    }
16202
16203    /**
16204     * Check if text direction resolution can be done.
16205     *
16206     * @return true if text direction resolution can be done otherwise return false.
16207     */
16208    public boolean canResolveTextDirection() {
16209        switch (getTextDirection()) {
16210            case TEXT_DIRECTION_INHERIT:
16211                return (mParent != null) && (mParent instanceof ViewGroup);
16212            default:
16213                return true;
16214        }
16215    }
16216
16217    /**
16218     * Reset resolved text direction. Text direction can be resolved with a call to
16219     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16220     * reset is done.
16221     */
16222    public void resetResolvedTextDirection() {
16223        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16224        onResolvedTextDirectionReset();
16225    }
16226
16227    /**
16228     * Called when text direction is reset. Subclasses that care about text direction reset should
16229     * override this method and do a reset of the text direction of their children. The default
16230     * implementation does nothing.
16231     */
16232    public void onResolvedTextDirectionReset() {
16233    }
16234
16235    /**
16236     * Return the value specifying the text alignment or policy that was set with
16237     * {@link #setTextAlignment(int)}.
16238     *
16239     * @return the defined text alignment. It can be one of:
16240     *
16241     * {@link #TEXT_ALIGNMENT_INHERIT},
16242     * {@link #TEXT_ALIGNMENT_GRAVITY},
16243     * {@link #TEXT_ALIGNMENT_CENTER},
16244     * {@link #TEXT_ALIGNMENT_TEXT_START},
16245     * {@link #TEXT_ALIGNMENT_TEXT_END},
16246     * {@link #TEXT_ALIGNMENT_VIEW_START},
16247     * {@link #TEXT_ALIGNMENT_VIEW_END}
16248     */
16249    @ViewDebug.ExportedProperty(category = "text", mapping = {
16250            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16251            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16252            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16253            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16254            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16255            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16256            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16257    })
16258    public int getTextAlignment() {
16259        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16260    }
16261
16262    /**
16263     * Set the text alignment.
16264     *
16265     * @param textAlignment The text alignment to set. Should be one of
16266     *
16267     * {@link #TEXT_ALIGNMENT_INHERIT},
16268     * {@link #TEXT_ALIGNMENT_GRAVITY},
16269     * {@link #TEXT_ALIGNMENT_CENTER},
16270     * {@link #TEXT_ALIGNMENT_TEXT_START},
16271     * {@link #TEXT_ALIGNMENT_TEXT_END},
16272     * {@link #TEXT_ALIGNMENT_VIEW_START},
16273     * {@link #TEXT_ALIGNMENT_VIEW_END}
16274     *
16275     * @attr ref android.R.styleable#View_textAlignment
16276     */
16277    public void setTextAlignment(int textAlignment) {
16278        if (textAlignment != getTextAlignment()) {
16279            // Reset the current and resolved text alignment
16280            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16281            resetResolvedTextAlignment();
16282            // Set the new text alignment
16283            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16284            // Refresh
16285            requestLayout();
16286            invalidate(true);
16287        }
16288    }
16289
16290    /**
16291     * Return the resolved text alignment.
16292     *
16293     * The resolved text alignment. This needs resolution if the value is
16294     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16295     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16296     *
16297     * @return the resolved text alignment. Returns one of:
16298     *
16299     * {@link #TEXT_ALIGNMENT_GRAVITY},
16300     * {@link #TEXT_ALIGNMENT_CENTER},
16301     * {@link #TEXT_ALIGNMENT_TEXT_START},
16302     * {@link #TEXT_ALIGNMENT_TEXT_END},
16303     * {@link #TEXT_ALIGNMENT_VIEW_START},
16304     * {@link #TEXT_ALIGNMENT_VIEW_END}
16305     */
16306    @ViewDebug.ExportedProperty(category = "text", mapping = {
16307            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16308            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16309            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16310            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16311            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16312            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16313            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16314    })
16315    public int getResolvedTextAlignment() {
16316        // If text alignment is not resolved, then resolve it
16317        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16318            resolveTextAlignment();
16319        }
16320        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16321    }
16322
16323    /**
16324     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16325     * resolution is done.
16326     */
16327    public void resolveTextAlignment() {
16328        // Reset any previous text alignment resolution
16329        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16330
16331        if (hasRtlSupport()) {
16332            // Set resolved text alignment flag depending on text alignment flag
16333            final int textAlignment = getTextAlignment();
16334            switch (textAlignment) {
16335                case TEXT_ALIGNMENT_INHERIT:
16336                    // Check if we can resolve the text alignment
16337                    if (canResolveLayoutDirection() && mParent instanceof View) {
16338                        View view = (View) mParent;
16339
16340                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16341                        switch (parentResolvedTextAlignment) {
16342                            case TEXT_ALIGNMENT_GRAVITY:
16343                            case TEXT_ALIGNMENT_TEXT_START:
16344                            case TEXT_ALIGNMENT_TEXT_END:
16345                            case TEXT_ALIGNMENT_CENTER:
16346                            case TEXT_ALIGNMENT_VIEW_START:
16347                            case TEXT_ALIGNMENT_VIEW_END:
16348                                // Resolved text alignment is the same as the parent resolved
16349                                // text alignment
16350                                mPrivateFlags2 |=
16351                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16352                                break;
16353                            default:
16354                                // Use default resolved text alignment
16355                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16356                        }
16357                    }
16358                    else {
16359                        // We cannot do the resolution if there is no parent so use the default
16360                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16361                    }
16362                    break;
16363                case TEXT_ALIGNMENT_GRAVITY:
16364                case TEXT_ALIGNMENT_TEXT_START:
16365                case TEXT_ALIGNMENT_TEXT_END:
16366                case TEXT_ALIGNMENT_CENTER:
16367                case TEXT_ALIGNMENT_VIEW_START:
16368                case TEXT_ALIGNMENT_VIEW_END:
16369                    // Resolved text alignment is the same as text alignment
16370                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16371                    break;
16372                default:
16373                    // Use default resolved text alignment
16374                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16375            }
16376        } else {
16377            // Use default resolved text alignment
16378            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16379        }
16380
16381        // Set the resolved
16382        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16383        onResolvedTextAlignmentChanged();
16384    }
16385
16386    /**
16387     * Check if text alignment resolution can be done.
16388     *
16389     * @return true if text alignment resolution can be done otherwise return false.
16390     */
16391    public boolean canResolveTextAlignment() {
16392        switch (getTextAlignment()) {
16393            case TEXT_DIRECTION_INHERIT:
16394                return (mParent != null);
16395            default:
16396                return true;
16397        }
16398    }
16399
16400    /**
16401     * Called when text alignment has been resolved. Subclasses that care about text alignment
16402     * resolution should override this method.
16403     *
16404     * The default implementation does nothing.
16405     */
16406    public void onResolvedTextAlignmentChanged() {
16407    }
16408
16409    /**
16410     * Reset resolved text alignment. Text alignment can be resolved with a call to
16411     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16412     * reset is done.
16413     */
16414    public void resetResolvedTextAlignment() {
16415        // Reset any previous text alignment resolution
16416        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16417        onResolvedTextAlignmentReset();
16418    }
16419
16420    /**
16421     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16422     * override this method and do a reset of the text alignment of their children. The default
16423     * implementation does nothing.
16424     */
16425    public void onResolvedTextAlignmentReset() {
16426    }
16427
16428    //
16429    // Properties
16430    //
16431    /**
16432     * A Property wrapper around the <code>alpha</code> functionality handled by the
16433     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16434     */
16435    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16436        @Override
16437        public void setValue(View object, float value) {
16438            object.setAlpha(value);
16439        }
16440
16441        @Override
16442        public Float get(View object) {
16443            return object.getAlpha();
16444        }
16445    };
16446
16447    /**
16448     * A Property wrapper around the <code>translationX</code> functionality handled by the
16449     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16450     */
16451    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16452        @Override
16453        public void setValue(View object, float value) {
16454            object.setTranslationX(value);
16455        }
16456
16457                @Override
16458        public Float get(View object) {
16459            return object.getTranslationX();
16460        }
16461    };
16462
16463    /**
16464     * A Property wrapper around the <code>translationY</code> functionality handled by the
16465     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16466     */
16467    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16468        @Override
16469        public void setValue(View object, float value) {
16470            object.setTranslationY(value);
16471        }
16472
16473        @Override
16474        public Float get(View object) {
16475            return object.getTranslationY();
16476        }
16477    };
16478
16479    /**
16480     * A Property wrapper around the <code>x</code> functionality handled by the
16481     * {@link View#setX(float)} and {@link View#getX()} methods.
16482     */
16483    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16484        @Override
16485        public void setValue(View object, float value) {
16486            object.setX(value);
16487        }
16488
16489        @Override
16490        public Float get(View object) {
16491            return object.getX();
16492        }
16493    };
16494
16495    /**
16496     * A Property wrapper around the <code>y</code> functionality handled by the
16497     * {@link View#setY(float)} and {@link View#getY()} methods.
16498     */
16499    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16500        @Override
16501        public void setValue(View object, float value) {
16502            object.setY(value);
16503        }
16504
16505        @Override
16506        public Float get(View object) {
16507            return object.getY();
16508        }
16509    };
16510
16511    /**
16512     * A Property wrapper around the <code>rotation</code> functionality handled by the
16513     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16514     */
16515    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16516        @Override
16517        public void setValue(View object, float value) {
16518            object.setRotation(value);
16519        }
16520
16521        @Override
16522        public Float get(View object) {
16523            return object.getRotation();
16524        }
16525    };
16526
16527    /**
16528     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16529     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16530     */
16531    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16532        @Override
16533        public void setValue(View object, float value) {
16534            object.setRotationX(value);
16535        }
16536
16537        @Override
16538        public Float get(View object) {
16539            return object.getRotationX();
16540        }
16541    };
16542
16543    /**
16544     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16545     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16546     */
16547    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16548        @Override
16549        public void setValue(View object, float value) {
16550            object.setRotationY(value);
16551        }
16552
16553        @Override
16554        public Float get(View object) {
16555            return object.getRotationY();
16556        }
16557    };
16558
16559    /**
16560     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16561     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16562     */
16563    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16564        @Override
16565        public void setValue(View object, float value) {
16566            object.setScaleX(value);
16567        }
16568
16569        @Override
16570        public Float get(View object) {
16571            return object.getScaleX();
16572        }
16573    };
16574
16575    /**
16576     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16577     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16578     */
16579    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16580        @Override
16581        public void setValue(View object, float value) {
16582            object.setScaleY(value);
16583        }
16584
16585        @Override
16586        public Float get(View object) {
16587            return object.getScaleY();
16588        }
16589    };
16590
16591    /**
16592     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16593     * Each MeasureSpec represents a requirement for either the width or the height.
16594     * A MeasureSpec is comprised of a size and a mode. There are three possible
16595     * modes:
16596     * <dl>
16597     * <dt>UNSPECIFIED</dt>
16598     * <dd>
16599     * The parent has not imposed any constraint on the child. It can be whatever size
16600     * it wants.
16601     * </dd>
16602     *
16603     * <dt>EXACTLY</dt>
16604     * <dd>
16605     * The parent has determined an exact size for the child. The child is going to be
16606     * given those bounds regardless of how big it wants to be.
16607     * </dd>
16608     *
16609     * <dt>AT_MOST</dt>
16610     * <dd>
16611     * The child can be as large as it wants up to the specified size.
16612     * </dd>
16613     * </dl>
16614     *
16615     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16616     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16617     */
16618    public static class MeasureSpec {
16619        private static final int MODE_SHIFT = 30;
16620        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16621
16622        /**
16623         * Measure specification mode: The parent has not imposed any constraint
16624         * on the child. It can be whatever size it wants.
16625         */
16626        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16627
16628        /**
16629         * Measure specification mode: The parent has determined an exact size
16630         * for the child. The child is going to be given those bounds regardless
16631         * of how big it wants to be.
16632         */
16633        public static final int EXACTLY     = 1 << MODE_SHIFT;
16634
16635        /**
16636         * Measure specification mode: The child can be as large as it wants up
16637         * to the specified size.
16638         */
16639        public static final int AT_MOST     = 2 << MODE_SHIFT;
16640
16641        /**
16642         * Creates a measure specification based on the supplied size and mode.
16643         *
16644         * The mode must always be one of the following:
16645         * <ul>
16646         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16647         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16648         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16649         * </ul>
16650         *
16651         * @param size the size of the measure specification
16652         * @param mode the mode of the measure specification
16653         * @return the measure specification based on size and mode
16654         */
16655        public static int makeMeasureSpec(int size, int mode) {
16656            return size + mode;
16657        }
16658
16659        /**
16660         * Extracts the mode from the supplied measure specification.
16661         *
16662         * @param measureSpec the measure specification to extract the mode from
16663         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16664         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16665         *         {@link android.view.View.MeasureSpec#EXACTLY}
16666         */
16667        public static int getMode(int measureSpec) {
16668            return (measureSpec & MODE_MASK);
16669        }
16670
16671        /**
16672         * Extracts the size from the supplied measure specification.
16673         *
16674         * @param measureSpec the measure specification to extract the size from
16675         * @return the size in pixels defined in the supplied measure specification
16676         */
16677        public static int getSize(int measureSpec) {
16678            return (measureSpec & ~MODE_MASK);
16679        }
16680
16681        /**
16682         * Returns a String representation of the specified measure
16683         * specification.
16684         *
16685         * @param measureSpec the measure specification to convert to a String
16686         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16687         */
16688        public static String toString(int measureSpec) {
16689            int mode = getMode(measureSpec);
16690            int size = getSize(measureSpec);
16691
16692            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16693
16694            if (mode == UNSPECIFIED)
16695                sb.append("UNSPECIFIED ");
16696            else if (mode == EXACTLY)
16697                sb.append("EXACTLY ");
16698            else if (mode == AT_MOST)
16699                sb.append("AT_MOST ");
16700            else
16701                sb.append(mode).append(" ");
16702
16703            sb.append(size);
16704            return sb.toString();
16705        }
16706    }
16707
16708    class CheckForLongPress implements Runnable {
16709
16710        private int mOriginalWindowAttachCount;
16711
16712        public void run() {
16713            if (isPressed() && (mParent != null)
16714                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16715                if (performLongClick()) {
16716                    mHasPerformedLongPress = true;
16717                }
16718            }
16719        }
16720
16721        public void rememberWindowAttachCount() {
16722            mOriginalWindowAttachCount = mWindowAttachCount;
16723        }
16724    }
16725
16726    private final class CheckForTap implements Runnable {
16727        public void run() {
16728            mPrivateFlags &= ~PREPRESSED;
16729            setPressed(true);
16730            checkForLongClick(ViewConfiguration.getTapTimeout());
16731        }
16732    }
16733
16734    private final class PerformClick implements Runnable {
16735        public void run() {
16736            performClick();
16737        }
16738    }
16739
16740    /** @hide */
16741    public void hackTurnOffWindowResizeAnim(boolean off) {
16742        mAttachInfo.mTurnOffWindowResizeAnim = off;
16743    }
16744
16745    /**
16746     * This method returns a ViewPropertyAnimator object, which can be used to animate
16747     * specific properties on this View.
16748     *
16749     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16750     */
16751    public ViewPropertyAnimator animate() {
16752        if (mAnimator == null) {
16753            mAnimator = new ViewPropertyAnimator(this);
16754        }
16755        return mAnimator;
16756    }
16757
16758    /**
16759     * Interface definition for a callback to be invoked when a hardware key event is
16760     * dispatched to this view. The callback will be invoked before the key event is
16761     * given to the view. This is only useful for hardware keyboards; a software input
16762     * method has no obligation to trigger this listener.
16763     */
16764    public interface OnKeyListener {
16765        /**
16766         * Called when a hardware key is dispatched to a view. This allows listeners to
16767         * get a chance to respond before the target view.
16768         * <p>Key presses in software keyboards will generally NOT trigger this method,
16769         * although some may elect to do so in some situations. Do not assume a
16770         * software input method has to be key-based; even if it is, it may use key presses
16771         * in a different way than you expect, so there is no way to reliably catch soft
16772         * input key presses.
16773         *
16774         * @param v The view the key has been dispatched to.
16775         * @param keyCode The code for the physical key that was pressed
16776         * @param event The KeyEvent object containing full information about
16777         *        the event.
16778         * @return True if the listener has consumed the event, false otherwise.
16779         */
16780        boolean onKey(View v, int keyCode, KeyEvent event);
16781    }
16782
16783    /**
16784     * Interface definition for a callback to be invoked when a touch event is
16785     * dispatched to this view. The callback will be invoked before the touch
16786     * event is given to the view.
16787     */
16788    public interface OnTouchListener {
16789        /**
16790         * Called when a touch event is dispatched to a view. This allows listeners to
16791         * get a chance to respond before the target view.
16792         *
16793         * @param v The view the touch event has been dispatched to.
16794         * @param event The MotionEvent object containing full information about
16795         *        the event.
16796         * @return True if the listener has consumed the event, false otherwise.
16797         */
16798        boolean onTouch(View v, MotionEvent event);
16799    }
16800
16801    /**
16802     * Interface definition for a callback to be invoked when a hover event is
16803     * dispatched to this view. The callback will be invoked before the hover
16804     * event is given to the view.
16805     */
16806    public interface OnHoverListener {
16807        /**
16808         * Called when a hover event is dispatched to a view. This allows listeners to
16809         * get a chance to respond before the target view.
16810         *
16811         * @param v The view the hover event has been dispatched to.
16812         * @param event The MotionEvent object containing full information about
16813         *        the event.
16814         * @return True if the listener has consumed the event, false otherwise.
16815         */
16816        boolean onHover(View v, MotionEvent event);
16817    }
16818
16819    /**
16820     * Interface definition for a callback to be invoked when a generic motion event is
16821     * dispatched to this view. The callback will be invoked before the generic motion
16822     * event is given to the view.
16823     */
16824    public interface OnGenericMotionListener {
16825        /**
16826         * Called when a generic motion event is dispatched to a view. This allows listeners to
16827         * get a chance to respond before the target view.
16828         *
16829         * @param v The view the generic motion event has been dispatched to.
16830         * @param event The MotionEvent object containing full information about
16831         *        the event.
16832         * @return True if the listener has consumed the event, false otherwise.
16833         */
16834        boolean onGenericMotion(View v, MotionEvent event);
16835    }
16836
16837    /**
16838     * Interface definition for a callback to be invoked when a view has been clicked and held.
16839     */
16840    public interface OnLongClickListener {
16841        /**
16842         * Called when a view has been clicked and held.
16843         *
16844         * @param v The view that was clicked and held.
16845         *
16846         * @return true if the callback consumed the long click, false otherwise.
16847         */
16848        boolean onLongClick(View v);
16849    }
16850
16851    /**
16852     * Interface definition for a callback to be invoked when a drag is being dispatched
16853     * to this view.  The callback will be invoked before the hosting view's own
16854     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16855     * onDrag(event) behavior, it should return 'false' from this callback.
16856     *
16857     * <div class="special reference">
16858     * <h3>Developer Guides</h3>
16859     * <p>For a guide to implementing drag and drop features, read the
16860     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16861     * </div>
16862     */
16863    public interface OnDragListener {
16864        /**
16865         * Called when a drag event is dispatched to a view. This allows listeners
16866         * to get a chance to override base View behavior.
16867         *
16868         * @param v The View that received the drag event.
16869         * @param event The {@link android.view.DragEvent} object for the drag event.
16870         * @return {@code true} if the drag event was handled successfully, or {@code false}
16871         * if the drag event was not handled. Note that {@code false} will trigger the View
16872         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16873         */
16874        boolean onDrag(View v, DragEvent event);
16875    }
16876
16877    /**
16878     * Interface definition for a callback to be invoked when the focus state of
16879     * a view changed.
16880     */
16881    public interface OnFocusChangeListener {
16882        /**
16883         * Called when the focus state of a view has changed.
16884         *
16885         * @param v The view whose state has changed.
16886         * @param hasFocus The new focus state of v.
16887         */
16888        void onFocusChange(View v, boolean hasFocus);
16889    }
16890
16891    /**
16892     * Interface definition for a callback to be invoked when a view is clicked.
16893     */
16894    public interface OnClickListener {
16895        /**
16896         * Called when a view has been clicked.
16897         *
16898         * @param v The view that was clicked.
16899         */
16900        void onClick(View v);
16901    }
16902
16903    /**
16904     * Interface definition for a callback to be invoked when the context menu
16905     * for this view is being built.
16906     */
16907    public interface OnCreateContextMenuListener {
16908        /**
16909         * Called when the context menu for this view is being built. It is not
16910         * safe to hold onto the menu after this method returns.
16911         *
16912         * @param menu The context menu that is being built
16913         * @param v The view for which the context menu is being built
16914         * @param menuInfo Extra information about the item for which the
16915         *            context menu should be shown. This information will vary
16916         *            depending on the class of v.
16917         */
16918        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16919    }
16920
16921    /**
16922     * Interface definition for a callback to be invoked when the status bar changes
16923     * visibility.  This reports <strong>global</strong> changes to the system UI
16924     * state, not what the application is requesting.
16925     *
16926     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16927     */
16928    public interface OnSystemUiVisibilityChangeListener {
16929        /**
16930         * Called when the status bar changes visibility because of a call to
16931         * {@link View#setSystemUiVisibility(int)}.
16932         *
16933         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16934         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
16935         * This tells you the <strong>global</strong> state of these UI visibility
16936         * flags, not what your app is currently applying.
16937         */
16938        public void onSystemUiVisibilityChange(int visibility);
16939    }
16940
16941    /**
16942     * Interface definition for a callback to be invoked when this view is attached
16943     * or detached from its window.
16944     */
16945    public interface OnAttachStateChangeListener {
16946        /**
16947         * Called when the view is attached to a window.
16948         * @param v The view that was attached
16949         */
16950        public void onViewAttachedToWindow(View v);
16951        /**
16952         * Called when the view is detached from a window.
16953         * @param v The view that was detached
16954         */
16955        public void onViewDetachedFromWindow(View v);
16956    }
16957
16958    private final class UnsetPressedState implements Runnable {
16959        public void run() {
16960            setPressed(false);
16961        }
16962    }
16963
16964    /**
16965     * Base class for derived classes that want to save and restore their own
16966     * state in {@link android.view.View#onSaveInstanceState()}.
16967     */
16968    public static class BaseSavedState extends AbsSavedState {
16969        /**
16970         * Constructor used when reading from a parcel. Reads the state of the superclass.
16971         *
16972         * @param source
16973         */
16974        public BaseSavedState(Parcel source) {
16975            super(source);
16976        }
16977
16978        /**
16979         * Constructor called by derived classes when creating their SavedState objects
16980         *
16981         * @param superState The state of the superclass of this view
16982         */
16983        public BaseSavedState(Parcelable superState) {
16984            super(superState);
16985        }
16986
16987        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16988                new Parcelable.Creator<BaseSavedState>() {
16989            public BaseSavedState createFromParcel(Parcel in) {
16990                return new BaseSavedState(in);
16991            }
16992
16993            public BaseSavedState[] newArray(int size) {
16994                return new BaseSavedState[size];
16995            }
16996        };
16997    }
16998
16999    /**
17000     * A set of information given to a view when it is attached to its parent
17001     * window.
17002     */
17003    static class AttachInfo {
17004        interface Callbacks {
17005            void playSoundEffect(int effectId);
17006            boolean performHapticFeedback(int effectId, boolean always);
17007        }
17008
17009        /**
17010         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17011         * to a Handler. This class contains the target (View) to invalidate and
17012         * the coordinates of the dirty rectangle.
17013         *
17014         * For performance purposes, this class also implements a pool of up to
17015         * POOL_LIMIT objects that get reused. This reduces memory allocations
17016         * whenever possible.
17017         */
17018        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17019            private static final int POOL_LIMIT = 10;
17020            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17021                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17022                        public InvalidateInfo newInstance() {
17023                            return new InvalidateInfo();
17024                        }
17025
17026                        public void onAcquired(InvalidateInfo element) {
17027                        }
17028
17029                        public void onReleased(InvalidateInfo element) {
17030                            element.target = null;
17031                        }
17032                    }, POOL_LIMIT)
17033            );
17034
17035            private InvalidateInfo mNext;
17036            private boolean mIsPooled;
17037
17038            View target;
17039
17040            int left;
17041            int top;
17042            int right;
17043            int bottom;
17044
17045            public void setNextPoolable(InvalidateInfo element) {
17046                mNext = element;
17047            }
17048
17049            public InvalidateInfo getNextPoolable() {
17050                return mNext;
17051            }
17052
17053            static InvalidateInfo acquire() {
17054                return sPool.acquire();
17055            }
17056
17057            void release() {
17058                sPool.release(this);
17059            }
17060
17061            public boolean isPooled() {
17062                return mIsPooled;
17063            }
17064
17065            public void setPooled(boolean isPooled) {
17066                mIsPooled = isPooled;
17067            }
17068        }
17069
17070        final IWindowSession mSession;
17071
17072        final IWindow mWindow;
17073
17074        final IBinder mWindowToken;
17075
17076        final Callbacks mRootCallbacks;
17077
17078        HardwareCanvas mHardwareCanvas;
17079
17080        /**
17081         * The top view of the hierarchy.
17082         */
17083        View mRootView;
17084
17085        IBinder mPanelParentWindowToken;
17086        Surface mSurface;
17087
17088        boolean mHardwareAccelerated;
17089        boolean mHardwareAccelerationRequested;
17090        HardwareRenderer mHardwareRenderer;
17091
17092        boolean mScreenOn;
17093
17094        /**
17095         * Scale factor used by the compatibility mode
17096         */
17097        float mApplicationScale;
17098
17099        /**
17100         * Indicates whether the application is in compatibility mode
17101         */
17102        boolean mScalingRequired;
17103
17104        /**
17105         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17106         */
17107        boolean mTurnOffWindowResizeAnim;
17108
17109        /**
17110         * Left position of this view's window
17111         */
17112        int mWindowLeft;
17113
17114        /**
17115         * Top position of this view's window
17116         */
17117        int mWindowTop;
17118
17119        /**
17120         * Left actual position of this view's window.
17121         *
17122         * TODO: This is a workaround for 6623031. Remove when fixed.
17123         */
17124        int mActualWindowLeft;
17125
17126        /**
17127         * Actual top position of this view's window.
17128         *
17129         * TODO: This is a workaround for 6623031. Remove when fixed.
17130         */
17131        int mActualWindowTop;
17132
17133        /**
17134         * Indicates whether views need to use 32-bit drawing caches
17135         */
17136        boolean mUse32BitDrawingCache;
17137
17138        /**
17139         * For windows that are full-screen but using insets to layout inside
17140         * of the screen decorations, these are the current insets for the
17141         * content of the window.
17142         */
17143        final Rect mContentInsets = new Rect();
17144
17145        /**
17146         * For windows that are full-screen but using insets to layout inside
17147         * of the screen decorations, these are the current insets for the
17148         * actual visible parts of the window.
17149         */
17150        final Rect mVisibleInsets = new Rect();
17151
17152        /**
17153         * The internal insets given by this window.  This value is
17154         * supplied by the client (through
17155         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17156         * be given to the window manager when changed to be used in laying
17157         * out windows behind it.
17158         */
17159        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17160                = new ViewTreeObserver.InternalInsetsInfo();
17161
17162        /**
17163         * All views in the window's hierarchy that serve as scroll containers,
17164         * used to determine if the window can be resized or must be panned
17165         * to adjust for a soft input area.
17166         */
17167        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17168
17169        final KeyEvent.DispatcherState mKeyDispatchState
17170                = new KeyEvent.DispatcherState();
17171
17172        /**
17173         * Indicates whether the view's window currently has the focus.
17174         */
17175        boolean mHasWindowFocus;
17176
17177        /**
17178         * The current visibility of the window.
17179         */
17180        int mWindowVisibility;
17181
17182        /**
17183         * Indicates the time at which drawing started to occur.
17184         */
17185        long mDrawingTime;
17186
17187        /**
17188         * Indicates whether or not ignoring the DIRTY_MASK flags.
17189         */
17190        boolean mIgnoreDirtyState;
17191
17192        /**
17193         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17194         * to avoid clearing that flag prematurely.
17195         */
17196        boolean mSetIgnoreDirtyState = false;
17197
17198        /**
17199         * Indicates whether the view's window is currently in touch mode.
17200         */
17201        boolean mInTouchMode;
17202
17203        /**
17204         * Indicates that ViewAncestor should trigger a global layout change
17205         * the next time it performs a traversal
17206         */
17207        boolean mRecomputeGlobalAttributes;
17208
17209        /**
17210         * Always report new attributes at next traversal.
17211         */
17212        boolean mForceReportNewAttributes;
17213
17214        /**
17215         * Set during a traveral if any views want to keep the screen on.
17216         */
17217        boolean mKeepScreenOn;
17218
17219        /**
17220         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17221         */
17222        int mSystemUiVisibility;
17223
17224        /**
17225         * Hack to force certain system UI visibility flags to be cleared.
17226         */
17227        int mDisabledSystemUiVisibility;
17228
17229        /**
17230         * Last global system UI visibility reported by the window manager.
17231         */
17232        int mGlobalSystemUiVisibility;
17233
17234        /**
17235         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17236         * attached.
17237         */
17238        boolean mHasSystemUiListeners;
17239
17240        /**
17241         * Set if the visibility of any views has changed.
17242         */
17243        boolean mViewVisibilityChanged;
17244
17245        /**
17246         * Set to true if a view has been scrolled.
17247         */
17248        boolean mViewScrollChanged;
17249
17250        /**
17251         * Global to the view hierarchy used as a temporary for dealing with
17252         * x/y points in the transparent region computations.
17253         */
17254        final int[] mTransparentLocation = new int[2];
17255
17256        /**
17257         * Global to the view hierarchy used as a temporary for dealing with
17258         * x/y points in the ViewGroup.invalidateChild implementation.
17259         */
17260        final int[] mInvalidateChildLocation = new int[2];
17261
17262
17263        /**
17264         * Global to the view hierarchy used as a temporary for dealing with
17265         * x/y location when view is transformed.
17266         */
17267        final float[] mTmpTransformLocation = new float[2];
17268
17269        /**
17270         * The view tree observer used to dispatch global events like
17271         * layout, pre-draw, touch mode change, etc.
17272         */
17273        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17274
17275        /**
17276         * A Canvas used by the view hierarchy to perform bitmap caching.
17277         */
17278        Canvas mCanvas;
17279
17280        /**
17281         * The view root impl.
17282         */
17283        final ViewRootImpl mViewRootImpl;
17284
17285        /**
17286         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17287         * handler can be used to pump events in the UI events queue.
17288         */
17289        final Handler mHandler;
17290
17291        /**
17292         * Temporary for use in computing invalidate rectangles while
17293         * calling up the hierarchy.
17294         */
17295        final Rect mTmpInvalRect = new Rect();
17296
17297        /**
17298         * Temporary for use in computing hit areas with transformed views
17299         */
17300        final RectF mTmpTransformRect = new RectF();
17301
17302        /**
17303         * Temporary list for use in collecting focusable descendents of a view.
17304         */
17305        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17306
17307        /**
17308         * The id of the window for accessibility purposes.
17309         */
17310        int mAccessibilityWindowId = View.NO_ID;
17311
17312        /**
17313         * Whether to ingore not exposed for accessibility Views when
17314         * reporting the view tree to accessibility services.
17315         */
17316        boolean mIncludeNotImportantViews;
17317
17318        /**
17319         * The drawable for highlighting accessibility focus.
17320         */
17321        Drawable mAccessibilityFocusDrawable;
17322
17323        /**
17324         * Show where the margins, bounds and layout bounds are for each view.
17325         */
17326        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17327
17328        /**
17329         * Point used to compute visible regions.
17330         */
17331        final Point mPoint = new Point();
17332
17333        /**
17334         * Creates a new set of attachment information with the specified
17335         * events handler and thread.
17336         *
17337         * @param handler the events handler the view must use
17338         */
17339        AttachInfo(IWindowSession session, IWindow window,
17340                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17341            mSession = session;
17342            mWindow = window;
17343            mWindowToken = window.asBinder();
17344            mViewRootImpl = viewRootImpl;
17345            mHandler = handler;
17346            mRootCallbacks = effectPlayer;
17347        }
17348    }
17349
17350    /**
17351     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17352     * is supported. This avoids keeping too many unused fields in most
17353     * instances of View.</p>
17354     */
17355    private static class ScrollabilityCache implements Runnable {
17356
17357        /**
17358         * Scrollbars are not visible
17359         */
17360        public static final int OFF = 0;
17361
17362        /**
17363         * Scrollbars are visible
17364         */
17365        public static final int ON = 1;
17366
17367        /**
17368         * Scrollbars are fading away
17369         */
17370        public static final int FADING = 2;
17371
17372        public boolean fadeScrollBars;
17373
17374        public int fadingEdgeLength;
17375        public int scrollBarDefaultDelayBeforeFade;
17376        public int scrollBarFadeDuration;
17377
17378        public int scrollBarSize;
17379        public ScrollBarDrawable scrollBar;
17380        public float[] interpolatorValues;
17381        public View host;
17382
17383        public final Paint paint;
17384        public final Matrix matrix;
17385        public Shader shader;
17386
17387        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17388
17389        private static final float[] OPAQUE = { 255 };
17390        private static final float[] TRANSPARENT = { 0.0f };
17391
17392        /**
17393         * When fading should start. This time moves into the future every time
17394         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17395         */
17396        public long fadeStartTime;
17397
17398
17399        /**
17400         * The current state of the scrollbars: ON, OFF, or FADING
17401         */
17402        public int state = OFF;
17403
17404        private int mLastColor;
17405
17406        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17407            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17408            scrollBarSize = configuration.getScaledScrollBarSize();
17409            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17410            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17411
17412            paint = new Paint();
17413            matrix = new Matrix();
17414            // use use a height of 1, and then wack the matrix each time we
17415            // actually use it.
17416            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17417
17418            paint.setShader(shader);
17419            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17420            this.host = host;
17421        }
17422
17423        public void setFadeColor(int color) {
17424            if (color != 0 && color != mLastColor) {
17425                mLastColor = color;
17426                color |= 0xFF000000;
17427
17428                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17429                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17430
17431                paint.setShader(shader);
17432                // Restore the default transfer mode (src_over)
17433                paint.setXfermode(null);
17434            }
17435        }
17436
17437        public void run() {
17438            long now = AnimationUtils.currentAnimationTimeMillis();
17439            if (now >= fadeStartTime) {
17440
17441                // the animation fades the scrollbars out by changing
17442                // the opacity (alpha) from fully opaque to fully
17443                // transparent
17444                int nextFrame = (int) now;
17445                int framesCount = 0;
17446
17447                Interpolator interpolator = scrollBarInterpolator;
17448
17449                // Start opaque
17450                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17451
17452                // End transparent
17453                nextFrame += scrollBarFadeDuration;
17454                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17455
17456                state = FADING;
17457
17458                // Kick off the fade animation
17459                host.invalidate(true);
17460            }
17461        }
17462    }
17463
17464    /**
17465     * Resuable callback for sending
17466     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17467     */
17468    private class SendViewScrolledAccessibilityEvent implements Runnable {
17469        public volatile boolean mIsPending;
17470
17471        public void run() {
17472            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17473            mIsPending = false;
17474        }
17475    }
17476
17477    /**
17478     * <p>
17479     * This class represents a delegate that can be registered in a {@link View}
17480     * to enhance accessibility support via composition rather via inheritance.
17481     * It is specifically targeted to widget developers that extend basic View
17482     * classes i.e. classes in package android.view, that would like their
17483     * applications to be backwards compatible.
17484     * </p>
17485     * <div class="special reference">
17486     * <h3>Developer Guides</h3>
17487     * <p>For more information about making applications accessible, read the
17488     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17489     * developer guide.</p>
17490     * </div>
17491     * <p>
17492     * A scenario in which a developer would like to use an accessibility delegate
17493     * is overriding a method introduced in a later API version then the minimal API
17494     * version supported by the application. For example, the method
17495     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17496     * in API version 4 when the accessibility APIs were first introduced. If a
17497     * developer would like his application to run on API version 4 devices (assuming
17498     * all other APIs used by the application are version 4 or lower) and take advantage
17499     * of this method, instead of overriding the method which would break the application's
17500     * backwards compatibility, he can override the corresponding method in this
17501     * delegate and register the delegate in the target View if the API version of
17502     * the system is high enough i.e. the API version is same or higher to the API
17503     * version that introduced
17504     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17505     * </p>
17506     * <p>
17507     * Here is an example implementation:
17508     * </p>
17509     * <code><pre><p>
17510     * if (Build.VERSION.SDK_INT >= 14) {
17511     *     // If the API version is equal of higher than the version in
17512     *     // which onInitializeAccessibilityNodeInfo was introduced we
17513     *     // register a delegate with a customized implementation.
17514     *     View view = findViewById(R.id.view_id);
17515     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17516     *         public void onInitializeAccessibilityNodeInfo(View host,
17517     *                 AccessibilityNodeInfo info) {
17518     *             // Let the default implementation populate the info.
17519     *             super.onInitializeAccessibilityNodeInfo(host, info);
17520     *             // Set some other information.
17521     *             info.setEnabled(host.isEnabled());
17522     *         }
17523     *     });
17524     * }
17525     * </code></pre></p>
17526     * <p>
17527     * This delegate contains methods that correspond to the accessibility methods
17528     * in View. If a delegate has been specified the implementation in View hands
17529     * off handling to the corresponding method in this delegate. The default
17530     * implementation the delegate methods behaves exactly as the corresponding
17531     * method in View for the case of no accessibility delegate been set. Hence,
17532     * to customize the behavior of a View method, clients can override only the
17533     * corresponding delegate method without altering the behavior of the rest
17534     * accessibility related methods of the host view.
17535     * </p>
17536     */
17537    public static class AccessibilityDelegate {
17538
17539        /**
17540         * Sends an accessibility event of the given type. If accessibility is not
17541         * enabled this method has no effect.
17542         * <p>
17543         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17544         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17545         * been set.
17546         * </p>
17547         *
17548         * @param host The View hosting the delegate.
17549         * @param eventType The type of the event to send.
17550         *
17551         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17552         */
17553        public void sendAccessibilityEvent(View host, int eventType) {
17554            host.sendAccessibilityEventInternal(eventType);
17555        }
17556
17557        /**
17558         * Performs the specified accessibility action on the view. For
17559         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17560         * <p>
17561         * The default implementation behaves as
17562         * {@link View#performAccessibilityAction(int, Bundle)
17563         *  View#performAccessibilityAction(int, Bundle)} for the case of
17564         *  no accessibility delegate been set.
17565         * </p>
17566         *
17567         * @param action The action to perform.
17568         * @return Whether the action was performed.
17569         *
17570         * @see View#performAccessibilityAction(int, Bundle)
17571         *      View#performAccessibilityAction(int, Bundle)
17572         */
17573        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17574            return host.performAccessibilityActionInternal(action, args);
17575        }
17576
17577        /**
17578         * Sends an accessibility event. This method behaves exactly as
17579         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17580         * empty {@link AccessibilityEvent} and does not perform a check whether
17581         * accessibility is enabled.
17582         * <p>
17583         * The default implementation behaves as
17584         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17585         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17586         * the case of no accessibility delegate been set.
17587         * </p>
17588         *
17589         * @param host The View hosting the delegate.
17590         * @param event The event to send.
17591         *
17592         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17593         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17594         */
17595        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17596            host.sendAccessibilityEventUncheckedInternal(event);
17597        }
17598
17599        /**
17600         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17601         * to its children for adding their text content to the event.
17602         * <p>
17603         * The default implementation behaves as
17604         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17605         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17606         * the case of no accessibility delegate been set.
17607         * </p>
17608         *
17609         * @param host The View hosting the delegate.
17610         * @param event The event.
17611         * @return True if the event population was completed.
17612         *
17613         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17614         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17615         */
17616        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17617            return host.dispatchPopulateAccessibilityEventInternal(event);
17618        }
17619
17620        /**
17621         * Gives a chance to the host View to populate the accessibility event with its
17622         * text content.
17623         * <p>
17624         * The default implementation behaves as
17625         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17626         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17627         * the case of no accessibility delegate been set.
17628         * </p>
17629         *
17630         * @param host The View hosting the delegate.
17631         * @param event The accessibility event which to populate.
17632         *
17633         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17634         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17635         */
17636        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17637            host.onPopulateAccessibilityEventInternal(event);
17638        }
17639
17640        /**
17641         * Initializes an {@link AccessibilityEvent} with information about the
17642         * the host View which is the event source.
17643         * <p>
17644         * The default implementation behaves as
17645         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17646         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17647         * the case of no accessibility delegate been set.
17648         * </p>
17649         *
17650         * @param host The View hosting the delegate.
17651         * @param event The event to initialize.
17652         *
17653         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17654         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17655         */
17656        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17657            host.onInitializeAccessibilityEventInternal(event);
17658        }
17659
17660        /**
17661         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17662         * <p>
17663         * The default implementation behaves as
17664         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17665         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17666         * the case of no accessibility delegate been set.
17667         * </p>
17668         *
17669         * @param host The View hosting the delegate.
17670         * @param info The instance to initialize.
17671         *
17672         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17673         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17674         */
17675        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17676            host.onInitializeAccessibilityNodeInfoInternal(info);
17677        }
17678
17679        /**
17680         * Called when a child of the host View has requested sending an
17681         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17682         * to augment the event.
17683         * <p>
17684         * The default implementation behaves as
17685         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17686         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17687         * the case of no accessibility delegate been set.
17688         * </p>
17689         *
17690         * @param host The View hosting the delegate.
17691         * @param child The child which requests sending the event.
17692         * @param event The event to be sent.
17693         * @return True if the event should be sent
17694         *
17695         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17696         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17697         */
17698        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17699                AccessibilityEvent event) {
17700            return host.onRequestSendAccessibilityEventInternal(child, event);
17701        }
17702
17703        /**
17704         * Gets the provider for managing a virtual view hierarchy rooted at this View
17705         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17706         * that explore the window content.
17707         * <p>
17708         * The default implementation behaves as
17709         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17710         * the case of no accessibility delegate been set.
17711         * </p>
17712         *
17713         * @return The provider.
17714         *
17715         * @see AccessibilityNodeProvider
17716         */
17717        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17718            return null;
17719        }
17720    }
17721}
17722